prettyprint

2023年2月14日 星期二

[Raspberry Pi Pico W (c-sdk)] lwIP: Ep 5. HTTP Server & WiFiManager

本文章介紹Raspberry Pi Pico W使用lwIP HTTP application建立WiFi Manager,當Pico W沒有儲存WiFi連線的SSID與Password時,啟用AP模式,並啟用HTTP與DHCP server,透過網頁設定要連線的WiFi SSID與Password,並將設定檔存在flash memory中。如下流程圖。
一、HTTP server:
lwIP的http server(HTTPD)支援簡易SSI(server-side-include)與CGI功能,另外有支援POST功能。
  • SSI ; 相對應的API:
    http_set_ssi_handler():Set the SSI handler function.
    tSSIHandler: 處理SSI tag的callback function,可使用multi part處理較長的內容。
    const char ** tags: SSI tags。
  • CGI: 相對應的API:
    http_set_cgi_handlers():Set an array of CGI filenames/handler functions。
    tCGI StructURL):指定URL與相對應的function。
  • POST: 相對應的API:
    httpd_post_begin():
    httpd_post_receive_data():每收到一個pbuf就呼叫一次。
    httpd_post_data_recved():
    httpd_post_finished():資料收完或connection close。
  • 啟用HTTPD:
    httpd_init()
  • 在lwipots.h加入下列:
    #define LWIP_HTTPD 1
    #define LWIP_HTTPD_SSI 1
    #define LWIP_HTTPD_CGI 1
    #define LWIP_HTTPD_SSI_MULTIPART 1
    #define LWIP_HTTPD_SUPPORT_POST 1
    #define LWIP_HTTPD_SSI_INCLUDE_TAG 0
    #define HTTPD_FSDATA_FILE "_fsdata.c"  //網頁檔案存放的flash memory image檔。
  • 在pico-sdk/lib/lwip/src/apps/http/makefsdata的perl檔案makefsdata用來產生fsdata.c
  • 修改makefsdata perl檔案,約在24行處,將
    if($file =~ /\.html) {
    改成
    if($file =~ /\.html$/ or $file =~ /\.shtml$/ or $file =~ /\.htm$/ or $file =~ /\.shtm$/) {
    讓.shtml副檔名的檔案,加入Content-type: text/html\r\n檔頭,成為網頁檔案。
  • 在CMakeLists.txt加入下列執行產生fsdata.c
二、WiFi scan:
須先啟用為STA或AP mode才可執行wifi scan功能。
相對應API:
cyw43_arch_enable_sta_mode() or cyw43_arch_enable_ap_mode()
  • cyw43_wifi_scan(&cyw43_state, &scan_options, aps, scan_result):啟用wifi scan並且呼叫scan_result callback function取得scan到的資料。
  • cyw43_wifi_scan_active(&cyw43_state):查看wifi scan是否以完成。
其他進一步解說,請觀看「成果影片」連結。

三、成果影片


四、程式碼:
  • cSJON: https://github.com/DaveGamble/cJSON
  • dhcpserver: pico_examples/pico_w/wifi/access_point/dhcp_server
  • makefsdata: pico-sdk/lib/lwip/src/apps/http/makefsdata
  • ap_http_server.c
 #include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "lwip/apps/httpd.h"
#include "hardware/flash.h"
#include "hardware/watchdog.h"

#include "ap_http_server.h"
#include "wifi_scan.h"
#include "dhcpserver.h"

SCAN_APS_T *aps;

dhcp_server_t dhcp_server;
#define WIFI_AP_SSID "PicoW"
#define WIFI_AP_PASSWORD "picowpwd#"

/* ==== cgi begin ======*/
const char *
cgi_handler_wifi_refresh(int iIndex, int iNumParams, char *pcParam[], char *pcValue[]) {
    
    scan_aps(aps, 20000);
    return "/index.shtml";

}

static const tCGI cgi_handlers[] = {
    {
        //* Html request for "/wifi_refresh.cgi" will start cgi_handler_wifi_refresh 
        "/wifi_refresh.cgi", cgi_handler_wifi_refresh
    },
};
/* ==== cgi end ======*/

/*===== post begin =====*/
typedef struct HTTP_POST_SERVER_T_ {
    void *current_connection;
    //void *valid_connection;
    char ssid[WIFI_PASS_BUFSIZE];
    char pass[WIFI_PASS_BUFSIZE];
    bool post_recv;
 } HTTP_POST_SERVER_T;

HTTP_POST_SERVER_T *server=NULL;

char* urldecode(char* str) {
  char tmpstr[WIFI_PASS_BUFSIZE];
  int j=0;
  int i=0;
  char tmpval[5];
  while(i < strlen(str)) {
    if (str[i] == '%') {
        sprintf(tmpval, "%s%c%c", "0x",str[i+1], str[i+2]);
        tmpstr[j] = strtol(tmpval, NULL, 16);
        i+=3;
    } else {
      tmpstr[j]=str[i];
      i++;
    }
    j++;
  }
  tmpstr[j]='\0';
  strcpy(str, tmpstr);
  return str;
}

void save_to_flash() {
  char flash_buff[256];
  flash_range_erase(FLASH_OFFSET, 4096); // one sector

  memset(flash_buff, 0, 256);
  sprintf(flash_buff, "{\"ssid\":\"%s\",\"pass\":\"%s\"}", urldecode(server->ssid), urldecode(server->pass));
  flash_range_program(FLASH_OFFSET, flash_buff, 256);   // one page

  watchdog_enable(5000, false); // after save data to flash, reboot in 5 seconds
}

err_t httpd_post_begin(void *connection, const char *uri, const char *http_request,
                 u16_t http_request_len, int content_len, char *response_uri,
                 u16_t response_uri_len, u8_t *post_auto_wnd)  {
  LWIP_UNUSED_ARG(connection);
  LWIP_UNUSED_ARG(http_request);
  LWIP_UNUSED_ARG(http_request_len);
  LWIP_UNUSED_ARG(content_len);
  LWIP_UNUSED_ARG(post_auto_wnd);
  server->post_recv=false;
  if (!memcmp(uri, "/wifi_conn.shtml", 17)) {
    if (server->current_connection != connection) {
      server->current_connection = connection;
      //server->valid_connection = NULL;
      snprintf(response_uri, response_uri_len, "/index.shtml"); // default : return main page
      /* e.g. for large uploads to slow flash over a fast connection, you should
         manually update the rx window. That way, a sender can only send a full
         tcp window at a time. If this is required, set 'post_aut_wnd' to 0.
         We do not need to throttle upload speed here, so: */
      *post_auto_wnd = 1;

      return ERR_OK;
    }
  }
  return ERR_VAL;
}

err_t httpd_post_receive_data(void *connection, struct pbuf *p) {
  err_t ret;

  LWIP_ASSERT("NULL pbuf", p != NULL);

  if (server->current_connection == connection) {
    u16_t token_ssid = pbuf_memfind(p, "ssid=", 5, 0);
    u16_t token_pass = pbuf_memfind(p, "pass=", 5, 0);
 
    if ((token_ssid != 0xFFFF) && (token_pass != 0xFFFF)) {
      u16_t value_ssid = token_ssid + 5;
      u16_t value_pass = token_pass + 5;
    
      u16_t len_ssid = 0;
      u16_t len_pass = 0;
      
      u16_t tmp;
      
      /* find ssid len */
      tmp = pbuf_memfind(p, "&", 1, value_ssid);
      if (tmp != 0xFFFF) {
        len_ssid = tmp - value_ssid;
      } else {
        len_ssid = p->tot_len - value_ssid;
      }
      /* find pass len */
      tmp = pbuf_memfind(p, "&", 1, value_pass);
      if (tmp != 0xFFFF) {
        len_pass = tmp - value_pass;
      } else {
        len_pass = p->tot_len - value_pass;
      }
      
      if ((len_ssid > 0) && (len_ssid < WIFI_PASS_BUFSIZE) &&
          (len_pass > 0) && (len_pass < WIFI_PASS_BUFSIZE) ) {
        
        char* tmpstr= (char*)pbuf_get_contiguous(p, &server->ssid, sizeof(server->ssid), len_ssid, value_ssid);
        tmpstr[len_ssid]=0;
        strcpy(server->ssid, tmpstr);
        tmpstr = (char*)pbuf_get_contiguous(p, &server->pass, sizeof(server->pass), len_pass, value_pass);
        tmpstr[len_pass]=0;
        strcpy(server->pass, tmpstr);
        server->post_recv=true;
      }
    }
    //server->valid_connection = connection;
   
    ret = ERR_OK;
  } else {
    ret = ERR_VAL;
  }

  /* this function must ALWAYS free the pbuf it is passed or it will leak memory */
  pbuf_free(p);

  return ret;
}

void httpd_post_finished(void *connection, char *response_uri, u16_t response_uri_len) {
  if (server->current_connection == connection) {
    //if (server->valid_connection == connection) {
        if (server->post_recv) {
           //save ssid & pass to fresh memory
            save_to_flash();
            snprintf(response_uri, response_uri_len, "/wifi_conn.shtml");
        } 
    //}
    server->current_connection = NULL;
    //server->valid_connection = NULL;
  }
}
/*===== post end =====*/

/*  === ssi begin =====*/
const char* __not_in_flash("httpd") ssi_tags[] = {
    "scanwifi",
    "ssid",
};

/* for scan wifi, multipart: every part for one scaned AP*/
u16_t __time_critical_func(ssi_handler)(int iIndex, char *pcInsert, int iInsertLen, u16_t current_tag_part, u16_t *next_tag_part)
{
    size_t printed;
    static char buff[500];
    char keyimg[]="<img src='img/key.png'>";
    char checked[8]="checked";
    int rssi=1;
    switch (iIndex) { 
        case 0: // for scanwifi in index.shtml
        if (aps) {
            if (current_tag_part < aps->len) {
                if (((aps->AP)+current_tag_part)->rssi > -90) rssi=2;
                if (((aps->AP)+current_tag_part)->rssi > -80) rssi=3;
                if (((aps->AP)+current_tag_part)->rssi > -70) rssi=4;
                if (((aps->AP)+current_tag_part)->auth_mode == CYW43_AUTH_OPEN) strcpy(keyimg,"");
                if (current_tag_part == 0) strcpy(checked, "checked"); else strcpy(checked, "");
                sprintf(buff, "<tr>"
                "<td>"
                "<input  type='radio' name='ssid' %s value='%s'>%s"
                "</td>"
                "<td>"
                "<img src='img/wifi%d.png'>"
                "</td>"
                "<td>%s</td></tr>", 
                checked, ((aps->AP)+current_tag_part)->ssid,((aps->AP)+current_tag_part)->ssid, rssi, keyimg);
                *next_tag_part=current_tag_part+1;
                printed = snprintf(pcInsert, iInsertLen, buff);

            } else {
                printed = snprintf(pcInsert, iInsertLen, "");
            }
        }
        break;
        case 1: // for ssid in wifi_conn.shtml
            printed = snprintf(pcInsert, iInsertLen,server->ssid);
            break;
        default: 
          printed = snprintf(pcInsert, iInsertLen, "");
    }
    return printed;
}
/*  === ssi end =====*/

void ap_http_server_start() {
     aps = (SCAN_APS_T*)calloc(1, sizeof(SCAN_APS_T));
     if (!aps) {
        printf("cannot alloc scan ap memory\n");
        return;
    }
    
    server = (HTTP_POST_SERVER_T*) calloc(1, sizeof(HTTP_POST_SERVER_T));
    if (!server) {
        printf("cannot alloc server object\n");
        return;
    }
    if (cyw43_arch_init()) {
      printf("http server cyw43_arch init error\n");
      return;
    }
    printf("Starting AP Mode: local IP:192.168.4.1\n");
    cyw43_arch_enable_ap_mode(WIFI_AP_SSID, WIFI_AP_PASSWORD, CYW43_AUTH_WPA2_AES_PSK);
    /* start dhcp server*/
    ip_addr_t gw, mask;
    IP4_ADDR(ip_2_ip4(&gw), 192, 168, 4, 1);
    IP4_ADDR(ip_2_ip4(&mask), 255, 255, 255, 0); 
    dhcp_server_init(&dhcp_server, &gw, &mask);

    scan_aps(aps, 2000);
  
    //check tag length
    size_t i;
    for (i = 0; i < LWIP_ARRAYSIZE(ssi_tags); i++) {
        LWIP_ASSERT("tag too long for LWIP_HTTPD_MAX_TAG_NAME_LEN",
                    strlen(ssi_tags[i]) <= LWIP_HTTPD_MAX_TAG_NAME_LEN);
    }
    
    http_set_ssi_handler(ssi_handler, ssi_tags, LWIP_ARRAYSIZE(ssi_tags));
    http_set_cgi_handlers(cgi_handlers, LWIP_ARRAYSIZE(cgi_handlers));

    httpd_init();
 
}

void ap_http_server_stop() {
    dhcp_server_deinit(&dhcp_server);
    free(aps);
    cyw43_arch_deinit();
}

  • ap_http_server.h
 #ifndef __HTTP_SERVER_H_
#define __HTTP_SERVER_H_

#define FLASH_OFFSET  0x180000    //1.5M
#define WIFI_PASS_BUFSIZE 91
void ap_http_server_start();
void ap_http_server_stop();
char* urldecode(char* str);

#endif

  • wifi_scan.c
#include <stdio.h>

#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "string.h"
#include "wifi_scan.h"

static int scan_result(void *env, const cyw43_ev_scan_result_t *result) {
    SCAN_APS_T *res_APs = (SCAN_APS_T*) env;
    if (result) {
        for (int i =0; i < res_APs->len; i++) {
            if (strcmp(result->ssid, ((res_APs->AP)+i)->ssid)==0) {
                if (result->rssi > ((res_APs->AP)+i)->rssi) 
                    *((res_APs->AP)+i) = *result; 
                return 0;
            }
        }
        cyw43_ev_scan_result_t *tmp = (cyw43_ev_scan_result_t*) realloc(res_APs->AP, sizeof(cyw43_ev_scan_result_t)*(res_APs->len+1));
        if (tmp) {
            res_APs->len += 1;
            res_APs->AP = tmp;
            *(res_APs->AP+res_APs->len-1) = *result;
        }
    } 
   
    return res_APs->len;
}

bool scan_aps(SCAN_APS_T* aps, uint32_t timeout) { // timeout: ms
    //cyw43_arch_enable_sta_mode() or cyw43_arch_enable_ap_mode() must be called before this function
    bool ret = false;
    aps = realloc(aps,0);
    cyw43_wifi_scan_options_t scan_options = {0};
    int err = cyw43_wifi_scan(&cyw43_state, &scan_options, aps, scan_result);
    if (err == 0) {
        printf("\nPerforming wifi scan\n");
        absolute_time_t scan_timeout = make_timeout_time_ms(timeout); // timeout
        while(absolute_time_diff_us(get_absolute_time(), scan_timeout) > 0) {
            if (!cyw43_wifi_scan_active(&cyw43_state)) {
                    //print out all scaned APs for debug
                for (int i =0; i < aps->len; i++) {
                    printf("%d.. ssid: %-32s rssi: %4d chan: %3d mac: %02x:%02x:%02x:%02x:%02x:%02x sec: %u\n",
                        i, (aps->AP+i)->ssid, (aps->AP+i)->rssi, (aps->AP+i)->channel,
                        (aps->AP+i)->bssid[0], (aps->AP+i)->bssid[1], (aps->AP+i)->bssid[2], (aps->AP+i)->bssid[3], (aps->AP+i)->bssid[4], (aps->AP+i)->bssid[5],
                        (aps->AP+i)->auth_mode);
                }
                ret = true;
                break;
            }
            cyw43_arch_poll();
            sleep_ms(1);
        }
        ret=false;
    } else {
        printf("Failed to start scan: %d\n", err);
        ret = false;
    }
    
    return ret;

}


  • wifi_scan.h
#ifndef __WIFI_SCAN_H_
#define _WIFI_SCAN_H_

#include "pico/stdlib.h"
typedef struct SCAN_APS_T_ {
    uint16_t len;
    cyw43_ev_scan_result_t *AP;
} SCAN_APS_T;

bool scan_aps(SCAN_APS_T* aps, uint32_t timeout);
#endif 

CMakeLists.txt
 # perl makefsdata 
find_package(Perl)
if(NOT PERL_FOUND)
    message(FATAL_ERROR "Perl is needed for generating the fsdata.c file")
endif()

set(MAKE_FS_DATA_SCRIPT ${CMAKE_CURRENT_LIST_DIR}/mkfsdata/makefsdata)

if (EXISTS ${MAKE_FS_DATA_SCRIPT})
    message("Find makefsdata script")
    message("Running makefsdata script")
      execute_process(COMMAND
          perl ${MAKE_FS_DATA_SCRIPT}
          WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
          ECHO_OUTPUT_VARIABLE
          ECHO_ERROR_VARIABLE
        )
    file(RENAME fsdata.c _fsdata.c)
endif()

# Generated Cmake Pico project file
cmake_minimum_required(VERSION 3.13)

set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

# Initialise pico_sdk from installed location
# (note this can come from environment, CMake cache etc)
set(PICO_SDK_PATH "/home/duser/pico/pico-sdk")

set(PICO_BOARD pico_w CACHE STRING "Board type")

# Pull in Raspberry Pi Pico SDK (must be before project)
include(pico_sdk_import.cmake)

if (PICO_SDK_VERSION_STRING VERSION_LESS "1.5.0")
  message(FATAL_ERROR "Raspberry Pi Pico SDK version 1.5.0 (or later) required. Your version is ${PICO_SDK_VERSION_STRING}")
endif()

project(picow_wifimanager C CXX ASM)

# Initialise the Raspberry Pi Pico SDK
pico_sdk_init()

# Add executable. Default name is the project name, version 0.1

add_executable(picow_wifimanager 
  picow_wifimanager.c 
    wifi_scan/wifi_scan.c 
    ap_http_server/ap_http_server.c 
    cJSON/cJSON.c
    dhcpserver/dhcpserver.c
    )

pico_set_program_name(picow_wifimanager "picow_wifimanager")
pico_set_program_version(picow_wifimanager "0.1")

pico_enable_stdio_uart(picow_wifimanager 1)
pico_enable_stdio_usb(picow_wifimanager 0)

# Add the standard library to the build
target_link_libraries(picow_wifimanager
        pico_stdlib)

# Add the standard include files to the build
target_include_directories(picow_wifimanager PRIVATE
  ${CMAKE_CURRENT_LIST_DIR}
  ${CMAKE_CURRENT_LIST_DIR}/.. # for our common lwipopts or any other standard includes, if required
  ${CMAKE_CURRENT_LIST_DIR}/dhcpserver
  ${CMAKE_CURRENT_LIST_DIR}/cJSON 
  ${CMAKE_CURRENT_LIST_DIR}/ap_http_server
  ${CMAKE_CURRENT_LIST_DIR}/wifi_scan

)

# Add any user requested libraries
target_link_libraries(picow_wifimanager
        pico_cyw43_arch_lwip_poll
        pico_lwip_http
        hardware_flash
        hardware_watchdog
        )

pico_add_extra_outputs(picow_wifimanager)
  • picow_wifimanager.c
 #include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "lwip/apps/httpd.h"
#include "ap_http_server.h"
#include "cJSON.h"


bool connect_to_wifi_ssid() {

    char flash_buff[256];
    memset(flash_buff,0,256);
    snprintf(flash_buff, 256, "%s",(uint8_t*)(XIP_BASE+FLASH_OFFSET));
    if (!flash_buff) return false;
    cJSON *ssid_pass = cJSON_CreateObject();
    char *ssid;
    char *pass;
    ssid_pass = cJSON_Parse(flash_buff);
    if (ssid_pass) {
        ssid = cJSON_GetStringValue(cJSON_GetObjectItem(ssid_pass, "ssid"));
        pass = cJSON_GetStringValue(cJSON_GetObjectItem(ssid_pass, "pass"));
        
        if (cyw43_arch_init()) {
            printf("cyw43_arch init error\n");
            return false;
        }
        cyw43_arch_enable_sta_mode();
        printf("\n\n==========================\n"
            "Connecting to WiFi:%s\n"
                "==============================\n", ssid);
        if (cyw43_arch_wifi_connect_timeout_ms(ssid, pass, CYW43_AUTH_WPA2_AES_PSK, 10000)) { 
            printf("wifi sta connect error ssid:%s\n", ssid);
            cyw43_arch_deinit();
            return false;
        }
    } else {
        return false;
    }
    cJSON_Delete(ssid_pass);
    
    ip_addr_t addr = cyw43_state.netif->ip_addr;
    printf("connect successfully. get IP: %s\n", ipaddr_ntoa(&addr));
    return true;
}

int main()
{
    stdio_init_all();
    bool ap_mode=false;
    if (!connect_to_wifi_ssid()) {
        ap_mode=true;
        ap_http_server_start();
    }

    while(1) {
        static absolute_time_t led_time;
        static int led_on = true;
        if (absolute_time_diff_us(get_absolute_time(), led_time) < 0) {
            if (ap_mode) { 
                led_on = !led_on;
            }
            cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, led_on);
            led_time = make_timeout_time_ms(1000);
        }
        cyw43_arch_poll();
        sleep_ms(1);
    }
   
    ap_http_server_stop();
    return 0;
}
  • index.shtml
<!DOCTYPE html>
<html>
    <head> <title>Pico W WiFi Manager</title> 
    <style>
        h1 { font-size: 70px;}
        table {width:600px; margin:auto}
        img {height:35px;}
        td {padding:8px;font-size:40px;}
        p {font-size: 50px;}
        tr:hover {background-color: coral;}
        input[type="radio"] {
            height:40px;
            width:40px;
        }
                
    </style>
    </head>
    <body> <h1>Pico W WiFi Manager</h1>
        <p>Please select a SSID:</p>
        <form method="post" action="/wifi_conn.shtml">

        <table>
            <!--#scanwifi-->
        </table>  
        <p align="center">        
            Password:<input style="height:40px;width:300px;font-size: 35px;" type="password" name="pass" required maxlength="30"> </p>
        <p align="center"> 
            <input style="height:70px;width:250px;font-size: 40px;" type="submit" name="button" value="Save">&nbsp&nbsp&nbsp&nbsp
            <input style="height:70px;width:250px;font-size: 40px;" type="button" name="refresh" value="Refresh" onclick="window.location.href='wifi_refresh.cgi'">
        </p>
        
        </form>       
   </body>
</html>
  • wifi_conn.shtml
<!DOCTYPE html>
<html>
    <head>
        <title>
            Pico W WiFi Manager
        </title>
    </head>
    <body>
        <p style="font-size: 45px;">Connecting to ssid: <!--#ssid--> </p>
        <p style="font-size: 35px;color:red;">The device will reboot in 5 seconds ...  </p>
    </body>
</html>
  • 404.shmtl
<html>
<head><title>lwIP - A Lightweight TCP/IP Stack</title></head>
<body bgcolor="white" text="black">

    <table width="100%">
      <tr valign="top"><td width="80">	  
	  
	</td><td width="500">	  
	  <h1>lwIP - A Lightweight TCP/IP Stack</h1>
	  <h2>404 - Page not found</h2>
	  <p>
	    Sorry, the page you are requesting was not found on this
	    server. 
	  </p>
	</td><td>
	  &nbsp;
	</td></tr>
      </table>
</body>
</html>

2023年2月7日 星期二

[Raspberry Pi Pico W (c-sdk)] lwIP: Ep 4. MQTT Client & Node-RED & Mosquitto & WS2812

 本文章介紹Raspberry Pi Pico W 使用lwIP MQTT Client 透過手機設定Pico W 上的WS2812 LED燈條展示方式。

  1. 顯示時鐘。
  2. 警示閃光。
  3. 隨機顏色、燈數與方向。
  4. 固定顏色、燈數與方向。




一、pico-sdk加入MQTT library:

pico-sdk(1.4)未將lwip MQTT client application llibrary加入,為了使用lwIP MQTT Client library修正下列檔案加入MQTT Client library。

(註:Pico SDK 1.5.0 已經加入了)

pico-sdk/src/rp2-common/pico_lwip/CMakeLists.txt:

#MQTT 

    add_library(pico_lwip_mqtt INTERFACE)
    target_sources(pico_lwip_mqtt INTERFACE
            ${PICO_LWIP_PATH}/src/apps/mqtt/mqtt.c
            )

如下圖所示:

在project CMakeLists.txt加入pico_lwip_mqtt library。


二、WS2812 LED燈條:

根據Datasheet每個bit 0 & 1 timer,使用raspberry Pi Pico PIO的時間如下圖:

WS2812的  Send data at speeds of 800Kbps. PIO clock如下設定。

ws2812_program_init(pio, sm, WS2812_PIN, 800000);


三、lwIP MQTT Clinet Appliction:
Subscribe API:
    mqtt_sub_unsub(): subscribe or unsubscribe MQTT topic。
    mqtt_set_inpub_callback():設定callback function,接收subscribe的topic&message。
    mqtt_incoming_publish_cb_t: callback function 接收topic 與total length。
    mqtt_incoming_data_cb_t: callback funcion 接收subscibe data。
Publish API:
    mqtt_publish(): publish a topic message。
Connection API:
    mqtt_client_connect(): connect to MQTT server。設定connected callback。
    mqtt_connection_cb_t: connect callback function,mqtt_connection_status_t 參數為連線狀態。

四、MQTT Server & Node-RED

    請參閱下列連結進一步說明:



五、成果影片:




六、程式碼:

  • Pi Pico W
 #include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pio.h"
#include "pico/cyw43_arch.h"
#include "hardware/rtc.h"

#include "lwip/apps/mqtt.h"
#include "ws2812.pio.h"
#include "hardware/clocks.h"
#include "ntp_time.h"
#include "cJSON.h"

#define WIFI_SSID "your_SSID"
#define WIFI_PASSWORD "your_PASSWORD"

typedef struct MQTT_CLIENT_DATA_T_ {
    mqtt_client_t* mqtt_client_inst;
    struct mqtt_connect_client_info_t mqtt_client_info;
    uint8_t data[MQTT_OUTPUT_RINGBUF_SIZE];
    uint8_t topic[100];
    uint32_t len;
    bool playing;
    bool newTopic;
} MQTT_CLIENT_DATA_T;

MQTT_CLIENT_DATA_T *mqtt;

struct mqtt_connect_client_info_t mqtt_client_info=
{
  "ws2812",
  NULL, /* user */
  NULL, /* pass */
  0,  /* keep alive */
  NULL, /* will_topic */
  NULL, /* will_msg */
  0,    /* will_qos */
  0     /* will_retain */
#if LWIP_ALTCP && LWIP_ALTCP_TLS
  , NULL
#endif
};

#define NUM_PIXELS 60
#define WS2812_PIN 16

#define green 0xff0000
#define red 0x00ff00
#define blue 0x0000ff
uint32_t color_pixel[NUM_PIXELS];
repeating_timer_t colok_timer;

static inline void ws2812_program_init(PIO pio, uint sm, uint pin, float freq) {
    pio_gpio_init(pio, pin);
    pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true);

    uint offset = pio_add_program(pio, &ws2812_program);

    pio_sm_config c = ws2812_program_get_default_config(offset);
    sm_config_set_sideset_pins(&c, pin);
    sm_config_set_out_shift(&c, false, true, 24);
    sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX);

    int cycles_per_bit = ws2812_T1 + ws2812_T2 *2;
    float div = clock_get_hz(clk_sys) / (freq * cycles_per_bit);
    sm_config_set_clkdiv(&c, div);

    pio_sm_init(pio, sm, offset, &c);
    pio_sm_set_enabled(pio, sm, true);
}

