first and compiling freertos

This commit is contained in:
2025-07-27 19:07:40 -04:00
commit cead28fdd6
43 changed files with 2737 additions and 0 deletions

252
DEVELOPMENT_INSTRUCTIONS.md Normal file
View File

@@ -0,0 +1,252 @@
# RP2040-ETH Precision Timing Tool Development Instructions
## Project Overview
A precision timing tool using Waveshare RP2040-ETH with FreeRTOS for complex timing and scheduling operations.
### Input Protocols
- NTP (Network Time Protocol)
- PTP (Precision Time Protocol)
- IRIG (Inter-Range Instrumentation Group time codes)
- GPS (Global Positioning System time)
- PPS (Pulse Per Second)
### Output Protocols
- PTP (Precision Time Protocol)
- NTP (Network Time Protocol)
- IRIG-A (Audio frequency time code)
## Development Environment Setup
### Prerequisites
1. **ARM GCC Toolchain**: arm-none-eabi-gcc
2. **CMake**: Version 3.13 or higher
3. **Pico SDK**: Will be included as submodule
4. **FreeRTOS**: Will be included from RP2040-FreeRTOS repository
5. **Python 3**: For build tools and utilities
### Initial Setup Steps
```bash
# 1. Clone the FreeRTOS-RP2040 repository as reference
git clone --recursive https://github.com/smittytone/RP2040-FreeRTOS.git reference/
# 2. Set up Pico SDK environment variable
export PICO_SDK_PATH=/path/to/pico-sdk
# 3. Install required tools
# macOS:
brew install cmake python3 gcc-arm-embedded
# Linux:
sudo apt update
sudo apt install cmake gcc-arm-none-eabi libnewlib-arm-none-eabi build-essential
```
## Project Architecture
### Core Components
1. **FreeRTOS Kernel Integration**
- Task scheduling for time-critical operations
- Inter-task communication via queues
- Software timers for periodic updates
- Interrupt handling for PPS and timing signals
2. **Network Stack (CH9120)**
- Ethernet controller management
- TCP/UDP protocol implementation
- NTP client/server functionality
- PTP protocol stack
3. **Timing Core**
- High-precision time keeping
- Clock synchronization algorithms
- Time source arbitration
- Drift compensation
4. **Protocol Handlers**
- NTP: RFC 5905 implementation
- PTP: IEEE 1588 implementation
- IRIG: Time code generation/decoding
- GPS: NMEA/UBX parsing
- PPS: Edge detection and timestamping
### Task Structure
```
Main Tasks:
├── Network Task (Priority: High)
│ ├── Ethernet management
│ ├── Protocol handling
│ └── Packet processing
├── Timing Task (Priority: Critical)
│ ├── Clock maintenance
│ ├── Synchronization
│ └── Drift correction
├── Input Task (Priority: High)
│ ├── GPS parsing
│ ├── PPS handling
│ └── IRIG decoding
├── Output Task (Priority: Normal)
│ ├── NTP server
│ ├── PTP master
│ └── IRIG-A generation
└── Management Task (Priority: Low)
├── Configuration
├── Monitoring
└── Statistics
```
## Build Configuration
### CMake Structure
```cmake
# Main CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
include(pico_sdk_import.cmake)
project(precision_timing_tool)
pico_sdk_init()
# Add FreeRTOS
add_subdirectory(FreeRTOS-Kernel)
# Project sources
add_executable(timing_tool
src/main.c
src/network/ch9120.c
src/network/ntp.c
src/network/ptp.c
src/timing/clock.c
src/timing/sync.c
src/io/gps.c
src/io/pps.c
src/io/irig.c
)
# Link libraries
target_link_libraries(timing_tool
pico_stdlib
hardware_spi
hardware_i2c
hardware_dma
hardware_pio
hardware_timer
FreeRTOS
)
```
## Hardware Connections
### Pin Assignments
```
CH9120 Ethernet Controller:
- UART1 TX: GPIO 20
- UART1 RX: GPIO 21
- CFG: GPIO 18
- RES: GPIO 19
GPS Module:
- UART0 TX: GPIO 0
- UART0 RX: GPIO 1
- PPS: GPIO 2 (interrupt)
IRIG Interface:
- Input: GPIO 3 (capture)
- Output: GPIO 4 (PWM)
Status LEDs:
- System: GPIO 25
- GPS Lock: GPIO 26
- Network: GPIO 27
- PTP Sync: GPIO 28
```
## Development Workflow
1. **Initial Development**
- Set up basic FreeRTOS tasks
- Implement CH9120 driver
- Create timing core structure
2. **Protocol Implementation**
- Start with NTP client
- Add GPS time source
- Implement PPS interrupt handler
- Add NTP server functionality
3. **Advanced Features**
- PTP implementation
- IRIG encoding/decoding
- Clock discipline algorithms
- Web configuration interface
4. **Testing & Validation**
- Unit tests for protocol handlers
- Integration tests with reference clocks
- Long-term stability testing
- Network stress testing
## Configuration
### FreeRTOSConfig.h Key Settings
```c
#define configUSE_PREEMPTION 1
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0
#define configUSE_TICKLESS_IDLE 0
#define configCPU_CLOCK_HZ 133000000
#define configTICK_RATE_HZ 1000
#define configMAX_PRIORITIES 32
#define configMINIMAL_STACK_SIZE 256
#define configTOTAL_HEAP_SIZE (128 * 1024)
#define configUSE_MUTEXES 1
#define configUSE_RECURSIVE_MUTEXES 1
#define configUSE_COUNTING_SEMAPHORES 1
#define configQUEUE_REGISTRY_SIZE 8
#define configUSE_QUEUE_SETS 1
#define configUSE_TIME_SLICING 1
```
## Debugging
### Debug Output
- UART0: GPS data (when not connected)
- USB Serial: Debug console
- SWD: Hardware debugging
### Performance Monitoring
- FreeRTOS task statistics
- Network packet counters
- Time synchronization metrics
- Clock drift measurements
## Next Steps
1. Create project structure based on FreeRTOS template
2. Implement basic CH9120 communication
3. Add GPS NMEA parser
4. Implement NTP client
5. Add PPS interrupt handler
6. Create basic web interface
7. Implement additional protocols
## Innovative Ideas
1. **Multi-source Time Fusion**
- Kalman filter for optimal time estimation
- Automatic source quality assessment
- Seamless failover between sources
2. **Adaptive Network Timing**
- Machine learning for network delay prediction
- Dynamic packet rate adjustment
- Congestion-aware protocol selection
3. **Hardware Timestamping**
- PIO state machines for precise capture
- DMA-based packet timestamping
- Sub-microsecond accuracy
4. **Configuration Options**
- Web-based management interface
- SNMP monitoring
- REST API for integration
- Mobile app for configuration

257
PROJECT_STRUCTURE.md Normal file
View File

@@ -0,0 +1,257 @@
# Precision Timing Tool - Project Structure
## Directory Layout
```
precision-timing-tool/
├── CMakeLists.txt # Main build configuration
├── pico_sdk_import.cmake # Pico SDK integration
├── FreeRTOSConfig.h # FreeRTOS configuration
├── README.md # Project documentation
├── DEVELOPMENT_INSTRUCTIONS.md # Development guide
├── PROJECT_STRUCTURE.md # This file
├── src/ # Source code
│ ├── main.c # Application entry point
│ ├── config.h # System configuration
│ │
│ ├── freertos/ # FreeRTOS specific
│ │ ├── tasks.c # Task definitions
│ │ ├── tasks.h
│ │ └── hooks.c # FreeRTOS hooks
│ │
│ ├── drivers/ # Hardware drivers
│ │ ├── ch9120/ # Ethernet controller
│ │ │ ├── ch9120.c
│ │ │ ├── ch9120.h
│ │ │ └── ch9120_config.h
│ │ ├── gps/ # GPS receiver
│ │ │ ├── gps.c
│ │ │ ├── gps.h
│ │ │ └── nmea_parser.c
│ │ └── hardware/ # RP2040 hardware
│ │ ├── pps.c # PPS interrupt handler
│ │ ├── pps.h
│ │ ├── rtc.c # Real-time clock
│ │ └── rtc.h
│ │
│ ├── network/ # Network protocols
│ │ ├── ntp/ # NTP implementation
│ │ │ ├── ntp_client.c
│ │ │ ├── ntp_server.c
│ │ │ ├── ntp_common.h
│ │ │ └── ntp_packet.h
│ │ ├── ptp/ # PTP implementation
│ │ │ ├── ptp_clock.c
│ │ │ ├── ptp_messages.c
│ │ │ ├── ptp_common.h
│ │ │ └── ptp_types.h
│ │ └── network_stack.c # Common network functions
│ │
│ ├── timing/ # Timing core
│ │ ├── clock_discipline.c # Clock sync algorithms
│ │ ├── clock_discipline.h
│ │ ├── time_sources.c # Time source management
│ │ ├── time_sources.h
│ │ ├── timebase.c # System timebase
│ │ └── timebase.h
│ │
│ ├── protocols/ # Time code protocols
│ │ ├── irig/ # IRIG time codes
│ │ │ ├── irig_decoder.c
│ │ │ ├── irig_encoder.c
│ │ │ └── irig_common.h
│ │ └── timecode.h # Common time code interface
│ │
│ ├── utils/ # Utility functions
│ │ ├── circular_buffer.c
│ │ ├── circular_buffer.h
│ │ ├── statistics.c # Timing statistics
│ │ ├── statistics.h
│ │ └── debug.h # Debug macros
│ │
│ └── web/ # Web interface
│ ├── web_server.c
│ ├── web_server.h
│ ├── api_handlers.c # REST API
│ └── html_content.h # Embedded HTML
├── lib/ # External libraries
│ ├── FreeRTOS-Kernel/ # FreeRTOS submodule
│ └── pico-sdk/ # Pico SDK submodule
├── test/ # Unit tests
│ ├── test_ntp.c
│ ├── test_ptp.c
│ ├── test_clock.c
│ └── CMakeLists.txt
├── tools/ # Development tools
│ ├── deploy.sh # Deployment script
│ ├── monitor.py # Serial monitor
│ └── time_client.py # Test client
├── docs/ # Documentation (already created)
│ ├── hardware/
│ ├── software/
│ ├── examples/
│ ├── freertos/
│ └── timing/
└── build/ # Build output (generated)
└── timing_tool.uf2 # Firmware binary
```
## Module Descriptions
### Core Modules
#### Main Application (`src/main.c`)
- System initialization
- FreeRTOS scheduler start
- Hardware configuration
- Task creation
#### FreeRTOS Tasks (`src/freertos/tasks.c`)
```c
// Task priorities (higher number = higher priority)
#define TASK_PRIORITY_TIMING (configMAX_PRIORITIES - 1) // Critical
#define TASK_PRIORITY_PPS (configMAX_PRIORITIES - 2) // High
#define TASK_PRIORITY_NETWORK (configMAX_PRIORITIES - 3) // High
#define TASK_PRIORITY_GPS (configMAX_PRIORITIES - 4) // Normal
#define TASK_PRIORITY_OUTPUT (configMAX_PRIORITIES - 5) // Normal
#define TASK_PRIORITY_WEB (configMAX_PRIORITIES - 6) // Low
#define TASK_PRIORITY_STATS (configMAX_PRIORITIES - 7) // Low
```
### Hardware Drivers
#### CH9120 Ethernet (`src/drivers/ch9120/`)
- UART communication with CH9120
- Network configuration
- Packet transmission/reception
- TCP/UDP socket management
#### GPS Driver (`src/drivers/gps/`)
- NMEA sentence parsing
- Time extraction
- Position data (for fixed installations)
- PPS synchronization
### Network Protocols
#### NTP Implementation (`src/network/ntp/`)
- Client: Time synchronization
- Server: Time distribution
- Stratum management
- Authentication support
#### PTP Implementation (`src/network/ptp/`)
- Best Master Clock Algorithm
- Sync message generation
- Delay measurement
- Hardware timestamping hooks
### Timing Core
#### Clock Discipline (`src/timing/clock_discipline.c`)
- Phase-locked loop (PLL)
- Frequency-locked loop (FLL)
- Hybrid PLL/FLL algorithm
- Drift compensation
#### Time Sources (`src/timing/time_sources.c`)
- Source priority management
- Quality assessment
- Automatic failover
- Source statistics
## Build System
### CMake Configuration
```cmake
# Feature flags
option(ENABLE_NTP "Enable NTP protocol" ON)
option(ENABLE_PTP "Enable PTP protocol" ON)
option(ENABLE_GPS "Enable GPS support" ON)
option(ENABLE_IRIG "Enable IRIG support" ON)
option(ENABLE_WEB "Enable web interface" ON)
option(DEBUG_OUTPUT "Enable debug output" OFF)
```
### Memory Layout
```
RAM Usage (264KB total):
- FreeRTOS heap: 128KB
- Network buffers: 32KB
- Time data structures: 16KB
- Stack space: 32KB
- BSS/Data: ~56KB
Flash Usage (4MB total):
- Application code: ~256KB
- Web content: ~64KB
- Configuration: 4KB
- Reserved: ~3.7MB
```
## Configuration Files
### System Configuration (`src/config.h`)
```c
// Network settings
#define DEFAULT_IP_ADDRESS "192.168.1.100"
#define DEFAULT_SUBNET_MASK "255.255.255.0"
#define DEFAULT_GATEWAY "192.168.1.1"
// Time source priorities (0 = highest)
#define PRIORITY_GPS 0
#define PRIORITY_PTP 1
#define PRIORITY_NTP 2
#define PRIORITY_IRIG 3
// Timing parameters
#define PLL_UPDATE_INTERVAL_MS 1000
#define DRIFT_COMP_WINDOW_S 3600
#define MAX_OFFSET_JUMP_MS 1000
```
## Inter-Task Communication
### Message Queues
- Time update queue
- Network packet queue
- Configuration queue
- Statistics queue
### Semaphores/Mutexes
- Clock access mutex
- Network resource mutex
- Configuration mutex
- Statistics buffer mutex
### Event Groups
- Time source events
- Network events
- System status events
## Development Guidelines
1. **Coding Standards**
- MISRA-C 2012 compliance where practical
- Consistent naming convention
- Comprehensive error handling
2. **Real-Time Considerations**
- Minimize ISR execution time
- Avoid dynamic memory allocation
- Use fixed-priority preemptive scheduling
3. **Testing Strategy**
- Unit tests for algorithms
- Integration tests for protocols
- System tests with reference clocks
4. **Documentation**
- Doxygen comments for APIs
- Design documents for complex modules
- User manual for configuration

BIN
RP2040-ETH-WS2812B.zip Normal file

Binary file not shown.

BIN
RP2040_ETH_CODE.zip Normal file

Binary file not shown.

View File