static inline void put_pixel(uint32_t pixel_grb) {
    pio_sm_put_blocking(pio0, 0, pixel_grb << 8u);
}

static inline uint32_t urgb_u32(uint8_t r, uint8_t g, uint8_t b) {
    return
            ((uint32_t) (r) << 8) |
            ((uint32_t) (g) << 16) |
            (uint32_t) (b);
}

void wait_connecting() {
    for (int i = 0; i < NUM_PIXELS; i++) put_pixel(red);
}

void clear_pixel() {
    for (int i = 0; i < NUM_PIXELS; i++) put_pixel(0x000000);
}

void connected() {
    for (int i = 0; i < NUM_PIXELS; i++) put_pixel(green);
}

void random_pixel(uint8_t color_index, uint len,  int dir, uint32_t color, uint8_t speed) {
    static uint t=0;

    while(mqtt->playing) { 
        if (len > NUM_PIXELS) len = NUM_PIXELS;
            for (int i=0; i < NUM_PIXELS; i++) color_pixel[i] = 0x000000;  // reset all pixel

            for (int i = t; i < (t+len);++i) {
                switch (color_index) {
                    case 1:
                    color_pixel[(i)%NUM_PIXELS]=color;
                    break;
                    case 2:
                    color_pixel[(i)%NUM_PIXELS] = (rand());
                    break;
                }
            }
            
        for (int i = 0; i < NUM_PIXELS; i++) put_pixel(color_pixel[i]);
        t = (t+dir+NUM_PIXELS) % NUM_PIXELS;
        sleep_ms(10*speed);
    }
    clear_pixel();
}