@@ -0,0 +1,315 @@
#include "CH9120.h"
UCHAR CH9120_Mode = TCP_CLIENT; //Optional:TCP_SERVER、TCP_CLIENT、UDP_SERVER、UDP_CLIENT
UCHAR CH9120_LOCAL_IP[4] = {192, 168, 10, 205}; // LOCAL IP
UCHAR CH9120_GATEWAY[4] = {192, 168, 11, 1}; // GATEWAY
UCHAR CH9120_SUBNET_MASK[4] = {255, 255, 252, 0}; // SUBNET MASK
UCHAR CH9120_TARGET_IP[4] = {192, 168, 10, 137}; // TARGET_IP
UWORD CH9120_PORT1 = 1000; // LOCAL PORT1
UWORD CH9120_TARGET_PORT = 2000; // TARGET PORT
UDOUBLE CH9120_BAUD_RATE = 115200; // BAUD RATE
UCHAR tx[8] = {0x57, 0xAB};
/******************************************************************************
function: Send four bytes
parameter:
data: parameter
command: command code
Info: Set mode, enable port, clear serial port, switch DHCP, switch port 2
******************************************************************************/
void CH9120_TX_4_bytes(UCHAR data, int command)
{
for (int i = 2; i < 4; i++)
{
if (i == 2)
tx[i] = command;
else
tx[i] = data;
}
DEV_Delay_ms(10);
for (int o = 0; o < 4; o++)
UART_ID1.write(tx[o]);
DEV_Delay_ms(10);
for (int i = 2; i < 4; i++)
tx[i] = 0;
}
/******************************************************************************
function: Send five bytes
parameter:
data: parameter
command: command code
Info: Set the local port and target port
******************************************************************************/
void CH9120_TX_5_bytes(UWORD data, int command)
{
UCHAR Port[2];
Port[0] = data & 0xff;
Port[1] = data >> 8;
for (int i = 2; i < 5; i++)
{
if (i == 2)
tx[i] = command;
else
tx[i] = Port[i - 3];
}
DEV_Delay_ms(10);
for (int o = 0; o < 5; o++)
UART_ID1.write(tx[o]);
DEV_Delay_ms(10);
for (int i = 2; i < 5; i++)
tx[i] = 0;
}
/******************************************************************************
function: Send seven bytes
parameter:
data: parameter
command: command code
Info: Set the IP address, subnet mask, gateway,
******************************************************************************/
void CH9120_TX_7_bytes(UCHAR data[], int command)
{
for (int i = 2; i < 7; i++)
{
if (i == 2)
tx[i] = command;
else
tx[i] = data[i - 3];
}
DEV_Delay_ms(10);
for (int o = 0; o < 7; o++)
UART_ID1.write(tx[o]);
DEV_Delay_ms(10);
for (int i = 2; i < 7; i++)
tx[i] = 0;
}
/******************************************************************************
function: CH9120_TX_BAUD
parameter:
data: parameter
command: command code
Info: Set baud rate
******************************************************************************/
void CH9120_TX_BAUD(UDOUBLE data, int command)
{
UCHAR Port[4];
Port[0] = (data & 0xff);
Port[1] = (data >> 8) & 0xff;
Port[2] = (data >> 16) & 0xff;
Port[3] = data >> 24;
for (int i = 2; i < 7; i++)
{
if (i == 2)
tx[i] = command;
else
tx[i] = Port[i - 3];
}
DEV_Delay_ms(10);
for (int o = 0; o < 7; o++)
UART_ID1.write(tx[o]);
DEV_Delay_ms(10);
for (int i = 2; i < 7; i++)
tx[i] = 0;
}
/******************************************************************************
function: CH9120_Start
parameter:
Info: Start configuration Parameters
******************************************************************************/
void CH9120_Start(void)
{
digitalWrite(CFG_PIN, 0);
digitalWrite(RES_PIN, 1);
DEV_Delay_ms(500);
}
/******************************************************************************
function: CH9120_End
parameter:
Info: Updating configuration Parameters
******************************************************************************/
void CH9120_End(void)
{
tx[2] = 0x0d;
for (int o = 0; o < 3; o++)
UART_ID1.write(tx[o]);
DEV_Delay_ms(200);
tx[2] = 0x0e;
for (int o = 0; o < 3; o++)
UART_ID1.write(tx[o]);
DEV_Delay_ms(200);
tx[2] = 0x5e;
for (int o = 0; o < 3; o++)
UART_ID1.write(tx[o]);
DEV_Delay_ms(500);
gpio_put(CFG_PIN, 1);
}
/******************************************************************************
Function: CH9120_SetMode
Parameters:
Mode: Mode parameter
Info: Configure communication mode
******************************************************************************/
void CH9120_SetMode(UCHAR Mode)
{
CH9120_TX_4_bytes(Mode, Mode1); //Mode
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetLocalIP
Parameters:
CH9120_LOCAL_IP: Local IP parameter
Info: Configure local IP
******************************************************************************/
void CH9120_SetLocalIP(UCHAR CH9120_LOCAL_IP[])
{
CH9120_TX_7_bytes(CH9120_LOCAL_IP, LOCAL_IP); //LOCALIP
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetSubnetMask
Parameters:
CH9120_SUBNET_MASK: SUBNET MASK parameter
Info: Configure subnet mask
******************************************************************************/
void CH9120_SetSubnetMask(UCHAR CH9120_SUBNET_MASK[])
{
CH9120_TX_7_bytes(CH9120_SUBNET_MASK, SUBNET_MASK); //SUBNET MASK
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetGateway
Parameters:
CH9120_GATEWAY: Gateway parameter
Info: Configure gateway
******************************************************************************/
void CH9120_SetGateway(UCHAR CH9120_GATEWAY[])
{
CH9120_TX_7_bytes(CH9120_GATEWAY, GATEWAY); //GATEWAY
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetTargetIP
Parameters:
CH9120_TARGET_IP: Target IP parameter
Info: Configure target IP
******************************************************************************/
void CH9120_SetTargetIP(UCHAR CH9120_TARGET_IP[])
{
CH9120_TX_7_bytes(CH9120_TARGET_IP, TARGET_IP1); //TARGET IP
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetLocalPort
Parameters:
CH9120_PORT: Local Port parameter
Info: Configure local port number
******************************************************************************/
void CH9120_SetLocalPort(UWORD CH9120_PORT)
{
CH9120_TX_5_bytes(CH9120_PORT, LOCAL_PORT1); //Local port
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetTargetPort
Parameters:
CH9120_TARGET_PORT: Target Port parameter
Info: Configure target port number
******************************************************************************/
void CH9120_SetTargetPort(UWORD CH9120_TARGET_PORT)
{
CH9120_TX_5_bytes(CH9120_TARGET_PORT, TARGET_PORT1); //Target port
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetBaudRate
Parameters:
CH9120_BAUD_RATE: Baud Rate parameter
Info: Configure communication baud rate
******************************************************************************/
void CH9120_SetBaudRate(UDOUBLE CH9120_BAUD_RATE)
{
CH9120_TX_BAUD(CH9120_BAUD_RATE, UART1_BAUD1); //Port 1 baud rate
DEV_Delay_ms(100);
}
/**
* delay x ms
**/
void DEV_Delay_ms(UDOUBLE xms)
{
delay(xms);
}
void DEV_Delay_us(UDOUBLE xus)
{
delayMicroseconds(xus);
}
/******************************************************************************
function: CH9120_init
parameter:
Info: Initialize CH9120
******************************************************************************/
void CH9120_init(void)
{
Serial.begin(115200);
delay(1000);
UART_ID1.setTX(UART_TX_PIN1);
UART_ID1.setRX(UART_RX_PIN1);
UART_ID1.begin(Inti_BAUD_RATE);
pinMode(CFG_PIN,OUTPUT);
pinMode(RES_PIN,OUTPUT);
CH9120_Start();
CH9120_SetMode(CH9120_Mode); //Mode
CH9120_SetLocalIP(CH9120_LOCAL_IP); //LOCALIP
CH9120_SetSubnetMask(CH9120_SUBNET_MASK); //SUBNET MASK
CH9120_SetGateway(CH9120_GATEWAY); //GATEWAY
CH9120_SetTargetIP(CH9120_TARGET_IP); //TARGET IP
CH9120_SetLocalPort(CH9120_PORT1); //Local port
CH9120_SetTargetPort(CH9120_TARGET_PORT); //Target port
CH9120_SetBaudRate(CH9120_BAUD_RATE); //Port 1 baud rate
CH9120_End();
UART_ID1.begin(Transport_BAUD_RATE);
while (UART_ID1.available())
{
UBYTE ch1 = UART_ID1.read();
}
}
/******************************************************************************
function: RX_TX
parameter:
Info: Serial port 1 and serial port 2 receive and dispatch
******************************************************************************/
void RX_TX()
{
while (1)
{
while (UART_ID1.available())
{
UCHAR ch1 = UART_ID1.read();
UART_ID1.write(ch1);
// Serial.print((char)ch1);
}
}
}

View File

@@ -0,0 +1,54 @@
#ifndef _CH9120_H_
#define _CH9120_H_
#include <Arduino.h>
#include <stdlib.h> // malloc() free()
#include <stdio.h>
/// \tag::uart_advanced[]
#define UART_ID1 Serial2
#define Inti_BAUD_RATE 9600
#define Transport_BAUD_RATE 115200
#define DATA_BITS 8
#define STOP_BITS 1
#define PARITY UART_PARITY_NONE
// We are using pins 0 and 1, but see the GPIO function select table in the
// datasheet for information on which other pins can be used.
#define UART_TX_PIN1 20
#define UART_RX_PIN1 21
#define CFG_PIN 18
#define RES_PIN 19
#define GPIO_OUT 1
#define GPIO_IN 0
#define UCHAR unsigned char
#define UBYTE uint8_t
#define UWORD uint16_t
#define UDOUBLE uint32_t
#define TCP_SERVER 0
#define TCP_CLIENT 1
#define UDP_SERVER 2
#define UDP_CLIENT 3
#define Mode1 0x10 //Port 1: Setup Mode 0x00:TCP Server 0x01:TCP Client 0x02:UDP Server 0x03:UDP Client
#define LOCAL_IP 0x11 //Local IP
#define SUBNET_MASK 0x12 //Subnet Mask
#define GATEWAY 0x13 //Gateway
#define LOCAL_PORT1 0X14 //Port 1:Local Port
#define TARGET_IP1 0x15 //Port 1:Target IP
#define TARGET_PORT1 0x16 //Port 1:Target Port
#define PORT_RANDOM_ENABLE1 0x17 //Port 1:Port Random Enable
#define UART1_BAUD1 0x21 //Port 1:Baud rate of serial port 1
void CH9120_init(void);
void RX_TX();
void DEV_Delay_ms(UDOUBLE xms);
void DEV_Delay_us(UDOUBLE xus);
#endif

View File

@@ -0,0 +1,10 @@
#include "CH9120.h"
void setup() {
CH9120_init();
RX_TX();
}
void loop() {
}

View File

@@ -0,0 +1,29 @@
cmake_minimum_required(VERSION 3.12)
include(pico_sdk_import.cmake)
project(Pico_ePaper_Code)
pico_sdk_init()
#添加编译子目录
add_subdirectory(lib/CH9120)
add_subdirectory(examples)
#添加头文件目录
include_directories(examples)
include_directories(./lib/CH9120)
# 生成可执行文件
add_executable(main
main.c
)
# enable usb output, disable uart output
pico_enable_stdio_usb(main 1)
pico_enable_stdio_uart(main 1)
# create map/bin/hex/uf2 file etc.
pico_add_extra_outputs(main)
target_link_libraries(main examples CH9120 pico_stdlib hardware_spi)

View File

@@ -0,0 +1,45 @@
/*****************************************************************************
* | File : CH9120_Test.h
* | Author : Waveshare team
* | Function : RP2040 ETH test Demo
* | Info :
*----------------
* | This version: V1.0
* | Date : 2023-04-01
* | Info :
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
******************************************************************************/
#ifndef _CH9120_TEST_H_
#define _CH9120_TEST_H_
#include "CH9120.h"
extern UCHAR CH9120_LOCAL_IP[4];
extern UCHAR CH9120_GATEWAY[4];
extern UCHAR CH9120_SUBNET_MASK[4];
extern UCHAR CH9120_TARGET_IP[4];
extern UWORD CH9120_PORT1;
extern UWORD CH9120_TARGET_PORT;
extern UDOUBLE CH9120_BAUD_RATE;
int Pico_ETH_CH9120_test(void);
#endif

View File

@@ -0,0 +1,9 @@
# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_examples_SRCS 变量
aux_source_directory(. DIR_examples_SRCS)
include_directories(../lib/CH9120)
# 生成链接库
add_library(examples ${DIR_examples_SRCS})
target_link_libraries(examples PUBLIC CH9120)

View File

@@ -0,0 +1,36 @@
/*****************************************************************************
* | File : RP2040_ETH_CH9120_test.c
* | Author : Waveshare team
* | Function : Pico_ETH_CH9120 test demo
* | Info :
*----------------
* | This version: V1.0
* | Date : 2023-04-01
* | Info :
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
******************************************************************************/
#include "CH9120_Test.h"
int Pico_ETH_CH9120_test(void)
{
CH9120_init(); //Initialize Configuration CH9120
RX_TX(); //receive and dispatch
}

View File

@@ -0,0 +1,313 @@
#include "CH9120.h"
UCHAR CH9120_Mode = TCP_CLIENT; //Optional:TCP_SERVER、TCP_CLIENT、UDP_SERVER、UDP_CLIENT
UCHAR CH9120_LOCAL_IP[4] = {192, 168, 1, 200}; // LOCAL IP
UCHAR CH9120_GATEWAY[4] = {192, 168, 1, 1}; // GATEWAY
UCHAR CH9120_SUBNET_MASK[4] = {255, 255, 255, 0}; // SUBNET MASK
UCHAR CH9120_TARGET_IP[4] = {192, 168, 1, 10}; // TARGET_IP
UWORD CH9120_PORT1 = 1000; // LOCAL PORT1
UWORD CH9120_TARGET_PORT = 2000; // TARGET PORT
UDOUBLE CH9120_BAUD_RATE = 115200; // BAUD RATE
UCHAR tx[8] = {0x57, 0xAB};
/******************************************************************************
function: Send four bytes
parameter:
data: parameter
command: command code
Info: Set mode, enable port, clear serial port, switch DHCP, switch port 2
******************************************************************************/
void CH9120_TX_4_bytes(UCHAR data, int command)
{
for (int i = 2; i < 4; i++)
{
if (i == 2)
tx[i] = command;
else
tx[i] = data;
}
DEV_Delay_ms(10);
for (int o = 0; o < 4; o++)
uart_putc(UART_ID1, tx[o]);
DEV_Delay_ms(10);
for (int i = 2; i < 4; i++)
tx[i] = 0;
}
/******************************************************************************
function: Send five bytes
parameter:
data: parameter
command: command code
Info: Set the local port and target port
******************************************************************************/
void CH9120_TX_5_bytes(UWORD data, int command)
{
UCHAR Port[2];
Port[0] = data & 0xff;
Port[1] = data >> 8;
for (int i = 2; i < 5; i++)
{
if (i == 2)
tx[i] = command;
else
tx[i] = Port[i - 3];
}
DEV_Delay_ms(10);
for (int o = 0; o < 5; o++)
uart_putc(UART_ID1, tx[o]);
DEV_Delay_ms(10);
for (int i = 2; i < 5; i++)
tx[i] = 0;
}
/******************************************************************************
function: Send seven bytes
parameter:
data: parameter
command: command code
Info: Set the IP address, subnet mask, gateway,
******************************************************************************/
void CH9120_TX_7_bytes(UCHAR data[], int command)
{
for (int i = 2; i < 7; i++)
{
if (i == 2)
tx[i] = command;
else
tx[i] = data[i - 3];
}
DEV_Delay_ms(10);
for (int o = 0; o < 7; o++)
uart_putc(UART_ID1, tx[o]);
DEV_Delay_ms(10);
for (int i = 2; i < 7; i++)
tx[i] = 0;
}
/******************************************************************************
function: CH9120_TX_BAUD
parameter:
data: parameter
command: command code
Info: Set baud rate
******************************************************************************/
void CH9120_TX_BAUD(UDOUBLE data, int command)
{
UCHAR Port[4];
Port[0] = (data & 0xff);
Port[1] = (data >> 8) & 0xff;
Port[2] = (data >> 16) & 0xff;
Port[3] = data >> 24;
for (int i = 2; i < 7; i++)
{
if (i == 2)
tx[i] = command;
else
tx[i] = Port[i - 3];
}
DEV_Delay_ms(10);
for (int o = 0; o < 7; o++)
uart_putc(UART_ID1, tx[o]);
DEV_Delay_ms(10);
for (int i = 2; i < 7; i++)
tx[i] = 0;
}
/******************************************************************************
function: CH9120_Start
parameter:
Info: Start configuration Parameters
******************************************************************************/
void CH9120_Start()
{
gpio_put(RES_PIN, 1);
gpio_put(CFG_PIN, 0);
DEV_Delay_ms(500);
}
/******************************************************************************
function: CH9120_End
parameter:
Info: Updating configuration Parameters
******************************************************************************/
void CH9120_End()
{
tx[2] = 0x0d;
uart_puts(UART_ID1, tx);
DEV_Delay_ms(200);
tx[2] = 0x0e;
uart_puts(UART_ID1, tx);
DEV_Delay_ms(200);
tx[2] = 0x5e;
uart_puts(UART_ID1, tx);
DEV_Delay_ms(200);
gpio_put(CFG_PIN, 1);
}
/******************************************************************************
Function: CH9120_SetMode
Parameters:
Mode: Mode parameter
Info: Configure communication mode
******************************************************************************/
void CH9120_SetMode(UCHAR Mode)
{
CH9120_TX_4_bytes(Mode, Mode1); //Mode
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetLocalIP
Parameters:
CH9120_LOCAL_IP: Local IP parameter
Info: Configure local IP
******************************************************************************/
void CH9120_SetLocalIP(UCHAR CH9120_LOCAL_IP[])
{
CH9120_TX_7_bytes(CH9120_LOCAL_IP, LOCAL_IP); //LOCALIP
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetSubnetMask
Parameters:
CH9120_SUBNET_MASK: SUBNET MASK parameter
Info: Configure subnet mask
******************************************************************************/
void CH9120_SetSubnetMask(UCHAR CH9120_SUBNET_MASK[])
{
CH9120_TX_7_bytes(CH9120_SUBNET_MASK, SUBNET_MASK); //SUBNET MASK
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetGateway
Parameters:
CH9120_GATEWAY: Gateway parameter
Info: Configure gateway
******************************************************************************/
void CH9120_SetGateway(UCHAR CH9120_GATEWAY[])
{
CH9120_TX_7_bytes(CH9120_GATEWAY, GATEWAY); //GATEWAY
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetTargetIP
Parameters:
CH9120_TARGET_IP: Target IP parameter
Info: Configure target IP
******************************************************************************/
void CH9120_SetTargetIP(UCHAR CH9120_TARGET_IP[])
{
CH9120_TX_7_bytes(CH9120_TARGET_IP, TARGET_IP1); //TARGET IP
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetLocalPort
Parameters:
CH9120_PORT: Local Port parameter
Info: Configure local port number
******************************************************************************/
void CH9120_SetLocalPort(UWORD CH9120_PORT)
{
CH9120_TX_5_bytes(CH9120_PORT, LOCAL_PORT1); //Local port
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetTargetPort
Parameters:
CH9120_TARGET_PORT: Target Port parameter
Info: Configure target port number
******************************************************************************/
void CH9120_SetTargetPort(UWORD CH9120_TARGET_PORT)
{
CH9120_TX_5_bytes(CH9120_TARGET_PORT, TARGET_PORT1); //Target port
DEV_Delay_ms(100);
}
/******************************************************************************
Function: CH9120_SetBaudRate
Parameters:
CH9120_BAUD_RATE: Baud Rate parameter
Info: Configure communication baud rate
******************************************************************************/
void CH9120_SetBaudRate(UDOUBLE CH9120_BAUD_RATE)
{
CH9120_TX_BAUD(CH9120_BAUD_RATE, UART1_BAUD1); //Port 1 baud rate
DEV_Delay_ms(100);
}
/**
* delay x ms
**/
void DEV_Delay_ms(UDOUBLE xms)
{
sleep_ms(xms);
}
void DEV_Delay_us(UDOUBLE xus)
{
sleep_us(xus);
}
/******************************************************************************
function: CH9120_init
parameter:
Info: Initialize CH9120
******************************************************************************/
void CH9120_init(void)
{
stdio_init_all();
uart_init(UART_ID1, Inti_BAUD_RATE);
gpio_set_function(UART_TX_PIN1, GPIO_FUNC_UART);
gpio_set_function(UART_RX_PIN1, GPIO_FUNC_UART);
gpio_init(CFG_PIN);
gpio_init(RES_PIN);
gpio_set_dir(CFG_PIN, GPIO_OUT);
gpio_set_dir(RES_PIN, GPIO_OUT);
CH9120_Start();
CH9120_SetMode(CH9120_Mode); //Mode
CH9120_SetLocalIP(CH9120_LOCAL_IP); //LOCALIP
CH9120_SetSubnetMask(CH9120_SUBNET_MASK); //SUBNET MASK
CH9120_SetGateway(CH9120_GATEWAY); //GATEWAY
CH9120_SetTargetIP(CH9120_TARGET_IP); //TARGET IP
CH9120_SetLocalPort(CH9120_PORT1); //Local port
CH9120_SetTargetPort(CH9120_TARGET_PORT); //Target port
CH9120_SetBaudRate(CH9120_BAUD_RATE); //Port 1 baud rate
CH9120_End();
uart_set_baudrate(UART_ID1, Transport_BAUD_RATE);
while (uart_is_readable(UART_ID1))
{
UBYTE ch1 = uart_getc(UART_ID1);
}
}
/******************************************************************************
function: RX_TX
parameter:
Info: Serial port 1 and serial port 2 receive and dispatch
******************************************************************************/
void RX_TX()
{
while (1)
{
while (uart_is_readable(UART_ID1))
{
UBYTE ch1 = uart_getc(UART_ID1);
if (uart_is_writable(UART_ID1))
{
uart_putc(UART_ID1, ch1);
}
}
}
}

View File

@@ -0,0 +1,54 @@
#ifndef _CH9120_H_
#define _CH9120_H_
#include <stdlib.h> // malloc() free()
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/uart.h"
#include "hardware/irq.h"
/// \tag::uart_advanced[]
#define UART_ID1 uart1
#define Inti_BAUD_RATE 9600
#define Transport_BAUD_RATE 115200
#define DATA_BITS 8
#define STOP_BITS 1
#define PARITY UART_PARITY_NONE
// We are using pins 0 and 1, but see the GPIO function select table in the
// datasheet for information on which other pins can be used.
#define UART_TX_PIN1 20
#define UART_RX_PIN1 21
#define CFG_PIN 18
#define RES_PIN 19
#define GPIO_OUT 1
#define GPIO_IN 0
#define UCHAR unsigned char
#define UBYTE uint8_t
#define UWORD uint16_t
#define UDOUBLE uint32_t
#define TCP_SERVER 0
#define TCP_CLIENT 1
#define UDP_SERVER 2
#define UDP_CLIENT 3
#define Mode1 0x10 //Port 1: Setup Mode 0x00:TCP Server 0x01:TCP Client 0x02:UDP Server 0x03:UDP Client
#define LOCAL_IP 0x11 //Local IP
#define SUBNET_MASK 0x12 //Subnet Mask
#define GATEWAY 0x13 //Gateway
#define LOCAL_PORT1 0X14 //Port 1:Local Port
#define TARGET_IP1 0x15 //Port 1:Target IP
#define TARGET_PORT1 0x16 //Port 1:Target Port
#define PORT_RANDOM_ENABLE1 0x17 //Port 1:Port Random Enable
#define UART1_BAUD1 0x21 //Port 1:Baud rate of serial port 1
void CH9120_init(void);
void RX_TX();
void DEV_Delay_ms(UDOUBLE xms);
void DEV_Delay_us(UDOUBLE xus);
#endif

View File

@@ -0,0 +1,9 @@
# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_CH9120_SRCS 变量
aux_source_directory(. DIR_CH9120_SRCS)
include_directories(../Config)
# 生成链接库
add_library(CH9120 ${DIR_CH9120_SRCS})
target_link_libraries( CH9120 PUBLIC pico_stdlib hardware_spi)

View File

@@ -0,0 +1,6 @@
#include "CH9120_Test.h"
int main()
{
Pico_ETH_CH9120_test();
}

View File

@@ -0,0 +1,62 @@
# This is a copy of <PICO_SDK_PATH>/external/pico_sdk_import.cmake
# This can be dropped into an external project to help locate this SDK
# It should be include()ed prior to project()
if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH))
set(PICO_SDK_PATH $ENV{PICO_SDK_PATH})
message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')")
endif ()
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT))
set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT})
message("Using PICO_SDK_FETCH_FROM_GIT from environment ('${PICO_SDK_FETCH_FROM_GIT}')")
endif ()
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH))
set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH})
message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')")
endif ()
set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the PICO SDK")
set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of PICO SDK from git if not otherwise locatable")
set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK")
if (NOT PICO_SDK_PATH)
if (PICO_SDK_FETCH_FROM_GIT)
include(FetchContent)
set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR})
if (PICO_SDK_FETCH_FROM_GIT_PATH)
get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")
endif ()
FetchContent_Declare(
pico_sdk
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
GIT_TAG master
)
if (NOT pico_sdk)
message("Downloading PICO SDK")
FetchContent_Populate(pico_sdk)
set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR})
endif ()
set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE})
else ()
message(FATAL_ERROR
"PICO SDK location was not specified. Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT to on to fetch from git. \r\nexport PICO_SDK_PATH=../../pico-sdk"
)
endif ()
endif ()
get_filename_component(PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")
if (NOT EXISTS ${PICO_SDK_PATH})
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found")
endif ()
set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake)
if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE})
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' does not appear to contain the PICO SDK")
endif ()
set(PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to the PICO SDK" FORCE)
include(${PICO_SDK_INIT_CMAKE_FILE})

View File

@@ -0,0 +1,45 @@
from machine import UART, Pin
from mqtt_client import MQTTClient
from ch9120 import CH9120
import time
# CH9120
MODE = 1 #0:TCP Server 1:TCP Client 2:UDP Server 3:UDP Client
GATEWAY = (192, 168, 1, 1) # GATEWAY
TARGET_IP = (192, 168, 1, 10) # TARGET_IP
LOCAL_IP = (192, 168, 1, 200) # LOCAL_IP
SUBNET_MASK = (255,255,255,0) # SUBNET_MASK
LOCAL_PORT1 = 1000 # LOCAL_PORT1
TARGET_PORT = 2000 # TARGET_PORT
BAUD_RATE = 115200 # BAUD_RATE
uart1 = UART(1, baudrate=9600, tx=Pin(20), rx=Pin(21))
def ch9120_configure():
# Configure
global uart1
ch9120 = CH9120(uart1)
ch9120.enter_config() # enter configuration mode
ch9120.set_mode(MODE) # 0:TCP Server 1:TCP Client 2:UDP Server 3:UDP Client
ch9120.set_localIP(LOCAL_IP)
ch9120.set_subnetMask(SUBNET_MASK)
ch9120.set_gateway(GATEWAY)
ch9120.set_localPort(LOCAL_PORT1)
ch9120.set_targetIP(TARGET_IP)
ch9120.set_targetPort(TARGET_PORT)
ch9120.set_baudRate(BAUD_RATE)
ch9120.exit_config() # exit configuration mode
# Clear cache and reconfigure uart1
uart1.read(uart1.any())
time.sleep(0.5)
uart1 = UART(1, baudrate=115200, tx=Pin(20), rx=Pin(21))
if __name__ == "__main__":
ch9120_configure()
while True:
time.sleep(0.1)
while uart1.any() > 0:
rxData1 = uart1.read(uart1.any())
uart1.write(rxData1)
print(rxData1.decode('utf8'))

View File

@@ -0,0 +1,74 @@
from machine import UART, Pin
import time
class CH9120:
def __init__(self, uart):
self.uart = uart
self.MODE = 1 #0:TCP Server 1:TCP Client 2:UDP Server 3:UDP Client
self.GATEWAY = (192, 168, 11, 1) # GATEWAY
self.TARGET_IP = (47, 92, 129, 18) # TARGET_IP
self.LOCAL_IP = (192, 168, 10, 200) # LOCAL_IP
self.SUBNET_MASK = (255,255,252,0) # SUBNET_MASK
self.LOCAL_PORT = 1000 # LOCAL_PORT1
self.TARGET_PORT = 1883 # TARGET_PORT
self.BAUD_RATE = 115200 # BAUD_RATE
self.CFG = Pin(18, Pin.OUT,Pin.PULL_UP)
self.RST = Pin(19, Pin.OUT,Pin.PULL_UP)
def enter_config(self):
print("begin")
self.RST.value(1)
self.CFG.value(0)
time.sleep(0.5)
def exit_config(self):
self.uart.write(b'\x57\xab\x0D')
time.sleep(0.1)
self.uart.write(b'\x57\xab\x0E')
time.sleep(0.1)
self.uart.write(b'\x57\xab\x5E')
time.sleep(0.1)
self.CFG.value(1)
time.sleep(0.1)
print("end")
def set_mode(self,MODE):
self.MODE = MODE
self.uart.write(b'\x57\xab\x10' + self.MODE.to_bytes(1, 'little'))#Convert int to bytes
time.sleep(0.1)
def set_localIP(self,LOCAL_IP):
self.LOCAL_IP = LOCAL_IP
self.uart.write(b'\x57\xab\x11' + bytes(self.LOCAL_IP))#Converts the int tuple to bytes
time.sleep(0.1)
def set_subnetMask(self,SUBNET_MASK):
self.SUBNET_MASK = SUBNET_MASK
self.uart.write(b'\x57\xab\x12' + bytes(self.SUBNET_MASK))
time.sleep(0.1)
def set_gateway(self,GATEWAY):
self.GATEWAY = GATEWAY
self.uart.write(b'\x57\xab\x13' + bytes(self.GATEWAY))
time.sleep(0.1)
def set_localPort(self,LOCAL_PORT):
self.LOCAL_PORT = LOCAL_PORT
self.uart.write(b'\x57\xab\x14' + self.LOCAL_PORT.to_bytes(2, 'little'))
time.sleep(0.1)
def set_targetIP(self,TARGET_IP):
self.TARGET_IP = TARGET_IP
self.uart.write(b'\x57\xab\x15' + bytes(self.TARGET_IP))
time.sleep(0.1)
def set_targetPort(self,TARGET_PORT):
self.TARGET_PORT = TARGET_PORT
self.uart.write(b'\x57\xab\x16' + self.TARGET_PORT.to_bytes(2, 'little'))
time.sleep(0.1)
def set_baudRate(self,BAUD_RATE):
self.BAUD_RATE = BAUD_RATE
self.uart.write(b'\x57\xab\x21' + self.BAUD_RATE.to_bytes(4, 'little'))
time.sleep(0.1)

View File

@@ -0,0 +1,86 @@
from machine import UART, Pin
from mqtt_client import MQTTClient
from ch9120 import CH9120
import time
# MQTT
CLIENT_ID = "Waveshare_RP2040_ETH"
SUBSCRIBE_TOPIC = "test_topic1"
PUBLISH_TOPIC = "test_topic2"
# CH9120
MODE = 1 #0:TCP Server 1:TCP Client 2:UDP Server 3:UDP Client
GATEWAY = (192, 168, 1, 1) # GATEWAY
TARGET_IP = (47, 92, 129, 18) # TARGET_IP
LOCAL_IP = (192, 168, 1, 200) # LOCAL_IP
SUBNET_MASK = (255,255,255,0) # SUBNET_MASK
LOCAL_PORT1 = 1000 # LOCAL_PORT1
TARGET_PORT = 1883 # TARGET_PORT
BAUD_RATE = 115200 # BAUD_RATE
uart1 = UART(1, baudrate=9600, tx=Pin(20), rx=Pin(21))
def ch9120_configure():
global uart1
ch9120 = CH9120(uart1)
ch9120.enter_config() # enter configuration mode
ch9120.set_mode(MODE)
ch9120.set_localIP(LOCAL_IP)
ch9120.set_subnetMask(SUBNET_MASK)
ch9120.set_gateway(GATEWAY)
ch9120.set_localPort(LOCAL_PORT1)
ch9120.set_targetIP(TARGET_IP)
ch9120.set_targetPort(TARGET_PORT)
ch9120.set_baudRate(BAUD_RATE)
ch9120.exit_config() # exit configuration mode
# Clear cache and reconfigure uart1
uart1.read(uart1.any())
time.sleep(0.5)
uart1 = UART(1, baudrate=115200, tx=Pin(20), rx=Pin(21))
if __name__ == "__main__":
ch9120_configure()
mqtt_client = MQTTClient(uart1)
mqtt_client.ClientID = CLIENT_ID # Set ClientID
mqtt_client.connect() # Connect to MQTT server
mqtt_client.subscribe(SUBSCRIBE_TOPIC) # Subscribe to topictest_topic1
mqtt_client.send_heartbeat()
last_heartbeat_time = time.time()
time.sleep_ms(60) # Sending the first heartbeat
uart1.read() # Clear unnecessary data
while True:
rxData = uart1.read()
if rxData is not None:
topic, message = mqtt_client.extract_data(rxData) # Parse the received data
if topic == SUBSCRIBE_TOPIC:
print("Topic:", topic)
print("Message:", message)
mqtt_client.publish(PUBLISH_TOPIC, message) # Send received data to topictest_topic2
current_time = time.time()
if current_time - last_heartbeat_time >= 30:
mqtt_client.send_heartbeat() # Send a heartbeat every 30 seconds
last_heartbeat_time = current_time
time.sleep_ms(60) # Waiting for the server to respond
if not mqtt_client.check_heartbeat_response():
while True:
print("Reconnecting...")
mqtt_client = MQTTClient(uart1)
mqtt_client.ClientID = CLIENT_ID # Set ClientID
mqtt_client.connect() # Connect to MQTT server
mqtt_client.subscribe(SUBSCRIBE_TOPIC) # Subscribe to topictest_topic1
time.sleep_ms(200) # Waiting for the server to respond
uart1.read() # Clear unnecessary data
mqtt_client.send_heartbeat() # Sending the first heartbeat
last_heartbeat_time = current_time # Clear unnecessary data
time.sleep_ms(60) # Waiting for the server to respond
if mqtt_client.check_heartbeat_response():
print("Reconnection successful!")
break
time.sleep_ms(20)

View File

@@ -0,0 +1,74 @@
from machine import UART, Pin
import time
class CH9120:
def __init__(self, uart):
self.uart = uart
self.MODE = 1 #0:TCP Server 1:TCP Client 2:UDP Server 3:UDP Client
self.GATEWAY = (192, 168, 11, 1) # GATEWAY
self.TARGET_IP = (47, 92, 129, 18) # TARGET_IP
self.LOCAL_IP = (192, 168, 10, 200) # LOCAL_IP
self.SUBNET_MASK = (255,255,252,0) # SUBNET_MASK
self.LOCAL_PORT = 1000 # LOCAL_PORT1
self.TARGET_PORT = 1883 # TARGET_PORT
self.BAUD_RATE = 115200 # BAUD_RATE
self.CFG = Pin(18, Pin.OUT,Pin.PULL_UP)
self.RST = Pin(19, Pin.OUT,Pin.PULL_UP)
def enter_config(self):
print("begin")
self.RST.value(1)
self.CFG.value(0)
time.sleep(0.5)
def exit_config(self):
self.uart.write(b'\x57\xab\x0D')
time.sleep(0.1)
self.uart.write(b'\x57\xab\x0E')
time.sleep(0.1)
self.uart.write(b'\x57\xab\x5E')
time.sleep(0.1)
self.CFG.value(1)
time.sleep(0.1)
print("end")
def set_mode(self,MODE):
self.MODE = MODE
self.uart.write(b'\x57\xab\x10' + self.MODE.to_bytes(1, 'little'))#Convert int to bytes
time.sleep(0.1)
def set_localIP(self,LOCAL_IP):
self.LOCAL_IP = LOCAL_IP
self.uart.write(b'\x57\xab\x11' + bytes(self.LOCAL_IP))#Converts the int tuple to bytes
time.sleep(0.1)
def set_subnetMask(self,SUBNET_MASK):
self.SUBNET_MASK = SUBNET_MASK
self.uart.write(b'\x57\xab\x12' + bytes(self.SUBNET_MASK))
time.sleep(0.1)
def set_gateway(self,GATEWAY):
self.GATEWAY = GATEWAY
self.uart.write(b'\x57\xab\x13' + bytes(self.GATEWAY))
time.sleep(0.1)
def set_localPort(self,LOCAL_PORT):
self.LOCAL_PORT = LOCAL_PORT
self.uart.write(b'\x57\xab\x14' + self.LOCAL_PORT.to_bytes(2, 'little'))
time.sleep(0.1)
def set_targetIP(self,TARGET_IP):
self.TARGET_IP = TARGET_IP
self.uart.write(b'\x57\xab\x15' + bytes(self.TARGET_IP))
time.sleep(0.1)
def set_targetPort(self,TARGET_PORT):
self.TARGET_PORT = TARGET_PORT
self.uart.write(b'\x57\xab\x16' + self.TARGET_PORT.to_bytes(2, 'little'))
time.sleep(0.1)
def set_baudRate(self,BAUD_RATE):
self.BAUD_RATE = BAUD_RATE
self.uart.write(b'\x57\xab\x21' + self.BAUD_RATE.to_bytes(4, 'little'))
time.sleep(0.1)

View File

@@ -0,0 +1,68 @@
from machine import UART
import time
import ubinascii
class MQTTClient:
def __init__(self, uart):
self.uart = uart
self.ClientID = "Waveshare_RP2040_ETH"
self.connect_message = bytearray([
0x10, # MQTT control packet type (CONNECT)
0x11, # Remaining Length in the fixed header
0x00, 0x04, # Length of the UTF-8 encoded protocol name
0x4D, 0x51, 0x54, 0x54, # MQTT string "MQTT"
0x04, # Protocol Level (MQTT 3.1.1)
0x02, # Connect Flags: Clean Session, No Will, No Will Retain, QoS = 0, No Will Flag, Keep Alive = 60 seconds
0x00, 0x3C # Keep Alive Time in seconds
])
def connect(self):
byte_array = bytes(self.ClientID, "utf-8")
length = len(byte_array)
self.connect_message.extend(length.to_bytes(2, 'big')) # Length of the Client ID
self.connect_message.extend(byte_array) # Client ID
self.connect_message[1] = len(self.connect_message) - 2 # Change Length
self.uart.write(bytes(self.connect_message))
def publish(self, topic, message):
publish_message = bytearray([
0x30, 0x11, # MQTT control packet type (PUBLISH)
0x00, 0x0A # Length of the topic name
])
publish_message.extend(bytes(topic, "utf-8")) # Topic
publish_message.extend(bytes(message, "utf-8")) # Message content
publish_message[1] = len(publish_message) - 2 # Change Length
publish_message[3] = len(bytes(topic, "utf-8")) # Change Length
self.uart.write(bytes(publish_message))
def subscribe(self, topic):
subscribe_message = bytearray([
0x82, 0x0A, # MQTT control packet type (SUBSCRIBE)
0x00, 0x01 # Remaining length
])
byte_array = bytes(topic, "utf-8")
length = len(byte_array)
subscribe_message.extend(length.to_bytes(2, 'big')) # Length of the topic name
subscribe_message.extend(byte_array) # Topic
subscribe_message.extend(bytes([0x00])) # qos
subscribe_message[1] = len(subscribe_message) - 2 # Change Length
self.uart.write(bytes(subscribe_message))
def send_heartbeat(self):
heartbeat_message = bytearray([0xC0, 0x00])# Heartbeat message to keep the connection alive
self.uart.write(heartbeat_message)
def check_heartbeat_response(self):
response = self.uart.read()# Check for PINGRESP message
if response == bytes([0xD0, 0x00]):
return True
else:
return False
def extract_data(self, rxData):
rxArray = bytearray()
rxArray.extend(rxData)
topic = rxArray[4:4 + rxArray[3]].decode('utf-8')
message = rxArray[4 + rxArray[3]:rxArray[1] + 2].decode('utf-8')
return topic, message

View File

@@ -0,0 +1,41 @@
# Generated Cmake Pico project file
cmake_minimum_required(VERSION 3.13)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)
# initalize pico_sdk from installed location
# (note this can come from environment, CMake cache etc)
#set(PICO_SDK_PATH "D:/Raspberry/Pico-Code/pico-sdk")
# Pull in Raspberry Pi Pico SDK (must be before project)
include(pico_sdk_import.cmake)
project(RP2040_WS2812B_Test 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(RP2040_WS2812B_Test RP2040_WS2812B_Test.c )
pico_generate_pio_header(RP2040_WS2812B_Test ${CMAKE_CURRENT_LIST_DIR}/ws2812.pio OUTPUT_DIR ${CMAKE_CURRENT_LIST_DIR}/generated)
pico_set_program_name(RP2040_WS2812B_Test "RP2040_WS2812B_Test")
pico_set_program_version(RP2040_WS2812B_Test "0.1")
pico_enable_stdio_uart(RP2040_WS2812B_Test 0)
pico_enable_stdio_usb(RP2040_WS2812B_Test 0)
# Add the standard library to the build
target_link_libraries(RP2040_WS2812B_Test pico_stdlib)
# Add any user requested libraries
target_link_libraries(RP2040_WS2812B_Test
hardware_pio
)
pico_add_extra_outputs(RP2040_WS2812B_Test)

View File

@@ -0,0 +1,51 @@
#include <stdio.h>
#include <stdlib.h>
#include "pico/stdlib.h"
#include "hardware/pio.h"
#include "hardware/clocks.h"
#include "ws2812.pio.h"
void put_pixel(uint32_t pixel_grb)
{
pio_sm_put_blocking(pio0, 0, pixel_grb << 8u);
}
void put_rgb(uint8_t red, uint8_t green, uint8_t blue)
{
uint32_t mask = (green << 16) | (red << 8) | (blue << 0);
put_pixel(mask);
}
int main()
{
//set_sys_clock_48();
stdio_init_all();
PIO pio = pio0;
int sm = 0;
uint offset = pio_add_program(pio, &ws2812_program);
uint8_t cnt = 0;
puts("RP2040-Zero WS2812 Test");
ws2812_program_init(pio, sm, offset, 25, 800000, true);
while (1)
{
for (cnt = 0; cnt < 0xff; cnt++)
{
put_rgb(cnt, 0xff - cnt, 0);
sleep_ms(3);
}
for (cnt = 0; cnt < 0xff; cnt++)
{
put_rgb(0xff - cnt, 0, cnt);
sleep_ms(3);
}
for (cnt = 0; cnt < 0xff; cnt++)
{
put_rgb(0, cnt, 0xff - cnt);
sleep_ms(3);
}
}
}

View File

@@ -0,0 +1,34 @@
/*****************************************************************************
* | File : Readme_CN.txt
* | Author :
* | Function : Help with use
* | Info :
*----------------
* | This version: V1.0
* | Date : 2023-04-23
* | Info : 在这里提供一个中文版本的使用文档,以便你的快速使用
******************************************************************************/
这个文件是帮助您使用本例程。
由于我们的LCD越来越多不便于我们的维护因此把所有的LCD程序做成一个工程。
在这里简略的描述本工程的使用:
1.基本信息:
本例程用于测试或者演示RP2040-ETH上WS2812B;
2.管脚连接:
DIN -> 25
3.基本使用:
你需要执行:
如果目录已经存在,则可以直接进入。 如果没有目录,执行:
mkdir build
进入目录并添加SDK:
cd build
export PICO_SDK_PATH=../../pico-sdk
其中 ../../pico-sdk 是你的SDK的目录。
执行cmake自动生成Makefile文件:
cmake ..
执行make生成可执行文件然后在终端中输入
make
编译好的uf2文件复制到pico中即可

View File

@@ -0,0 +1,35 @@
/*****************************************************************************
* | File : Readme_EN.txt
* | Author :
* | Function : Help with use
* | Info :
*----------------
* | This version: V1.0
* | Date : 2021-02-04
* | Info : Here is an English version of the documentation for your quick use.
******************************************************************************/
This file is to help you use this routine.
Since our ink screens are getting more and more, it is not convenient for our maintenance, so all the ink screen programs are made into one project.
A brief description of the use of this project is here:
1. Basic information:
This routine is used to test or demonstrate WS2812B on RP2040-ETH.
2. Pin connection:
Pin connection You can look at dev_config.c/h in \lib\Config. Again, here:
DIN -> 25
3. Basic use:
You need to execute:
If the directory already exists, you can go directly. If there is no build directory, execute
mkdir build
Enter the build directory and type in the terminal:
cd build
export PICO_SDK_PATH=../../pico-sdk
Where ../../pico-sdk is your installed SDK directory
Execute cmake, automatically generate Makefile file, enter in the terminal:
cmake ..
Execute make to generate an executable file, and enter in the terminal:
make
Copy the compiled uf2 file to pico

View File

@@ -0,0 +1,61 @@
// -------------------------------------------------- //
// This file is autogenerated by pioasm; do not edit! //
// -------------------------------------------------- //
#pragma once
#if !PICO_NO_HARDWARE
#include "hardware/pio.h"
#endif
// ------ //
// ws2812 //
// ------ //
#define ws2812_wrap_target 0
#define ws2812_wrap 3
#define ws2812_T1 2
#define ws2812_T2 5
#define ws2812_T3 3
static const uint16_t ws2812_program_instructions[] = {
// .wrap_target
0x6221, // 0: out x, 1 side 0 [2]
0x1123, // 1: jmp !x, 3 side 1 [1]
0x1400, // 2: jmp 0 side 1 [4]
0xa442, // 3: nop side 0 [4]
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program ws2812_program = {
.instructions = ws2812_program_instructions,
.length = 4,
.origin = -1,
};
static inline pio_sm_config ws2812_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + ws2812_wrap_target, offset + ws2812_wrap);
sm_config_set_sideset(&c, 1, false, false);
return c;
}
#include "hardware/clocks.h"
static inline void ws2812_program_init(PIO pio, uint sm, uint offset, uint pin, float freq, bool rgbw) {
pio_gpio_init(pio, pin);
pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true);
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, rgbw ? 32 : 24);
sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX);
int cycles_per_bit = ws2812_T1 + ws2812_T2 + ws2812_T3;
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);
}
#endif

View File

@@ -0,0 +1,62 @@
# This is a copy of <PICO_SDK_PATH>/external/pico_sdk_import.cmake
# This can be dropped into an external project to help locate this SDK
# It should be include()ed prior to project()
if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH))
set(PICO_SDK_PATH $ENV{PICO_SDK_PATH})
message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')")
endif ()
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT))
set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT})
message("Using PICO_SDK_FETCH_FROM_GIT from environment ('${PICO_SDK_FETCH_FROM_GIT}')")
endif ()
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH))
set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH})
message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')")
endif ()
set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK")
set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable")
set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK")
if (NOT PICO_SDK_PATH)
if (PICO_SDK_FETCH_FROM_GIT)
include(FetchContent)
set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR})
if (PICO_SDK_FETCH_FROM_GIT_PATH)
get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")
endif ()
FetchContent_Declare(
pico_sdk
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
GIT_TAG master
)
if (NOT pico_sdk)
message("Downloading Raspberry Pi Pico SDK")
FetchContent_Populate(pico_sdk)
set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR})
endif ()
set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE})
else ()
message(FATAL_ERROR
"SDK location was not specified. Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT to on to fetch from git."
)
endif ()
endif ()
get_filename_component(PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")
if (NOT EXISTS ${PICO_SDK_PATH})
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found")
endif ()
set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake)
if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE})
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' does not appear to contain the Raspberry Pi Pico SDK")
endif ()
set(PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to the Raspberry Pi Pico SDK" FORCE)
include(${PICO_SDK_INIT_CMAKE_FILE})

View File

@@ -0,0 +1,48 @@
;
; Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
;
; SPDX-License-Identifier: BSD-3-Clause
;
.program ws2812
.side_set 1
.define public T1 2
.define public T2 5
.define public T3 3
.lang_opt python sideset_init = pico.PIO.OUT_HIGH
.lang_opt python out_init = pico.PIO.OUT_HIGH
.lang_opt python out_shiftdir = 1
.wrap_target
bitloop:
out x, 1 side 0 [T3 - 1] ; Side-set still takes place when instruction stalls
jmp !x do_zero side 1 [T1 - 1] ; Branch on the bit we shifted out. Positive pulse
do_one:
jmp bitloop side 1 [T2 - 1] ; Continue driving high, for a long pulse
do_zero:
nop side 0 [T2 - 1] ; Or drive low, for a short pulse
.wrap
% c-sdk {
#include "hardware/clocks.h"
static inline void ws2812_program_init(PIO pio, uint sm, uint offset, uint pin, float freq, bool rgbw) {
pio_gpio_init(pio, pin);
pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true);
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, rgbw ? 32 : 24);
sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX);
int cycles_per_bit = ws2812_T1 + ws2812_T2 + ws2812_T3;
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);
}
%}