bool repeat_timer_cb(repeating_timer_t *rt) {
    static datetime_t dt;
  
    rtc_get_datetime(&dt);

    for (int i=0; i < NUM_PIXELS; i++) color_pixel[i]=0x000000;
    color_pixel[(dt.hour%12)*5] |= green;
    color_pixel[dt.min] |= blue;
    color_pixel[dt.sec] |= red;
    
    for (int i=0; i < NUM_PIXELS; i++) put_pixel(color_pixel[i]);
      
    return true;
}

void sparkle() {

      while(mqtt->playing) {
          for (int i = 0; i < NUM_PIXELS; ++i)
              put_pixel(rand() % 32 ? 0 : 0xffffffff);
          sleep_ms(10);
      }

}

void ws2812_action() {
    
    cancel_repeating_timer(&colok_timer);
    cJSON* json_obj = cJSON_CreateObject();
    json_obj = cJSON_Parse(mqtt->data);
    uint8_t *type = cJSON_GetStringValue(cJSON_GetObjectItem(json_obj, "type"));
    uint8_t speed = 11-(uint8_t)cJSON_GetNumberValue(cJSON_GetObjectItem(json_obj, "speed"));
    uint8_t length = (uint8_t)cJSON_GetNumberValue(cJSON_GetObjectItem(json_obj, "length"));
    int8_t dir = (int8_t)cJSON_GetNumberValue(cJSON_GetObjectItem(json_obj, "dir"));
    uint8_t *colorstr = (cJSON_GetStringValue(cJSON_GetObjectItem(json_obj, "color")));
    uint32_t color=strtoul(colorstr,NULL, 16);
  
    color = (color&0xff0000) >> 8 | (color&0x00ff00) << 8 | color &0x0000ff;

    if (strcmp(type, "clock") == 0) {
        mqtt->playing=true;
        add_repeating_timer_ms(-1000, repeat_timer_cb, NULL, &colok_timer);
    }
    if (strcmp(type, "sparkle") == 0) {
        mqtt->playing=true;
        sparkle();
    }
    if (strcmp(type, "randomcolor") == 0) {
        mqtt->playing=true;
        random_pixel(2,length,dir,0x000000,speed);////
    }
    if (strcmp(type, "pixelcolor") == 0) {
       mqtt->playing=true;
       random_pixel(1,length,dir,color,speed);////
    }
    cJSON_Delete(json_obj); 
}
void ws2812_stop() {
  mqtt->playing=false;
}
static void mqtt_incoming_data_cb(void *arg, const u8_t *data, u16_t len, u8_t flags) {
    MQTT_CLIENT_DATA_T* mqtt_client = (MQTT_CLIENT_DATA_T*)arg;
    LWIP_UNUSED_ARG(data);

    strncpy(mqtt_client->data, data, len);
    mqtt_client->len=len;
    mqtt_client->data[len]='\0';
    
    mqtt_client->newTopic=true;
    mqtt->playing=false;
 
}