View File

@@ -0,0 +1,53 @@
import time
from machine import Pin
import rp2
max_lum =100
r=0
g=0
b=0
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
def ws2812():
T1 = 2
T2 = 5
T3 = 3
wrap_target()
label("bitloop")
out(x, 1) .side(0) [T3 - 1]
jmp(not_x, "do_zero") .side(1) [T1 - 1]
jmp("bitloop") .side(1) [T2 - 1]
label("do_zero")
nop() .side(0) [T2 - 1]
wrap()
# Create the StateMachine with the ws2812 program, outputting on Pin(4).
sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(25))
# Start the StateMachine, it will wait for data on its FIFO.
sm.active(1)
# Color change
while True:
for i in range(0,max_lum):
r=i
b=max_lum-i
rgb =(g<<24) | (r<<16) | (b<<8)
sm.put(rgb)
time.sleep_ms(10)
time.sleep_ms(300)
for i in range(0,max_lum):
g=i
r=max_lum-i
rgb =(g<<24) | (r<<16) | (b<<8)
sm.put(rgb)
time.sleep_ms(10)
time.sleep_ms(300)
for i in range(0,max_lum):
b=i
g=max_lum-i
rgb =(g<<24) | (r<<16) | (b<<8)
sm.put(rgb)
time.sleep_ms(10)
time.sleep_ms(300)

View File

@@ -0,0 +1,36 @@
/*****************************************************************************
* | File : Readme_CN.txt
* | Author :
* | Function : Help with use
* | Info :
*----------------
* | This version: V1.0
* | Date : 2021-11-22
* | Info : 在这里提供一个中文版本的使用文档,以便你的快速使用
******************************************************************************/
这个文件是帮助您使用本例程。
在这里简略的描述本工程的使用:
1.基本信息:
本例程用于测试或者演示RP2040-Zero上WS2812B;
2.管脚连接:
管脚连接你可以在RP2040-Zero.py查看这里也再重述一次
DIN -> 16
3.基本使用:
1): 按住RP2040-Zero板上的Boot按键将RP2040-Zero通过Type-C USB线接到电脑的USB接口然后松开按键。
接入之后电脑会自动识别到一个可移动盘RPI-RP2
2): 将Python目录下的uf2文件夹中rp2-pico-20210902-v1.17.uf2 文件复制到识别的可移动盘RPI-RP2
3): 更新Thonny IDE
sudo apt upgrade thonny
4): 打开Thonny IDE 点击树莓logo -> Programming -> Thonny Python IDE
选择Tools -> Options... -> Interpreter
选择MicroPython(Raspberry Pi Pico 和ttyACM0端口
5): 在Thonny IDE中打开Python/RP2040-Zero.py文件
然后运行当前脚本(绿色小三角)即可