static void mqtt_incoming_publish_cb(void *arg, const char *topic, u32_t tot_len) {
  MQTT_CLIENT_DATA_T* mqtt_client = (MQTT_CLIENT_DATA_T*)arg;
  strcpy(mqtt_client->topic, topic);
}

static void mqtt_request_cb(void *arg, err_t err) {
  MQTT_CLIENT_DATA_T* mqtt_client = ( MQTT_CLIENT_DATA_T*)arg;

  LWIP_PLATFORM_DIAG(("MQTT client \"%s\" request cb: err %d\n", mqtt_client->mqtt_client_info.client_id, (int)err));
}

static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status) {
  MQTT_CLIENT_DATA_T* mqtt_client = (MQTT_CLIENT_DATA_T*)arg;
  LWIP_UNUSED_ARG(client);

  LWIP_PLATFORM_DIAG(("MQTT client \"%s\" connection cb: status %d\n", mqtt_client->mqtt_client_info.client_id, (int)status));

  if (status == MQTT_CONNECT_ACCEPTED) {
    mqtt_sub_unsub(client,
            "start", 0,
            mqtt_request_cb, arg,
            1);
    mqtt_sub_unsub(client,
            "stop", 0,
            mqtt_request_cb, arg,
            1);
  }
}

int main()
{
    stdio_init_all();
     PIO pio = pio0;
    int sm = 0;
    ws2812_program_init(pio, sm,  WS2812_PIN, 800000);

    mqtt=(MQTT_CLIENT_DATA_T*)calloc(1, sizeof(MQTT_CLIENT_DATA_T));

    if (!mqtt) {
        printf("mqtt client instant ini error\n");
        return 0;
    }
    mqtt->playing=false;
    mqtt->newTopic=false;
    mqtt->mqtt_client_info = mqtt_client_info;

    if (cyw43_arch_init())
    {
        printf("failed to initialise\n");
        return 1;
    }
    wait_connecting();
    cyw43_arch_enable_sta_mode();
    if (cyw43_arch_wifi_connect_timeout_ms(WIFI_SSID, WIFI_PASSWORD, CYW43_AUTH_WPA2_AES_PSK, 30000))
    {
        printf("failed to connect\n");
        return 1;
    }
    ntp_time_init();
    get_ntp_time();
    ip_addr_t addr;
    if (!ip4addr_aton("your_MQTT_SERVER_IP", &addr)) {
        printf("ip error\n");
        return 0;
    }

   
    mqtt->mqtt_client_inst = mqtt_client_new();
    mqtt_set_inpub_callback(mqtt->mqtt_client_inst, mqtt_incoming_publish_cb, mqtt_incoming_data_cb, mqtt);

    err_t err = mqtt_client_connect(mqtt->mqtt_client_inst, &addr, MQTT_PORT, &mqtt_connection_cb, mqtt, &mqtt->mqtt_client_info);
    if (err != ERR_OK) {
      printf("connect error\n");
      return 0;
    }
    connected();


    while(1) {
      if (mqtt->newTopic) { 
          mqtt->newTopic=false;
          if (strcmp(mqtt->topic, "start")==0) {
            ws2812_action();
          }
          if (strcmp(mqtt->topic, "stop")==0) {
              ws2812_stop();
          }
      }

   }
    return 0;
}

  • Node-RED flow
 [
    {
        "id": "6e21089b48879905",
        "type": "tab",
        "label": "Flow 1",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "27103af5cfb31338",
        "type": "function",
        "z": "6e21089b48879905",
        "name": "function 1",
        "func": "var newmsg={};\n\nif (msg.payload == \"clock\" || msg.payload == \"sparkle\") {\n    newmsg.payload = {\n        \"group\":\n        {\n            \"hide\": [\"WS2812_SCROOLCOLOR\", \"WS2812_SLIDEPARAM\"]\n        }\n    };\n} else {\n    if (msg.payload==\"pixelcolor\") {\n        newmsg.payload = {\n            \"group\":\n            {\n                \"show\": [\"WS2812_SCROOLCOLOR\",\"WS2812_SLIDEPARAM\"]\n            }\n        };\n    } else {\n        newmsg.payload = {\n            \"group\":\n            {\n                \"hide\": [\"WS2812_SCROOLCOLOR\"], \"show\":[\"WS2812_SLIDEPARAM\"]\n            }\n        };\n    }\n}\n\n\nreturn newmsg",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 320,
        "y": 40,
        "wires": [
            [
                "700d3dc46fdd7924"
            ]
        ]
    },
    {
        "id": "dbe22a0817d2347d",
        "type": "ui_dropdown",
        "z": "6e21089b48879905",
        "name": "",
        "label": "Dispaly Type:",
        "tooltip": "",
        "place": "Select option",
        "group": "82089b24e7a5068c",
        "order": 1,
        "width": 5,
        "height": 1,
        "passthru": false,
        "multiple": false,
        "options": [
            {
                "label": "Clock",
                "value": "clock",
                "type": "str"
            },
            {
                "label": "Sparkle",
                "value": "sparkle",
                "type": "str"
            },
            {
                "label": "Pixel Color",
                "value": "pixelcolor",
                "type": "str"
            },
            {
                "label": "Random Color",
                "value": "randomcolor",
                "type": "str"
            }
        ],
        "payload": "",
        "topic": "type",
        "topicType": "msg",
        "className": "",
        "x": 120,
        "y": 80,
        "wires": [
            [
                "27103af5cfb31338",
                "1272075b2d61d0ce"
            ]
        ]
    },
    {
        "id": "700d3dc46fdd7924",
        "type": "ui_ui_control",
        "z": "6e21089b48879905",
        "name": "",
        "events": "all",
        "x": 480,
        "y": 40,
        "wires": [
            []
        ]
    },
    {
        "id": "5a66ec42f68bd5aa",
        "type": "ui_slider",
        "z": "6e21089b48879905",
        "name": "",
        "label": "speed",
        "tooltip": "",
        "group": "f72a2a2a55f0b438",
        "order": 4,
        "width": 0,
        "height": 0,
        "passthru": false,
        "outs": "end",
        "topic": "topic",
        "topicType": "msg",
        "min": "1",
        "max": 10,
        "step": 1,
        "className": "",
        "x": 90,
        "y": 220,
        "wires": [
            [
                "50b09b338cf91909"
            ]
        ]
    },
    {
        "id": "ca0b6363716ad933",
        "type": "ui_slider",
        "z": "6e21089b48879905",
        "name": "",
        "label": "Pixels#",
        "tooltip": "",
        "group": "f72a2a2a55f0b438",
        "order": 3,
        "width": 0,
        "height": 0,
        "passthru": false,
        "outs": "end",
        "topic": "topic",
        "topicType": "msg",
        "min": "1",
        "max": "59",
        "step": 1,
        "className": "",
        "x": 100,
        "y": 180,
        "wires": [
            [
                "08d9446473a7a2f2"
            ]
        ]
    },
    {
        "id": "ddb42afe82963199",
        "type": "ui_colour_picker",
        "z": "6e21089b48879905",
        "name": "",
        "label": "",
        "group": "ff7916db92ed582e",
        "format": "hex",
        "outformat": "string",
        "showSwatch": true,
        "showPicker": false,
        "showValue": true,
        "showHue": false,
        "showAlpha": false,
        "showLightness": true,
        "square": "false",
        "dynOutput": "false",
        "order": 2,
        "width": 0,
        "height": 0,
        "passthru": false,
        "topic": "topic",
        "topicType": "msg",
        "className": "",
        "x": 110,
        "y": 360,
        "wires": [
            [
                "586673b8704f4617"
            ]
        ]
    },
    {
        "id": "d5e936d54e6a819b",
        "type": "ui_text",
        "z": "6e21089b48879905",
        "group": "ff7916db92ed582e",
        "order": 1,
        "width": 0,
        "height": 0,
        "name": "",
        "label": "Pick Color",
        "format": "",
        "layout": "col-center",
        "className": "",
        "x": 110,
        "y": 320,
        "wires": []
    },
    {
        "id": "3a36f74e374bc0ab",
        "type": "ui_text",
        "z": "6e21089b48879905",
        "group": "f72a2a2a55f0b438",
        "order": 1,
        "width": 0,
        "height": 0,
        "name": "",
        "label": "Select the number of Pixels and speed",
        "format": "{{msg.payload}}",
        "layout": "col-center",
        "className": "",
        "x": 190,
        "y": 140,
        "wires": []
    },
    {
        "id": "50b09b338cf91909",
        "type": "change",
        "z": "6e21089b48879905",
        "name": "",
        "rules": [
            {
                "t": "move",
                "p": "payload",
                "pt": "msg",
                "to": "speed",
                "tot": "flow"
            }
        ],
        "action": "",
        "property": "",
        "from": "",
        "to": "",
        "reg": false,
        "x": 270,
        "y": 220,
        "wires": [
            []
        ]
    },
    {
        "id": "08d9446473a7a2f2",
        "type": "change",
        "z": "6e21089b48879905",
        "name": "",
        "rules": [
            {
                "t": "move",
                "p": "payload",
                "pt": "msg",
                "to": "length",
                "tot": "flow"
            }
        ],
        "action": "",
        "property": "",
        "from": "",
        "to": "",
        "reg": false,
        "x": 270,
        "y": 180,
        "wires": [
            []
        ]
    },
    {
        "id": "586673b8704f4617",
        "type": "change",
        "z": "6e21089b48879905",
        "name": "",
        "rules": [
            {
                "t": "move",
                "p": "payload",
                "pt": "msg",
                "to": "color",
                "tot": "flow"
            }
        ],
        "action": "",
        "property": "",
        "from": "",
        "to": "",
        "reg": false,
        "x": 310,
        "y": 360,
        "wires": [
            []
        ]
    },
    {
        "id": "08a77a34f56dd819",
        "type": "ui_button",
        "z": "6e21089b48879905",
        "name": "",
        "group": "e5d38edfd552806e",
        "order": 1,
        "width": 2,
        "height": 1,
        "passthru": false,
        "label": "Start",
        "tooltip": "",
        "color": "",
        "bgcolor": "",
        "className": "",
        "icon": "",
        "payload": "",
        "payloadType": "str",
        "topic": "topic",
        "topicType": "msg",
        "x": 90,
        "y": 420,
        "wires": [
            [
                "32bc237d4be9a18c"
            ]
        ]
    },
    {
        "id": "32bc237d4be9a18c",
        "type": "function",
        "z": "6e21089b48879905",
        "name": "function 2",
        "func": "msg.payload={};\nmsg.payload.type=flow.get(\"type\") || \"\";\nmsg.payload.speed = flow.get(\"speed\") || 1;\nmsg.payload.length = flow.get(\"length\") || 1;\nmsg.payload.color = flow.get('color') || 0x000000;\nmsg.payload.dir = flow.get(\"dir\") || 1;\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 240,
        "y": 420,
        "wires": [
            [
                "03cebb9c7b1959d8"
            ]
        ]
    },
    {
        "id": "1272075b2d61d0ce",
        "type": "change",
        "z": "6e21089b48879905",
        "name": "",
        "rules": [
            {
                "t": "move",
                "p": "payload",
                "pt": "msg",
                "to": "type",
                "tot": "flow"
            }
        ],
        "action": "",
        "property": "",
        "from": "",
        "to": "",
        "reg": false,
        "x": 330,
        "y": 100,
        "wires": [
            []
        ]
    },
    {
        "id": "d98476ae54d711de",
        "type": "ui_button",
        "z": "6e21089b48879905",
        "name": "",
        "group": "e5d38edfd552806e",
        "order": 2,
        "width": 2,
        "height": 1,
        "passthru": false,
        "label": "Stop",
        "tooltip": "",
        "color": "",
        "bgcolor": "",
        "className": "",
        "icon": "",
        "payload": "",
        "payloadType": "str",
        "topic": "topic",
        "topicType": "msg",
        "x": 90,
        "y": 480,
        "wires": [
            [
                "f82aa1487c39a9cb"
            ]
        ]
    },
    {
        "id": "d84ae8a0e6a9e047",
        "type": "mqtt out",
        "z": "6e21089b48879905",
        "name": "",
        "topic": "",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "466c902492653c8c",
        "x": 590,
        "y": 480,
        "wires": []
    },
    {
        "id": "03cebb9c7b1959d8",
        "type": "json",
        "z": "6e21089b48879905",
        "name": "",
        "property": "payload",
        "action": "",
        "pretty": false,
        "x": 370,
        "y": 420,
        "wires": [
            [
                "f31a49d4d4727859"
            ]
        ]
    },
    {
        "id": "f82aa1487c39a9cb",
        "type": "function",
        "z": "6e21089b48879905",
        "name": "function 3",
        "func": "msg.topic=\"stop\";\nmsg.payload=\"stop\";\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 280,
        "y": 480,
        "wires": [
            [
                "d84ae8a0e6a9e047"
            ]
        ]
    },
    {
        "id": "f31a49d4d4727859",
        "type": "function",
        "z": "6e21089b48879905",
        "name": "function 4",
        "func": "msg.topic=\"start\";\n\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 520,
        "y": 420,
        "wires": [
            [
                "d84ae8a0e6a9e047"
            ]
        ]
    },
    {
        "id": "9edca29e76cc4a35",
        "type": "ui_dropdown",
        "z": "6e21089b48879905",
        "name": "",
        "label": "Direction",
        "tooltip": "",
        "place": "",
        "group": "f72a2a2a55f0b438",
        "order": 2,
        "width": 0,
        "height": 0,
        "passthru": true,
        "multiple": false,
        "options": [
            {
                "label": "clockwise",
                "value": 1,
                "type": "num"
            },
            {
                "label": "counterclockwise",
                "value": "-1",
                "type": "str"
            }
        ],
        "payload": "",
        "topic": "topic",
        "topicType": "msg",
        "className": "",
        "x": 100,
        "y": 260,
        "wires": [
            [
                "ed2d4290fb55a4bc"
            ]
        ]
    },
    {
        "id": "ed2d4290fb55a4bc",
        "type": "change",
        "z": "6e21089b48879905",
        "name": "",
        "rules": [
            {
                "t": "move",
                "p": "payload",
                "pt": "msg",
                "to": "dir",
                "tot": "flow"
            }
        ],
        "action": "",
        "property": "",
        "from": "",
        "to": "",
        "reg": false,
        "x": 270,
        "y": 260,
        "wires": [
            []
        ]
    },
    {
        "id": "104b1503d903372c",
        "type": "ui_spacer",
        "z": "6e21089b48879905",
        "name": "spacer",
        "group": "82089b24e7a5068c",
        "order": 2,
        "width": 1,
        "height": 1
    },
    {
        "id": "7783de4639450be7",
        "type": "ui_spacer",
        "z": "6e21089b48879905",
        "name": "spacer",
        "group": "e5d38edfd552806e",
        "order": 3,
        "width": 2,
        "height": 1
    },
    {
        "id": "82089b24e7a5068c",
        "type": "ui_group",
        "name": "Default",
        "tab": "8caf46a96fa73472",
        "order": 1,
        "disp": false,
        "width": 6,
        "collapse": false,
        "className": ""
    },
    {
        "id": "f72a2a2a55f0b438",
        "type": "ui_group",
        "name": "SLIDEPARAM",
        "tab": "8caf46a96fa73472",
        "order": 2,
        "disp": false,
        "width": "5",
        "collapse": false,
        "className": ""
    },
    {
        "id": "ff7916db92ed582e",
        "type": "ui_group",
        "name": "SCROOLCOLOR",
        "tab": "8caf46a96fa73472",
        "order": 3,
        "disp": false,
        "width": "5",
        "collapse": false,
        "className": ""
    },
    {
        "id": "e5d38edfd552806e",
        "type": "ui_group",
        "name": "Buttons",
        "tab": "8caf46a96fa73472",
        "order": 5,
        "disp": false,
        "width": 6,
        "collapse": false,
        "className": ""
    },
    {
        "id": "466c902492653c8c",
        "type": "mqtt-broker",
        "name": "mosquitto",
        "broker": "localhost",
        "port": "1883",
        "clientid": "",
        "autoConnect": true,
        "usetls": false,
        "protocolVersion": "4",
        "keepalive": "60",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closeQos": "0",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willPayload": "",
        "willMsg": {},
        "userProps": "",
        "sessionExpiry": "",
        "credentials": {}
    },
    {
        "id": "8caf46a96fa73472",
        "type": "ui_tab",
        "name": "WS2812",
        "icon": "dashboard",
        "disabled": false,
        "hidden": true
    }
]





2023年2月4日 星期六

[Raspberry Pi Pico W (c-sdk)] lwIP: Ep 3. TCP Client & Node-RED Display images

 本篇文章介紹Raspberry Pi Pico W使用lwIP TCP API上傳SD Card上的JPG 檔案到Node-RED TCP Server並透過Node-RED UI template即時顯示上傳的檔案。


  • TCP Client 連線:
按下列步驟設定連線:
  1. create TCP PCB
  2. 設定TCP PCB的callback function: 
    tcp_sent: sent callback
    tcp_recv: recv callback
    tcp_err: err callback
    tcp_poll: poll callback
  3. tcp_connect連線server ip:port
    於函式中設定connected callback。
如下圖。

  • 透過TCP connection送出檔案:
tcp_write寫入data後呼叫tcp_output送出data,在sent callback回傳server已收到的資料。比對server已收到後再送出下一筆資料。
如下圖。



詳細程式碼附於文末。

  • Node-RED端:

成果影片:


程式碼:
#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "hardware/spi.h"
#include "hardware/dma.h"
#include "pico/cyw43_arch.h"

#include "lwip/pbuf.h"
#include "lwip/tcp.h"

#include "modules/FatFs/ff.h"
#include "modules/FatFs/diskio.h"
#include "modules/ntp_time/ntp_time.h"
#include "string.h"
#include "inttypes.h"

#define WIFI_SSID "your_SSID"
#define WIFI_PASSWORD "your_PASSWORD"
#define TCP_SERVER_IP "your_SERVER_IP"
#define TCP_PORT 5656
#define BUF_SIZE (TCP_MSS*2)
#define POLL_TIME_S 5

typedef struct TCP_CLIENT_T_
{
    struct tcp_pcb *tcp_pcb;
    ip_addr_t remote_addr;
    int sent_len;
     bool connected;
} TCP_CLIENT_T;

TCP_CLIENT_T *tcp_client=NULL;

err_t tcp_client_connected_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
    if (err != ERR_OK) {
        printf("connect callback error\n");
        return err;
    }
    TCP_CLIENT_T *tcp_client=(TCP_CLIENT_T *)arg;
    
    printf("connect to ip:%s\n", ip4addr_ntoa(&tcp_client->remote_addr));
    tcp_client->connected = true;
    return ERR_OK;
}

err_t tcp_client_sent_cb(void *arg, struct tcp_pcb *tpcb, u16_t len){ 
    err_t err = ERR_OK;
    //printf("tcp server received: %d\n", len);
    TCP_CLIENT_T *tcp_client = (TCP_CLIENT_T*)arg;
    tcp_client->sent_len -= len;
    return err;
    
}

err_t tcp_client_close(void *arg)
{
    TCP_CLIENT_T *tcp_client = (TCP_CLIENT_T *)arg;
    err_t err = ERR_OK;
    if (tcp_client->tcp_pcb != NULL)
    {
        tcp_arg(tcp_client->tcp_pcb, NULL);
        tcp_poll(tcp_client->tcp_pcb, NULL, 0);
        tcp_sent(tcp_client->tcp_pcb, NULL);
        tcp_recv(tcp_client->tcp_pcb, NULL);
        tcp_err(tcp_client->tcp_pcb, NULL);
        err = tcp_close(tcp_client->tcp_pcb);
        if (err != ERR_OK)
        {
            printf("close failed %d, calling abort\n", err);
            tcp_abort(tcp_client->tcp_pcb);
            err = ERR_ABRT;
        }
        tcp_client->tcp_pcb = NULL;
    }
    return err;
}