View File

@@ -0,0 +1,38 @@
/*****************************************************************************
* | File : Readme_EN.txt
* | Author :
* | Function : Help with use
* | Info :
*----------------
* | This version: V1.0
* | Date : 2021-11-22
* | Info : Here is an English version of the documentation for your quick use.
******************************************************************************/
This file is to help you use this routine.
Here is a brief description of the use of this project:
1. Basic information:
This routine is used to test or demonstrate WS2812B on RP2040-Zero.
2. Pin connection:
You can check the pin connection at RP2040-Zero.py, and repeat it here:
DIN -> 16
3. Basic use:
1): Press and hold the Bootsel button on the RP2040-Zero board, connect RP2040-Zero to the USB port of the
computer through the Type-C USB cable, and then release the button.
After connecting, the computer will automatically recognize a removable disk (RPI-RP2)
2): Copy the rp2-Pico-20210902-v1.17.uf2 file from the Uf2 folder in the Python directory to an identified
removable disk (rpi-rp2)
3): Update Thonny IDE
sudo apt upgrade thonny
4): Open Thonny IDE Click raspberry logo -> Programming -> Thonny Python IDE
select Tools -> Options... -> Interpreter
select MicroPython(Raspberry Pi Pico and ttyACM0 port
5): Open the Python/ rp2040-zero.py file in Thonny IDE
Then run the current script (little green triangle)

View File

@@ -0,0 +1 @@
2021-11-22新创建。

View File

@@ -0,0 +1 @@
2021-11-22: newly built.

View File

@@ -0,0 +1,52 @@
# RP2040 FreeRTOS Implementation Overview
## Project Structure
The RP2040-FreeRTOS project provides a modular framework for developing FreeRTOS applications on the RP2040 microcontroller.
### Key Components
- **FreeRTOS Kernel**: Included as git submodule
- **Pico SDK**: Raspberry Pi Pico SDK as submodule
- **Application Templates**: Multiple example applications
- **Build System**: CMake-based configuration
## Example Applications
### 1. Template App
- Basic LED flip-flop demonstration
- Inter-task queue communication
- Foundation for custom projects
### 2. Scheduling App
- Temperature sensor integration
- LED display output
- Task scheduling demonstration
### 3. IRQs App
- Interrupt-driven temperature sensing
- Real-time response capabilities
### 4. Timers App
- FreeRTOS software timer implementation
- Periodic task execution
## Build System
- **Build Tool**: CMake
- **Configurations**: Debug and Release
- **Deployment**: Automated deploy script
- **Languages**: C and C++ support
## Configuration
- Central configuration: `FreeRTOSConfig.h`
- Application-specific CMakeLists.txt
- Flexible and extensible design
## Getting Started
1. Clone repository with submodules
2. Configure CMake build
3. Build selected application
4. Deploy to RP2040 device
## Development Environment Support
- Visual Studio Code
- Xcode
- Command-line tools

View File

@@ -0,0 +1,43 @@
# RP2040-ETH Hardware Specifications
## Overview
The Waveshare RP2040-ETH is a compact module based on the RP2040 microcontroller with integrated Ethernet connectivity via the CH9120 controller.
## Core Specifications
- **Processor**: Dual-core Arm Cortex M0+
- **Clock Speed**: Up to 133 MHz
- **SRAM**: 264KB internal
- **Flash**: 4MB onboard
- **Ethernet Controller**: CH9120 with integrated TCP/IP stack
## Pin Configuration
- **GPIO**: 14 multi-function pins
- **SPI**: 1x SPI0
- **I2C**: 2x interfaces
- **UART**: 2x interfaces
- **PWM**: 13 channels
- **PIO**: 8 Programmable I/O state machines
## Network Features
- **Controller**: CH9120
- **Modes Supported**:
- TCP Server
- TCP Client
- UDP Server
- UDP Client
- **Configuration**: Via host software or serial commands
## Physical Design
- Castellated module design
- Type-C USB connector
- Ethernet interface
- Compatible with some Raspberry Pi Pico HATs
## Power Requirements
- USB powered via Type-C
- Operating voltage: 3.3V I/O
## Additional Features
- Built-in temperature sensor
- Drag-and-drop programming via USB
- MicroPython, C/C++, and Arduino IDE support

View File

@@ -0,0 +1,140 @@
# Precision Timing Concepts
## Time Synchronization Protocols
### NTP (Network Time Protocol)
- **Accuracy**: Typically 1-10ms over Internet, <1ms on LAN
- **Protocol**: UDP port 123
- **Versions**: NTPv3 (RFC 1305), NTPv4 (RFC 5905)
- **Stratum Levels**: 0 (reference) to 15
- **Key Features**:
- Client/server and peer modes
- Symmetric key authentication
- Broadcast/multicast support
### PTP (Precision Time Protocol)
- **Standard**: IEEE 1588-2008 (PTPv2)
- **Accuracy**: Sub-microsecond with hardware support
- **Transport**: Ethernet (Layer 2) or UDP (Layer 3)
- **Clock Types**:
- Ordinary Clock (OC)
- Boundary Clock (BC)
- Transparent Clock (TC)
- **Messages**:
- Sync, Follow_Up
- Delay_Req, Delay_Resp
- Announce, Management
### IRIG Time Codes
- **Types**: IRIG-A, B, D, E, G, H
- **IRIG-B**: Most common (100 pps, 1kHz carrier)
- **Encoding**: Amplitude modulated or DC level shift
- **Information**: Time of year, year, status bits
- **Accuracy**: Microsecond level
### GPS Time
- **Source**: Global Positioning System satellites
- **Accuracy**: ~40ns relative to UTC
- **Outputs**:
- NMEA sentences (serial data)
- PPS (Pulse Per Second)
- 10MHz reference (some receivers)
- **Considerations**:
- GPS-UTC offset (leap seconds)
- Antenna placement
- Signal acquisition time
### PPS (Pulse Per Second)
- **Signal**: Rising edge aligned to second boundary
- **Accuracy**: Typically <100ns jitter
- **Uses**:
- Clock discipline
- Frequency reference
- Time interval measurements
## Clock Synchronization Algorithms
### Phase-Locked Loop (PLL)
- Adjusts local clock frequency
- Minimizes phase error
- Smooth corrections
### Frequency-Locked Loop (FLL)
- Adjusts clock rate
- Good for initial synchronization
- Handles large offsets
### Kalman Filter
- Optimal state estimation
- Handles noisy measurements
- Predicts clock behavior
### Clock Discipline Algorithm
1. Measure time offset
2. Calculate frequency error
3. Apply corrections
4. Monitor stability
## Time Scales
### UTC (Coordinated Universal Time)
- International time standard
- Includes leap seconds
- Based on atomic clocks
### TAI (International Atomic Time)
- Continuous time scale
- No leap seconds
- UTC = TAI - leap_seconds
### GPS Time
- Started January 6, 1980
- No leap seconds
- GPS = TAI - 19 seconds
## Precision Timing Metrics
### Accuracy
- Closeness to true time
- Absolute time error
### Precision
- Repeatability of measurements
- Standard deviation
### Stability
- Allan deviation
- Time deviation (TDEV)
- Maximum time interval error (MTIE)
### Jitter
- Short-term variations
- Peak-to-peak or RMS
### Wander
- Long-term variations
- Low-frequency drift
## Implementation Considerations
### Hardware Timestamping
- PHY or MAC layer stamps
- Reduces software latency
- Critical for PTP
### Interrupt Latency
- PPS edge detection
- Deterministic response
- Priority management
### Clock Sources
- Crystal oscillators (XO)
- Temperature compensated (TCXO)
- Oven controlled (OCXO)
- Chip scale atomic clocks (CSAC)
### Network Considerations
- Asymmetric delays
- Packet delay variation
- Queue management
- Traffic prioritization

1
freertos-build Submodule

Submodule freertos-build added at f0cec5b45d

242
ideas.md Normal file
View File

@@ -0,0 +1,242 @@
# Innovative Ideas for RP2040-ETH Precision Timing Tool
## Advanced Time Synchronization
### 1. Adaptive Multi-Source Fusion Algorithm
- **Concept**: Dynamic weighting of time sources based on real-time quality metrics
- **Implementation**:
- Kalman filter with adaptive covariance matrices
- Machine learning model to predict source reliability
- Automatic outlier detection and rejection
- Smooth transitions between primary sources
- **Benefits**: Superior accuracy through intelligent source combination
### 2. Predictive Network Delay Compensation
- **Concept**: ML-based prediction of network latency patterns
- **Implementation**:
- Train lightweight neural network on-device
- Pattern recognition for periodic network congestion
- Preemptive adjustment of polling intervals
- Store delay profiles for different network conditions
- **Benefits**: Better NTP/PTP accuracy in variable network conditions
### 3. Hardware-Accelerated Timestamping
- **Concept**: Use RP2040's PIO state machines for precise packet timestamping
- **Implementation**:
- PIO program to capture Ethernet PHY signals
- DMA transfer of timestamps to minimize latency
- Sub-microsecond resolution without CPU intervention
- Dedicated PIO for PPS edge detection
- **Benefits**: Hardware-level precision without expensive PHY chips
## Novel Protocol Features
### 4. Hybrid PTP/NTP Mode
- **Concept**: Seamlessly switch between PTP and NTP based on network capabilities
- **Implementation**:
- Auto-detect PTP-capable devices
- Fallback to NTP when PTP unavailable
- Weighted averaging when both available
- Transparent to client applications
- **Benefits**: Maximum compatibility and accuracy
### 5. Distributed Time Consensus
- **Concept**: Blockchain-inspired time agreement among multiple devices
- **Implementation**:
- Peer-to-peer time exchange protocol
- Byzantine fault tolerance for time sources
- Cryptographic signatures for time attestation
- Local consensus building without central authority
- **Benefits**: Resilient against single point of failure
### 6. Time Capsule Protocol
- **Concept**: Cryptographically signed time stamps for audit trails
- **Implementation**:
- Generate tamper-proof time certificates
- Chain of custody for time-critical events
- Integration with blockchain networks
- Legal compliance features
- **Benefits**: Forensic time verification
## Hardware Enhancements
### 7. Temperature-Compensated Timing
- **Concept**: Use RP2040's internal temperature sensor for drift compensation
- **Implementation**:
- Characterize crystal frequency vs temperature
- Real-time compensation algorithm
- Self-calibration during GPS lock periods
- Store compensation curves in flash
- **Benefits**: Improved holdover performance
### 8. Dual-Core Time Architecture
- **Concept**: Dedicate one RP2040 core exclusively to timekeeping
- **Implementation**:
- Core 0: Time maintenance, no interrupts
- Core 1: Network, I/O, and application tasks
- Shared memory time structure with atomic updates
- Deterministic time access latency
- **Benefits**: Jitter-free timekeeping
### 9. Power-Aware Timing
- **Concept**: Maintain time accuracy during power transitions
- **Implementation**:
- Supercapacitor backup for critical timing
- Fast time recovery from RTC
- Power profile optimization
- Graceful degradation modes
- **Benefits**: Continuous operation through power events
## User Experience Innovations
### 10. AR Time Visualization
- **Concept**: Augmented reality view of time synchronization status
- **Implementation**:
- QR code for mobile app connection
- 3D visualization of time sources
- Real-time sync quality display
- Network topology overlay
- **Benefits**: Intuitive understanding of complex timing
### 11. Voice-Controlled Configuration
- **Concept**: Natural language time system configuration
- **Implementation**:
- Lightweight voice recognition
- Command grammar for timing operations
- Audio feedback for blind operation
- Multi-language support
- **Benefits**: Hands-free operation in data centers
### 12. Predictive Maintenance
- **Concept**: AI-driven prediction of timing failures
- **Implementation**:
- Monitor drift trends
- Detect anomalous behavior patterns
- Alert before synchronization loss
- Suggest preventive actions
- **Benefits**: Increased system reliability
## Integration Features
### 13. Time-as-a-Service API
- **Concept**: RESTful API for time distribution
- **Implementation**:
- JSON-RPC time queries
- WebSocket for real-time updates
- OAuth2 authentication
- Rate limiting and QoS
- **Benefits**: Modern integration with cloud services
### 14. Quantum-Ready Time Distribution
- **Concept**: Prepare for quantum-secure time protocols
- **Implementation**:
- Post-quantum cryptography for signatures
- Quantum key distribution readiness
- Lattice-based authentication
- Future-proof protocol design
- **Benefits**: Long-term security
### 15. Edge Computing Time Sync
- **Concept**: Optimized for edge computing environments
- **Implementation**:
- Mesh network time distribution
- Low-power operation modes
- Containerized time service
- Kubernetes operator for deployment
- **Benefits**: Cloud-native compatibility
## Research Directions
### 16. Relativistic Time Corrections
- **Concept**: Account for relativistic effects in mobile applications
- **Implementation**:
- Velocity and altitude corrections
- GPS relativistic compensations
- Special relativity calculations
- Gravitational time dilation
- **Benefits**: Ultimate precision for aerospace
### 17. Biological Rhythm Integration
- **Concept**: Align technical time with human circadian rhythms
- **Implementation**:
- Sunrise/sunset calculations
- Timezone-aware scheduling
- Health-optimized time displays
- Chronobiology interfaces
- **Benefits**: Human-centric time systems
### 18. Time Compression Protocols
- **Concept**: Efficient time distribution for bandwidth-limited networks
- **Implementation**:
- Delta encoding for time updates
- Compressed time packet formats
- Predictive time extrapolation
- Adaptive update rates
- **Benefits**: Minimal network overhead
## Security Innovations
### 19. Time-Based Security Tokens
- **Concept**: Use precision time for enhanced authentication
- **Implementation**:
- Sub-second OTP generation
- Time-locked encryption keys
- Temporal access controls
- Anti-replay mechanisms
- **Benefits**: Enhanced security protocols
### 20. Timing Attack Detection
- **Concept**: Detect and prevent timing-based security attacks
- **Implementation**:
- Monitor for suspicious time queries
- Rate anomaly detection
- Timing pattern analysis
- Automated response systems
- **Benefits**: Improved security posture
## Future Expansions
### 21. Satellite Time Reception
- **Concept**: Support for multiple GNSS constellations
- **Implementation**:
- GPS, GLONASS, Galileo, BeiDou
- Multi-frequency reception
- Ionospheric correction models
- Signal integrity monitoring
- **Benefits**: Global coverage and redundancy
### 22. Environmental Time Stamping
- **Concept**: Correlate time with environmental events
- **Implementation**:
- Seismic event detection
- Lightning strike timing
- Temperature anomaly correlation
- Atmospheric pressure changes
- **Benefits**: Scientific research applications
### 23. Time Travel Debugging
- **Concept**: Record and replay time synchronization events
- **Implementation**:
- Circular buffer of time events
- State machine recording
- Time-travel debugging interface
- Deterministic replay
- **Benefits**: Simplified troubleshooting
### 24. Swarm Time Coordination
- **Concept**: Coordinate time across swarms of devices
- **Implementation**:
- Gossip protocol for time distribution
- Leader election for time master
- Byzantine agreement protocols
- Self-organizing time hierarchy
- **Benefits**: Scalable to thousands of nodes
### 25. Holographic Time Display
- **Concept**: 3D holographic visualization of time data
- **Implementation**:
- Volumetric display integration
- Time flow visualization
- Multi-dimensional time representation
- Gesture-based interaction
- **Benefits**: Intuitive time comprehension