err_t tcp_client_recv_cb(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) {
    if (!p) {
        printf(" connect close\n");
        tcp_client_close(arg);
        return err;
    } 
    cyw43_arch_lwip_check();
    uint8_t *buf = p->payload;
    buf[p->tot_len]='\0';
    printf("received data:%s\n", buf);
    
    tcp_recved(tpcb, p->tot_len);
    pbuf_free(p);  // * important
    return err;
}

void tcp_client_err_cb(void *arg, err_t err) {
    printf("tcp_client error: %d\n", err);
    tcp_client_close(arg);
}

err_t tcp_client_poll_cb(void *arg, struct tcp_pcb *tpcb) {
    printf("tcl_client_poll_cb\n");

    return ERR_OK;

}

bool tcp_client_connect_server(uint8_t *addr, uint16_t port) {
    tcp_client = (TCP_CLIENT_T*) calloc(1, sizeof(TCP_CLIENT_T));
    if (tcp_client == NULL) return false;
    if (! ip4addr_aton(addr, &tcp_client->remote_addr)) return false;
    tcp_client->tcp_pcb = tcp_new_ip_type(IP_GET_TYPE(&tcp_client->remote_addr));
    tcp_client->connected=false;
    tcp_client->sent_len=0;

    tcp_arg(tcp_client->tcp_pcb, tcp_client);
    tcp_sent(tcp_client->tcp_pcb, tcp_client_sent_cb);
    tcp_recv(tcp_client->tcp_pcb, tcp_client_recv_cb);
    tcp_err(tcp_client->tcp_pcb, tcp_client_err_cb);
    tcp_poll(tcp_client->tcp_pcb, tcp_client_poll_cb, POLL_TIME_S*2);

    absolute_time_t timeout = make_timeout_time_ms(10000);
    err_t err = tcp_connect(tcp_client->tcp_pcb, &tcp_client->remote_addr, port, tcp_client_connected_cb);
    if (err != ERR_OK) {
        printf("connect to server error!\n");
        return false;
    }
    while (absolute_time_diff_us(get_absolute_time(), timeout) > 0 && !tcp_client->connected) {
        sleep_ms(100);
    }
    if (!tcp_client->connected) {
        printf("connect time out\n");
        return false;
    }
    return true;
}
void upload_file(uint8_t *filename) {
    FIL fil;
    FRESULT res;
    char path[100];
    if (!tcp_client_connect_server(TCP_SERVER_IP, TCP_PORT)){
        return;
    }
    sprintf(path, "%s/%s", SDMMC_PATH, filename);
    res = f_open(&fil, path, FA_READ);
    if (res != FR_OK) {
        printf("open file error:\n");
        return;
    }

    uint8_t buff[BUF_SIZE];
    UINT br;
    
    //absolute_time_t t1 = get_absolute_time();
    do {
        res = f_read(&fil, buff, BUF_SIZE, &br);
        tcp_write(tcp_client->tcp_pcb, buff, br, TCP_WRITE_FLAG_COPY);
        tcp_client->sent_len += br;
        tcp_output(tcp_client->tcp_pcb);
       
        while(tcp_client->sent_len > 0) 
        {
            sleep_us(1);
        }

    } while(br >0);
    //printf("tcp upload time=%"PRIu64"\n", absolute_time_diff_us(t1, get_absolute_time()));
    res=f_close(&fil);
    tcp_client_close(tcp_client);
}

int main()
{
    stdio_init_all();
    gpio_init(5);
    gpio_init(6);
    gpio_set_dir(5, 1);
    gpio_set_dir(6,1);
    gpio_put(5,1);
    gpio_put(6,0);

    if (cyw43_arch_init())
    {
        printf("failed to initialise\n");
        return 1;
    }
    cyw43_arch_enable_sta_mode();
    if (cyw43_arch_wifi_connect_timeout_ms(WIFI_SSID, WIFI_PASSWORD, CYW43_AUTH_WPA2_AES_PSK, 30000))
    {
        printf("failed to connect\n");
        return 1;
    }
    ntp_time_init();
    get_ntp_time();
    gpio_put(5,0);
    gpio_put(6,1);
    FIL fil;
    FATFS fs;
    FRESULT res;

  
    
    res = f_mount(&fs, SDMMC_PATH, 1);
    if (res != FR_OK)
    {
        printf(" mount error\n");
        return 0;
    }
    uint8_t fname[15];
    for (int j=0;j < 2;j++)
    for (int i=1; i <=8; i++) {
        sprintf(fname, "pic%d.jpg",i);
        printf("%s\n", fname);
        upload_file(fname);
    }
    gpio_put(6,0);
    printf("Finish\n");
    if (tcp_client) free(tcp_client);
    return 0;
}

2023年1月30日 星期一

[Raspberry Pi Pico W (c-sdk)] lwIP: Ep 2. HTTP Client Application & Weather Station

 本文章介紹Raspberry Pi Pico W c-sdk,使用lwIP的HTTP Client Application 存取openweathermap網站的氣象資料,顯示在TFT LCD上。



使用httpc_get_file_dns function取得 網站資料。分別設定三個callback function:
1: httpc_result_fn:

2023年1月12日 星期四

[Raspberry Pi Pico W (c-sdk)] lwIP: Ep 1. NTP & RTC & Clock

 本文章介紹Raspberry Pi Pico W使用lwIP library 每6小時透過NTP校正RTC時鐘,並以Digital or Analog Clock方式透過ILI9341 TFT LCD時間,畫面上顯示WiFi連線狀態,當網路中斷後重新連線時立即做一次網路校時。


一、建立專案

安裝pico-project-generator程式,以圖行化產生專案初始內容。

~$ pico_project.py --gui

使用LwIP library 需要lwipopts.h檔案,將該檔案先複製到pico_project.py相同目錄下。

~$ cp pico-examples/pico_w/lwipopts_examples_common.h  <pico-project.py directory>/lwipopts.h 

Pico Wireless Options共有四種模式,本次使用Background lwIP模式:This is multi-core/thread/task safe, and maintenance of the driver and TCP/IP stack is handled automatically in the background。

二、週期檢視的程式碼:

       需要使用到的libraries為cyw43_arch, rtc, lwip/dns, lwip/udp, lwip/pbuf
        rtc_init()
        cyw43_arch_init()
        ili931_init()
  1. 每秒更新畫面:
    repeating_timer_t rt;
    add_repeating_timer_ms(-1000, repeat_timer_cb, &net_time, &rt);
    使用-1000ms確保每1秒呼叫一次repeat_time_cb function 更正時鐘畫面。

  2. 每六小時透過NTP校正RTC時鐘:
    ntp_time->ntp_update_time = make_timeout_time_ms(21600000); //6*60*60*1000
    add_alarm_at(ntp_time->ntp_update_time, alarm_ntp_update_cb, arg, false);

  3. 每10秒見識WiFi連線狀態:
    while(1) {
            sleep_ms(10000);
            tcpip_stat = cyw43_tcpip_link_status(&cyw43_state, CYW43_ITF_STA);
            if (tcpip_stat != net_time.tcpip_link_state) {
                net_time.tcpip_link_state = tcpip_stat;
                if (net_time.tcpip_link_state == CYW43_LINK_UP) {
                    get_ntp_time();
                } 
                set_wifi_status_icon(net_time.tcpip_link_state);
            }
        }
    若tcpip_link_state回覆到CYW43_LINK_UP則在呼叫get_ntp_time()立即重新校時。

三、NTP data format:

相對應於NTP request package payload。


收到NTP server回應的package 時間的秒數(相對於1900/01/01)在Transmit timestamp前四bytes。

四、成果影片



五、程式碼

 #include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "hardware/rtc.h"
#include "time.h"
#include "lwip/dns.h"
#include "lwip/pbuf.h"
#include "lwip/udp.h"
#include "modules/ili9341_tft/ili9341.h"
#include "fonts/font_fixedsys_mono_24.h"
#include "fonts/font48.h"
#include "fonts/font36.h"
#include "fonts/wifi.h"
#include "fonts/wifi_off.h"
#include "fonts/clock.h"
#include "math.h"


#define WIFI_SSID   "your-SSID"
#define WIFI_PASS   "your-WIFI_PASSWORD"
#define NTP_SERVER  "pool.ntp.org"
#define NTP_PORT    (123)
bool showAnalog=true;
/* RFC 1305 
 NTP timestamps are represented as a 64-bit unsigned fixed-
point number, in seconds relative to 0h on 1 January 1900. The integer
part is in the first 32 bits and the fraction part in the last 32 bits.*/
#define NTP_DELTA (2208988800) // seconds between 1 Jan 1900 and 1 Jan 1970
#define NTP_MSG_LEN (48)  // ignore Authenticator (optional)

typedef struct NTP_TIME_T {
    ip_addr_t ntp_ipaddr;
    struct udp_pcb *ntp_pcb;
    bool ntp_server_found;
    absolute_time_t ntp_update_time;
    int tcpip_link_state;
} NTP_TIME;
NTP_TIME net_time;

uint8_t wday[7][10] = {"Sunday", "Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday"};
void get_ntp_time();

void set_wifi_status_icon(int status) {
    if (status == CYW43_LINK_UP) {
        ili9341_draw_bitmap(270, 20, &wifi);
        
    } else {
        ili9341_draw_bitmap(270, 20, &wifi_off);
    }
}

int64_t alarm_ntp_update_cb(alarm_id_t alarm_id, void* param) {
    cancel_alarm(alarm_id);
    get_ntp_time();
}

void ntp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) {
    NTP_TIME* ntp_time = (NTP_TIME*)arg;
    uint8_t mode=pbuf_get_at(p,0)& 0x07;  // LI[2], VN[3], MODE[3], mode(0x04): server
    uint8_t stratum = pbuf_get_at(p,1);   // straum 
    uint8_t ts[4]={0};
    uint32_t sec_offset;
    if (port == NTP_PORT && ip_addr_cmp(&net_time.ntp_ipaddr, addr) && p->tot_len == NTP_MSG_LEN && mode == 0x04 && stratum != 0) { 
        pbuf_copy_partial(p, ts, sizeof(ts), 40);
        sec_offset = ((uint32_t)ts[0])<<24 | ((uint32_t)ts[1])<<16 | ((uint32_t)ts[2])<<8 | ((uint32_t)ts[3]);
        uint32_t temp = sec_offset - NTP_DELTA+8*60*60; //UTC+8
        time_t utc_sec_offset = temp;
        struct tm *utc = gmtime(&utc_sec_offset);
        datetime_t rtc_time;

        rtc_time.year=utc->tm_year+1900;
        rtc_time.month= utc->tm_mon+1;
        rtc_time.day = utc->tm_mday;
        rtc_time.hour = utc->tm_hour;
        rtc_time.min = utc->tm_min;
        rtc_time.sec = utc->tm_sec;
        rtc_time.dotw = utc->tm_wday;
        if (!rtc_set_datetime(&rtc_time)) printf("set rtc error\n");

        //printf("got ntp response: %02d/%02d/%04d %02d:%02d:%02d\n", utc->tm_mday, utc->tm_mon + 1, utc->tm_year + 1900,
        //        utc->tm_hour, utc->tm_min, utc->tm_sec);
        ntp_time->ntp_update_time = make_timeout_time_ms(21600000); //6*60*60*1000
        add_alarm_at(ntp_time->ntp_update_time, alarm_ntp_update_cb, arg, false);
        
    }
    pbuf_free(p);
}

void ntp_init_data() {
    net_time.ntp_pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
    net_time.ntp_server_found=false;
    net_time.tcpip_link_state = CYW43_LINK_DOWN;
    if (!net_time.ntp_pcb) {
        printf("alloc udp_new error\n");
        return;
    }
    udp_recv(net_time.ntp_pcb, ntp_recv_cb, &net_time);
}

void get_ntp_time() {
    cyw43_arch_lwip_begin();
    struct pbuf *pb = pbuf_alloc(PBUF_TRANSPORT, NTP_MSG_LEN, PBUF_RAM);
    uint8_t *req = (uint8_t *) pb->payload;
    memset(req, 0, NTP_MSG_LEN);
    req[0] = 0x1b;   // 0x00 011 011 (LI:00, VN:3(version), MODE:3 (client))
    udp_sendto(net_time.ntp_pcb, pb, &net_time.ntp_ipaddr, NTP_PORT);
    pbuf_free(pb);
    cyw43_arch_lwip_end();
}

void dns_cb(const char *name, const ip_addr_t *ipaddr, void *arg) {
    NTP_TIME* ntime = (NTP_TIME*)(arg);
    ntime->ntp_ipaddr=*ipaddr;
    printf("ntp server:%s\n", ipaddr_ntoa(&ntime->ntp_ipaddr));
    ntime->ntp_server_found = true;
}

void digitColck(datetime_t *dt) {
    char buf[100];
    sprintf(buf, "%04d-%02d-%02d", dt->year,dt->month,dt->day);
    ili9341_draw_string_withbg(80,20, buf, 0x0000,0xffff,&font36);
    sprintf(buf, "%02d:%02d:%02d", dt->hour,dt->min,dt->sec);
    ili9341_draw_string_withbg(10,80, buf, 0x001f,0xffff,&font48);
    ili9341_draw_string_withbg(20,190, wday[dt->dotw], 0xf800,0xffff,&font_fixedsys_mono_24);
}

void analogClock(datetime_t *dt) {
    double ang; 
    static int offx_h=0, offy_h=0;
    static int offx_m=0, offy_m=0;
    static int offx_s=0, offy_s=0;
    static int pre_offx_h=0, pre_offy_h=0;
    static int pre_offx_m=0, pre_offy_m=0;
    static int pre_offx_s=0, pre_offy_s=0;
       
    // hour hand
    ang=(((dt->hour)%12)*60+dt->min)*M_PI/360-M_PI/2;
    offx_h = 50*cos(ang);
    offy_h = 50*sin(ang);
    
    // minute hand
    ang=((dt->min)*60+dt->sec)*M_PI/1800-M_PI/2;
    offx_m = 70*cos(ang);
    offy_m = 70*sin(ang);
    
    // second hand
    ang = (dt->sec*M_PI)/30.0-M_PI/2;
    offx_s = 80*cos(ang);
    offy_s = 80*sin(ang);
    //clear clock hands
    ili9341_draw_line_width(159-pre_offx_s/7,119-pre_offy_s/7, 159+pre_offx_s, 119+pre_offy_s, 1,0xffff);
    ili9341_draw_circle(159+pre_offx_s, 119+pre_offy_s,3,0xffff);
    ili9341_draw_line_width(159-pre_offx_m/7,119-pre_offy_m/7, 159+pre_offx_m, 119+pre_offy_m, 1,0xffff);
    ili9341_draw_circle(159+pre_offx_m, 119+pre_offy_m,3,0xffff);
    ili9341_draw_line_width(159-pre_offx_h/7,119-pre_offy_h/7, 159+pre_offx_h, 119+pre_offy_h, 3,0xffff);

    //redraw clock hands
    //hour
    ili9341_draw_line_width(159-offx_h/7,119-offy_h/7, 159+offx_h, 119+offy_h, 3,0x0000);
    //min
    ili9341_draw_line_width(159-offx_m/7,119-offy_m/7, 159+offx_m, 119+offy_m, 1,0x001f);
    ili9341_draw_circle(159+offx_m, 119+offy_m,3,0x001f);
    //sec
    ili9341_draw_line_width(159-offx_s/7,119-offy_s/7, 159+offx_s, 119+offy_s, 1,0xf800);
    ili9341_draw_circle(159+offx_s, 119+offy_s,3,0xf800);

    pre_offx_h = offx_h;pre_offy_h=offy_h;
    pre_offx_m = offx_m;pre_offy_m=offy_m;
    pre_offx_s = offx_s;pre_offy_s=offy_s;
    
    ili9341_draw_fill_circle(159,119,5,0xff00);
  
}

bool repeat_timer_cb(repeating_timer_t *rt) {
    static datetime_t dt;
  
    rtc_get_datetime(&dt);
    

if (showAnalog)
    analogClock(&dt);
else
    digitColck(&dt);

/* 
    if (dt.sec == 0) { 
        ili9341_fill_rect(6,6,309, 229, 0xffff);
        set_wifi_status_icon(net_time.tcpip_link_state);
        showAnalog = !showAnalog;
        if (showAnalog)
            ili9341_draw_bitmap(49,9, &clock_bg);
    }
    */
    
    return true;
}

int main()
{
    stdio_init_all();
    rtc_init();
    cyw43_arch_init();
    ili9341_init();
    ntp_init_data();

    // border
    ili9341_draw_rect(0,0,320, 240, 0x07e0);
    ili9341_draw_rect(1,1,318, 238, 0x07e0);
    ili9341_draw_rect(2,2,316, 236, 0x07e0);
    ili9341_draw_rect(3,3,314, 234, 0x07e0);
    ili9341_draw_rect(4,4,312, 232, 0x0000);
    ili9341_draw_rect(5,5,310, 230, 0x0000);
    //analog clock background bitmap
    ili9341_draw_bitmap(49,9, &clock_bg);

    set_wifi_status_icon(net_time.tcpip_link_state);
   
    cyw43_arch_enable_sta_mode();
/* connect to wifi*/
    if (cyw43_arch_wifi_connect_timeout_ms(WIFI_SSID, WIFI_PASS, CYW43_AUTH_WPA2_AES_PSK, 10000)) {
        printf("Wifi connect timeout!\n");
        return 0;
    }
    int wait_secs = 0;
    while (wait_secs < 10) {
        net_time.tcpip_link_state = cyw43_tcpip_link_status(&cyw43_state, CYW43_ITF_STA);
        if (net_time.tcpip_link_state != CYW43_LINK_UP) {
            wait_secs++;
            if (wait_secs == 10) {
                printf("Can not get ip address\n");
                return 0;
            }
            sleep_ms(1000);
        } else {
            break;
        }

    }
    set_wifi_status_icon(net_time.tcpip_link_state);
   
/* get ntp server ip address  */
    int dns_ret;
    absolute_time_t timeout = make_timeout_time_ms(20000);
    while (!net_time.ntp_server_found && absolute_time_diff_us(get_absolute_time(), timeout) > 0) {
        dns_ret = dns_gethostbyname(NTP_SERVER, &net_time.ntp_ipaddr, dns_cb, &net_time);
        if (dns_ret == ERR_OK) break;
        sleep_ms(1000);
    }
    if(!net_time.ntp_server_found) {
        printf("NTP server not found!\n");
        return 0;
    }
    
    get_ntp_time();

   repeating_timer_t rt;
   add_repeating_timer_ms(-1000, repeat_timer_cb, &net_time, &rt);
   int tcpip_stat;
    while(1) {
        sleep_ms(10000);
        tcpip_stat = cyw43_tcpip_link_status(&cyw43_state, CYW43_ITF_STA);
        if (tcpip_stat != net_time.tcpip_link_state) {
            net_time.tcpip_link_state = tcpip_stat;
            if (net_time.tcpip_link_state == CYW43_LINK_UP) {
                get_ntp_time();
            } 
            set_wifi_status_icon(net_time.tcpip_link_state);
        }
    }
       
    return 0;
}

2022年12月26日 星期一

[Raspberry Pi Pico (c-sdk)] PIO I2S audio player

 本實驗整合

  1. [Raspberry Pi Pico (c-sdk)] Display: Ep 2 : PIO TFT LCD ILI9341 8-bit parallel C-code Driver
  2. [Raspberry Pi Pico (c-sdk)] Storage: Ep 3. Using SD/MMC Devices and Flash Devices Together
  3. Raspberry Pi Pico PIO(Programmable IO) Episode 4: I2S audio (Play WAVE File In SDCard from MAX98357A DAC)
再加入XPT2046 touch screen模組,製作一台聲音播放器。
各模組接到Raspberry Pi Pico接線腳位如下圖所示:


XPT2046 touch screen controller:

使用SPI界面,連接到SPI0。XPT2046 T_PEN腳位,平時為HIGH,按下時轉為LOW。使用GPIO EDGE_FALL 產生Interrupt。讀取觸控位置坐標,以便執行相關動作。

讀取X與Y座標的指令碼,分別為0xD0與0x90。透過spi送出指令後接著讀取讀取2 Bytes座標值。
連續取樣16次後平均後,再對應到實際TFT螢幕座標。

詳細程式碼如文末所附。

成果影片:


程式碼:



xpt2046.h
#ifndef _XPT2046_H_
#define _XPT2046_H_
#include "pico/stdlib.h"

#define XPT2046_PEN_GPIO    26
#define XPT2046_MOSI        19
#define XPT2046_MISO        16
#define XPT2046_CS          17
#define XPT2046_CLK         18
#define XPT2046_SPI         spi0

#define XPT2046_MIN_RAW_X 2000
#define XPT2046_MAX_RAW_X 30000
#define XPT2046_MIN_RAW_Y 1500
#define XPT2046_MAX_RAW_Y 29000

/* user define actions begin*/
enum {
    ACTION_FILE=1,
    ACTION_PLAY_PAUSE,
    ACTION_STOP,
    ACTION_IDLE
};

extern uint8_t user_action;
extern uint8_t selected_filename[60];
void main_menu();
/* user define actions end*/

void xpt2046_init();
bool xpt2046_getXY(uint16_t *x, uint16_t *y);
#endif

xpt2046.c
 #include "xpt2046.h"
#include "hardware/spi.h"
#include "hardware/gpio.h"
#include "pico/stdlib.h"
#include "stdio.h"
#include "ili9341.h"
#include "ff.h"
#include "spi_sdmmc.h"
#include "fonts/font_fixedsys_mono_24.h"
#include "i2s_pio_dma.h"
#include "string.h"
#include "fonts/play.h"
#include "fonts/stop.h"
#include "fonts/pause.h"
#include "fonts/resume.h"

uint32_t xpt2046_event=0;
uint8_t READ_X = 0xD0;
uint8_t READ_Y = 0x90;

static uint8_t top_index=0;
static uint16_t total_files=0;

/* user define action function*/
uint8_t user_action;            //export
uint8_t selected_filename[60];  // export

static int selected_item=-1;
static uint16_t sx=5, sy = 4;
static uint16_t item_height=30;

static uint8_t audio_files[30][30];
/* action region */
static uint16_t text_rgn_x0=2,text_rgn_x1=216,text_rgn_y0=2,text_rgn_y1=273;
static uint16_t menu_rgn_x0=2,menu_rgn_x1=238,menu_rgn_y0=275,menu_rgn_y1=318;
static uint16_t play_rgn_x0=8,play_rgn_x1=48,play_rgn_y0=276,play_rgn_y1=318;
static uint16_t stop_rgn_x0=100,stop_rgn_x1=140,stop_rgn_y0=276,stop_rgn_y1=318;
static uint16_t su_rgn_x0=220,su_rgn_x1=238,su_rgn_y0=5,su_rgn_y1=25;
static uint16_t sd_rgn_x0=220,sd_rgn_x1=238,sd_rgn_y0=262,sd_rgn_y1=272;

void draw_menu_item() {
    ili9341_fill_rect(2,2,215, 272,0x0000);
    for (int i = 0; i < 9; i++) {
        if (i+top_index < total_files)
            ili9341_draw_string(sx, sy+i*item_height,audio_files[i+top_index], 0xffff, &font_fixedsys_mono_24);
    }
}
void main_menu() {
    FRESULT fr;
    FIL file;
    FATFS fs;
    DIR dir;
    FILINFO finfo;
    uint8_t findex=0;
    

    fr = f_opendir(&dir, SDMMC_PATH"/");
    if (fr != FR_OK) {
        printf("open dir error\n");
        return;
    }
    uint8_t bc;
    fr = f_readdir(&dir, &finfo);
    total_files = 0;
    top_index = 0;
    while (fr == FR_OK && strlen(finfo.fname) > 0) { 
        
        if ((uint8_t)(finfo.fname[0]) != '.') {
            strcpy(audio_files[findex++], finfo.fname);
            total_files++;
       }   
        
        fr = f_readdir(&dir, &finfo);
    }

    ili9341_fill_rect(0,0, TFT_WIDTH, TFT_HEIGHT, 0x0000);
    ili9341_draw_rect(1,1,238, 318,0xffff);
    ili9341_draw_line(217,1,217,274,0xffff);
    ili9341_draw_line(1,274,238,274,0xffff);
    
    ili9341_draw_bitmap(10,277, &play);
    ili9341_draw_bitmap(102, 277, &stop);

    ili9341_fill_rect(222, 5, 10,10, 0xffff);
    ili9341_fill_rect(222, 262, 10,10, 0xffff);
    /* files */
    draw_menu_item();
      
}
/* user define action function*/
void touch_action() {
    uint16_t x, y;
    int temp_select;
    if (xpt2046_event & GPIO_IRQ_EDGE_FALL) {
            if (xpt2046_getXY(&x,&y)) { 
                if (x >= text_rgn_x0 && x <= text_rgn_x1 && y >= text_rgn_y0 && y <= text_rgn_y1) { 
                    temp_select = (int)((y-4)/item_height);
                    ili9341_fill_rect(2,sy+(temp_select)*item_height,215, 30, 0x001f);
                    ili9341_draw_string(sx, sy+(temp_select)*item_height,audio_files[temp_select+top_index], 0xffff, &font_fixedsys_mono_24);
                    ili9341_fill_rect(2,sy+(selected_item)*item_height,215, 30, 0x0000);
                    ili9341_draw_string(sx, sy+(selected_item)*item_height,audio_files[selected_item+top_index], 0xffff, &font_fixedsys_mono_24);
                    selected_item=temp_select;
                    user_action = ACTION_FILE;
                    strcpy(selected_filename, audio_files[selected_item+top_index]);
                }
                if (x >= play_rgn_x0 && x <= play_rgn_x1 && y >= play_rgn_y0 && y <= play_rgn_y1) {
                    user_action = ACTION_PLAY_PAUSE;
                    switch(i2s_play_state) {
                        case I2S_PLAYING:
                            i2s_play_state = I2S_PAUSE;
                            ili9341_draw_bitmap(10,277, &resume);
                        break;
                        case I2S_PAUSED:
                            i2s_play_state = I2S_RESUME;
                            ili9341_draw_bitmap(10,277, &pause);
                        break;
                        case I2S_STOP:
                            i2s_play_state = I2S_PLAY;
                        break;
                    }
                }
                if (x >= stop_rgn_x0 && x <= stop_rgn_x1 && y >= stop_rgn_y0 && y <= stop_rgn_y1) {
                    user_action = ACTION_STOP;
                    i2s_play_state=I2S_STOP;
                }
                if (x >= su_rgn_x0 && x <= su_rgn_x1 && y >= su_rgn_y0 && y <= su_rgn_y1) {
                    if (top_index > 0 && total_files > 9) {
                        top_index--;
                        draw_menu_item();
                    }
                }
                if (x >= sd_rgn_x0 && x <= sd_rgn_x1 && y >= sd_rgn_y0 && y <= sd_rgn_y1) { 
                    if (top_index+9 < total_files) {
                        top_index++;
                        draw_menu_item();
                    }
                }
            }
            xpt2046_event &= (!GPIO_IRQ_EDGE_FALL);
            gpio_set_irq_enabled(XPT2046_PEN_GPIO, GPIO_IRQ_EDGE_FALL, true);

        }
        if (xpt2046_event & GPIO_IRQ_EDGE_FALL) {
            xpt2046_event &= (!GPIO_IRQ_EDGE_RISE);
            gpio_set_irq_enabled(XPT2046_PEN_GPIO, GPIO_IRQ_EDGE_RISE, true);
        }

}

void touch_irq_handle(uint gpio, uint32_t event) {
    static uint32_t cnt=0;
    gpio_set_irq_enabled(gpio, GPIO_IRQ_EDGE_FALL&event, false);
    gpio_set_irq_enabled(gpio, GPIO_IRQ_EDGE_RISE&event, false);
    xpt2046_event |= event;
    if(event & GPIO_IRQ_EDGE_FALL && gpio == XPT2046_PEN_GPIO) { 
        touch_action();
    }
    if(event & GPIO_IRQ_EDGE_RISE  && gpio == XPT2046_PEN_GPIO) {

        
    }
 
}
bool xpt2046_getXY(uint16_t *x, uint16_t *y) {
   
    uint8_t temp[2];
    uint16_t raw_x, raw_y;
    uint32_t avg_x = 0;
    uint32_t avg_y = 0;
    uint8_t nsamples = 0;
    const uint8_t SAMPLES=16;

     gpio_put(XPT2046_CS, false);

    for(uint8_t i = 0; i < SAMPLES; i++, nsamples++)
    {
        if(gpio_get(XPT2046_PEN_GPIO))
            break;
        spi_write_blocking(XPT2046_SPI, &READ_X, 1);
        spi_read_blocking(XPT2046_SPI, 0x00, temp, 2);
        raw_x = ((uint16_t)temp[0]) << 8 | (uint16_t)temp[1];

        spi_write_blocking(XPT2046_SPI, &READ_Y, 1);
        spi_read_blocking(XPT2046_SPI, 0x00, temp, 2);
        raw_y = ((uint16_t)temp[0]) << 8 | (uint16_t)temp[1];

        avg_x += raw_x;
        avg_y += raw_y;
    }

    gpio_put(XPT2046_CS, true);

    if(nsamples < SAMPLES)
        return false;

    raw_x = (avg_x / SAMPLES);
    raw_y = (avg_y / SAMPLES);

    if(raw_x < XPT2046_MIN_RAW_X) raw_x = XPT2046_MIN_RAW_X;
    if(raw_x > XPT2046_MAX_RAW_X) raw_x = XPT2046_MAX_RAW_X;

    if(raw_y < XPT2046_MIN_RAW_Y) raw_y = XPT2046_MIN_RAW_Y;
    if(raw_y > XPT2046_MAX_RAW_Y) raw_y = XPT2046_MAX_RAW_Y;

    *x = (raw_x - XPT2046_MIN_RAW_X) * TFT_WIDTH  / (XPT2046_MAX_RAW_X - XPT2046_MIN_RAW_X);
    *y = (raw_y - XPT2046_MIN_RAW_Y) * TFT_HEIGHT / (XPT2046_MAX_RAW_Y - XPT2046_MIN_RAW_Y);
    return true;
    
}

void xpt2046_init() {
    gpio_init(XPT2046_PEN_GPIO);
    gpio_init(XPT2046_MISO);
    gpio_init(XPT2046_MOSI);
    gpio_init(XPT2046_CLK);
    gpio_init(XPT2046_CS);
    gpio_set_dir(XPT2046_CS, GPIO_OUT);
    gpio_set_function(XPT2046_CLK,GPIO_FUNC_SPI);
    gpio_set_function(XPT2046_CS,GPIO_FUNC_SIO);
    gpio_set_function(XPT2046_MOSI,GPIO_FUNC_SPI);
    gpio_set_function(XPT2046_MISO,GPIO_FUNC_SPI);
    spi_init(XPT2046_SPI,250000);

   gpio_set_irq_enabled_with_callback(XPT2046_PEN_GPIO, GPIO_IRQ_EDGE_RISE | GPIO_IRQ_EDGE_FALL, true, touch_irq_handle);
   

}