在编写直接访问内存的C#程序时可能会遇到 CS0227的错误提示。
解决方法时在项目上点击右键,然后选择 Properties:

然后在 Build 中选择 “Allow unsafe code”

在编写直接访问内存的C#程序时可能会遇到 CS0227的错误提示。
解决方法时在项目上点击右键,然后选择 Properties:

然后在 Build 中选择 “Allow unsafe code”

SST25VF080B 是一款 SPI NOR 芯片,容量为1MB(8MBITs)【参考1】。这次测试的使用 Arduino Pro Micro 【参考2】进行读写(它使用32U4 作为主控,工作在8Mhz,3.3V 下面)。特别注意,这个SPI NOR 工作电压为3.3V。
具体连接如下:

编写的测试代码如下:
#include <SST25VF.h>
#include <SPI.h>
#define MemCs 6 //CS#
#define MemWp 4 //WP#
#define MemHold 7 //HOLD#
#define EraseSwitch 5 //擦除开关
#define WriteSwitch 8 //写入开关
SST25VF flash;
uint8_t buffer[]="www.lab-z.com 2022";
void setup() {
Serial.begin(115200);
pinMode(EraseSwitch, INPUT_PULLUP);
pinMode(WriteSwitch, INPUT_PULLUP);
flash.begin(MemCs, MemWp, MemHold);
}
void loop() {
// 函数内部直接串口输出
flash.readID();
if (digitalRead(EraseSwitch) == LOW) {
// 擦除 Sector 0
Serial.println("erasing...");
flash.sectorErase(0);
}
if (digitalRead(WriteSwitch) == LOW) {
// 写入字符串
Serial.println("writing...");
flash.writeArray(0,buffer,sizeof(buffer));
}
//读取
flash.readArray(0,buffer,sizeof(buffer));
Serial.print("Read: ");
for (int i=0;i<sizeof(buffer);i++) {
Serial.print((char)buffer[i]);
}
Serial.println("");
delay(5000);
}
代码会读取当前芯片的 ID显示出来,然后读取 Address 0开始的数据,以 ASCII字符显示出来。同时预留了D5和D8。当D5接地时会进行Sector 0 的擦除动作;当D8接地时会对 Address 0 写入一个字符串。
参考:
1.芯片收据手册 https://ww1.microchip.com/downloads/en/DeviceDoc/20005045C.pdf
2.Arduino Pro Micro 引脚定义 https://content.arduino.cc/assets/Pinout-Micro_latest.pdf
最近我在使用 CH567 制作双 USB 设备,在这个过程中,我发现每次烧写程序都比较麻烦。例如,首先要拔掉设备,然后按下 DOWNLOAD 按键,接下来再插入USB端口中,最后才能烧写(值得庆幸的是我预留了RESET 按钮,否则还要重新插拔一次)。经过研究和实验,我设计了一个能够自动完成烧写的设备。基本原理是:使用芯片模拟USB设备下电过程(断开 D+、D-,再下电);然后通过MOSFET模拟按下DOWNLOAD键(Pin 下拉到GND);再使用芯片模拟USB设备上电过程(先上电,再连接 D+、D-);接下来用户就可以在PC上进行烧写;最后再通过MOSFET模拟RESET 键。烧写好的程序就可以正常运行了。
下面介绍这次用到的两颗主要芯片。首先是用于切换USB 信号(D+、D-)的CH442。它是 DPDT 模拟开关芯片,包含 2 路单刀双掷二选一开关。CH442 是CH44X 系列芯片的一款。这一系列是模拟开关芯片,具有高带宽,支持视频信号,支持低速、全速和高速 USB 信号的特点。

另外一个是 SY6280AAC芯片,用于控制 USB母头(连接CH567)的 USB 供电。

这次使用的主控为 DFRbot 出品的 FireBeetle,他的核心是 ESP32。实际上主要功能是通过GPIO来实现的,要求不高,有需要的朋友可以修改为任意的单片机。
最终电路图设计如下:

主控部分需要注意的是预留了一个跳线位置,必要时将此短接起来FireBeetle可以直接从USB1取电(例如,FireBeetle支持蓝牙,可以修改代码为蓝牙控制触发 CH567进去下载模式)。

下面是2个GPIO 通过MOSFET控制的RST和 PowerDown 引脚。没有触发时,RST和PWDPIN会出现3.3V,当有需要时可以拉低到GND。

接下来是USB接口和用于切换的CH442E 芯片,USB1 是USB公头,接入电脑中;USB3 是USB母头,用于连接CH567。CH442E控制USB1 的 USB信号(IN_D-、IN+D+)在USB3(DB、DC)和断开(S2B、S2C)之间切换。

最后是SY6280AA芯片,UPW_CTRL 控制IN_VCC 是否输出到 OUT_VCC 上。

这个设计是给FireBeetle 的Shield,最终的PCB 如下:

焊接之后照片如下,右侧是 DFRobot的FireBeetle,二者可以通过堆叠的方式进行连接。

完整代码如下:
#define PWD_CTRL 22
#define EN_CTRL 27
#define RST_CTRL 21
#define UPW_CTRL 14
#define IN_CTRL 26
void setup() {
Serial.begin(115200);
pinMode(PWD_CTRL, OUTPUT);
pinMode(EN_CTRL, OUTPUT);
pinMode(RST_CTRL, OUTPUT);
pinMode(UPW_CTRL, OUTPUT);
pinMode(IN_CTRL, OUTPUT);
digitalWrite(PWD_CTRL, LOW);
digitalWrite(EN_CTRL, LOW);
digitalWrite(RST_CTRL, LOW);
digitalWrite(UPW_CTRL, LOW);
digitalWrite(IN_CTRL, LOW);
}
void unplug() {
// USB1和USB3断开
digitalWrite(IN_CTRL, LOW);
Serial.print(IN_CTRL);
Serial.println("IN_CTRL LOW");
// CH567 断开5V
digitalWrite(UPW_CTRL, LOW);
Serial.print(UPW_CTRL);
Serial.println("UPW_CTRL LOW");
delay(20);
}
void plug() {
// CH567 上电
digitalWrite(UPW_CTRL, HIGH);
Serial.print(UPW_CTRL);
Serial.println("UPW_CTRL HIGH");
delay(20);
// USB1和USB3连通
digitalWrite(IN_CTRL, LOW);
Serial.print(IN_CTRL);
Serial.println("IN_CTRL HIGH");
}
void loop() {
if (Serial.available()) {
byte c = Serial.read();
// 按下 PowerDown
if (c == 'd') {
Serial.println("Press Power Down");
// 按下 PowerDown 键
digitalWrite(PWD_CTRL, HIGH);
Serial.println("PWD_CTRL HIGH");
}
// 抬起 PowerDown
if (c == 'u') {
Serial.println("Release Power Down");
//抬起 PowerDown 键
digitalWrite(PWD_CTRL, LOW);
Serial.println("PWD_CTRL HIGH");
}
// 按下抬起一次 RESET键
if (c == 'r') {
Serial.println("Press and Release RESET");
//按下 RESET 键
digitalWrite(RST_CTRL, HIGH);
Serial.println("RST_CTRL HIGH");
delay(20);
//抬起 PowerDown 键
digitalWrite(RST_CTRL, LOW);
Serial.println("RST_CTRL LOW");
}
// 模拟断开CH567
if (c == 'u') {
Serial.println("unplug");
unplug();
}
// 模拟插入CH567
if (c == 'p') {
Serial.println("plug");
plug();
}
}
}
使用方法是通过串口接收指令,代码定义了如下五个动作:
1.”d” 按下 PowerDown键
2.”f” 抬起 PowerDown键
3.”r” 按下然后抬起 RESET键
4.”u” 模拟断开 USB 母头设备
5.”p” 模拟插入 USB 母头设备
最近想找点题目给娃做,然后发现Baidu搜索到的大部分都是收费的,于是自己编写代码进行生成。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.IO;
namespace _100Calc
{
class Program
{
//将List转换为TXT文件
static public void WriteListToTextFile(List<string> list, string txtFile)
{
//创建一个文件流,用以写入或者创建一个StreamWriter
FileStream fs = new FileStream(txtFile, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Flush();
// 使用StreamWriter来往文件中写入内容
sw.BaseStream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < list.Count; i++) sw.WriteLine(list[i]);
//关闭此文件t
sw.Flush();
sw.Close();
fs.Close();
}
//读取文本文件转换为List
static public List<string> ReadTextFileToList(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
List<string> list = new List<string>();
StreamReader sr = new StreamReader(fs);
//使用StreamReader类来读取文件
sr.BaseStream.Seek(0, SeekOrigin.Begin);
// 从数据流中读取每一行,直到文件的最后一行
string tmp = sr.ReadLine();
while (tmp != null)
{
list.Add(tmp);
tmp = sr.ReadLine();
}
//关闭此StreamReader对象
sr.Close();
fs.Close();
return list;
}
static void Main(string[] args)
{
List<string> Add100 = new List<string>();
for (int i = 10; i < 100; i++)
for (int j = 10; j < 100; j++) {
//Console.WriteLine("{0}+{1}=", i, j);
Add100.Add(i.ToString() + "+" + j.ToString() + "=");
}
//WriteListToTextFile(Add100,"100Add.txt");
List<string> Sub100 = new List<string>();
for (int i = 99; i >10; i--)
for (int j = i-1; j >10; j--)
{
//Console.WriteLine("{0}-{1}=", i, j);
Sub100.Add(i.ToString() + "-" + j.ToString() + "=");
}
//A - B + C 形式的,特别注意 A-B>0
List<string> ThrCalc1 = new List<string>();
for (int i = 99; i > 10; i--)
for (int j = i - 1; j > 10; j--)
for (int k = 10; k<100; k++)
{
//Console.WriteLine("{0}-{1}+{2}=", i, j,k);
ThrCalc1.Add(i.ToString() + "-" + j.ToString() + "+" + k.ToString() + "=");
}
//A - B - C 形式的,特别注意 A-B-C>0
List<string> ThrCalc2 = new List<string>();
for (int i = 99; i > 10; i--)
for (int j = i - 1; j > 10; j--)
for (int k = 10; k < 100; k++)
{
if (i-j-k>0)
{
//Console.WriteLine("{0}-{1}+{2}=", i, j,k);
ThrCalc2.Add(i.ToString() + "-" + j.ToString() + "-" + k.ToString() + "=");
}
}
Random rnd = new Random();
List<string> timu = new List<string>();
// 生成 180 套题目
for (int i = 0; i < 160; i++) {
for (int q1 = 0; q1 < 21; q1++) {
int v = rnd.Next(Add100.Count);
timu.Add(Add100[v]);
Add100.RemoveAt(v);
}
for (int q2 = 0; q2 < 22; q2++)
{
int v = rnd.Next(Sub100.Count);
timu.Add(Sub100[v]);
Sub100.RemoveAt(v);
}
for (int q3 = 0; q3 < 7; q3++)
{
int v = rnd.Next(ThrCalc1.Count);
timu.Add(ThrCalc1[v]);
ThrCalc1.RemoveAt(v);
}
for (int q4 = 0; q4 < 7; q4++)
{
int v = rnd.Next(ThrCalc2.Count);
timu.Add(ThrCalc2[v]);
ThrCalc2.RemoveAt(v);
}
// 打乱排列顺序
string s;
for (int j = 0; j < timu.Count; j++) {
int v = rnd.Next(timu.Count);
s = timu[v];
timu[v] = timu[j];
timu[j] = s;
}
// 输出
for (int j = 0; j < timu.Count/3; j++)
{
Console.WriteLine("{0,-10}\t\t\t{1,-10}\t\t\t{2,-10}", timu[j*3], timu[j*3+1], timu[j*3+2]);
}
//Console.WriteLine("Data: Score: ");
timu.Clear();
}
Console.WriteLine("{0} {1} {2} {3}", Add100.Count,Sub100.Count, ThrCalc1.Count, ThrCalc2.Count);
Console.ReadLine();
}
}
}
每一页21道2位数加法,22道两位数减法(没有负数),还有14到3个两位数加减运算。一共160页。直接拷贝到 Word文章后,生成一份 PDF如下,有需要的朋友可以下载打印。
增加一个3个数字的加减乘运算
一年级二十以内加减题目
https://www.lab-z.com/wp-content/uploads/2022/11/100Calc.pdf
增加一个3个数字的加减乘运算
https://www.lab-z.com/wp-content/uploads/2023/01/3Calc.pdf
一年级二十以内加减题目
随着科技的进步,现在的大多数电脑都在使用固态硬盘,但是因为价格的问题,你的办公电脑硬盘永远比实际需要小一个档次。经过一段时间硬盘空间就会变得捉襟见肘。为此,需要进行硬盘的清理,在这个过程中我不建议使用全自动工具清理,因为全自动工具通常删除的只是缓存内容,删除之后很可能影响性能,并且经过一段时间之后仍然会自动生成,另外,这种工具“深度清理”之后很可能导致系统奇怪的问题。我建议用户进行手工的清理,该删除的要删除,该备份的要即时备份。这里推荐名为 “SpaceSniffer” 的工具,能够帮助用户快速识别当前系统中占用硬盘最高的内容。
这个工具的官方网站如下:
http://www.uderzo.it/main_products/space_sniffer/index.html
软件是绿色并且免费的,无需安装:

解压之后直接运行 SpaceSniffer 即可。
首先会要求你选择扫描的路径,一般情况下我们会选择某个盘符,这里我们选择扫描 C盘。

扫描过程中可能会出现如下的提示信息,出现的原因是软件权限不够一些文件无法访问。我们可以忽略这个提示。如果不想看到这个的话,可以在运行时选择以管理员权限运行这个软件。

最终扫描结果如下:

整体是按照占用控件进行排序的,比如左上角是 Windows 目录占用了 25.3GB 的控件,其中WinSxS 占用了 11.3GB 的大小。鼠标移动到方块上之后可以直接打开目录进行详细的查看。
有兴趣的朋友不妨试试这款软件,帮助你节省更多空间出来。有兴趣的朋友请到上面给出的官网下载
Arduino 可以使用键盘作为输入设备,最常见的是下面2种接口的键盘:

这次介绍的是ESP32 Arduino 直接读取蓝牙键盘的输入。特别需要注意的是蓝牙键盘有两种,Classical 和 BLE。我测试过罗技的 K480 是Classical蓝牙键盘:

还有苹果的A2449键盘,同样也是Classical 键盘。

IDF 提供了一个读取 Classical 键盘输入的示例,但是经过我的测试该代码无法正常工作。
这次介绍的代码只适用于 BLE 键盘,我入手的是雷柏 x220t 键鼠套装。这个键盘支持三种模式:2.4G、Classical 蓝牙和 BLE 蓝牙。

代码来自 https://github.com/esp32beans/BLE_HID_Client
/** NimBLE_Server Demo:
*
* Demonstrates many of the available features of the NimBLE client library.
*
* Created: on March 24 2020
* Author: H2zero
*
*/
/*
* This program is based on https://github.com/h2zero/NimBLE-Arduino/tree/master/examples/NimBLE_Client.
* My changes are covered by the MIT license.
*/
/*
* MIT License
*
* Copyright (c) 2022 esp32beans@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation 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
* furnished 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 FOR 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.
*/
// Install NimBLE-Arduino by h2zero using the IDE library manager.
#include <NimBLEDevice.h>
const char HID_SERVICE[] = "1812";
const char HID_INFORMATION[] = "2A4A";
const char HID_REPORT_MAP[] = "2A4B";
const char HID_CONTROL_POINT[] = "2A4C";
const char HID_REPORT_DATA[] = "2A4D";
void scanEndedCB(NimBLEScanResults results);
static NimBLEAdvertisedDevice* advDevice;
static bool doConnect = false;
static uint32_t scanTime = 0; /** 0 = scan forever */
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) {
Serial.println("Connected");
/** After connection we should change the parameters if we don't need fast response times.
* These settings are 150ms interval, 0 latency, 450ms timout.
* Timeout should be a multiple of the interval, minimum is 100ms.
* I find a multiple of 3-5 * the interval works best for quick response/reconnect.
* Min interval: 120 * 1.25ms = 150, Max interval: 120 * 1.25ms = 150, 0 latency, 60 * 10ms = 600ms timeout
*/
pClient->updateConnParams(120,120,0,60);
};
void onDisconnect(NimBLEClient* pClient) {
Serial.print(pClient->getPeerAddress().toString().c_str());
Serial.println(" Disconnected - Starting scan");
NimBLEDevice::getScan()->start(scanTime, scanEndedCB);
};
/** Called when the peripheral requests a change to the connection parameters.
* Return true to accept and apply them or false to reject and keep
* the currently used parameters. Default will return true.
*/
bool onConnParamsUpdateRequest(NimBLEClient* pClient, const ble_gap_upd_params* params) {
// Failing to accepts parameters may result in the remote device
// disconnecting.
return true;
};
/********************* Security handled here **********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyRequest(){
Serial.println("Client Passkey Request");
/** return the passkey to send to the server */
return 123456;
};
bool onConfirmPIN(uint32_t pass_key){
Serial.print("The passkey YES/NO number: ");
Serial.println(pass_key);
/** Return false if passkeys don't match. */
return true;
};
/** Pairing process complete, we can check the results in ble_gap_conn_desc */
void onAuthenticationComplete(ble_gap_conn_desc* desc){
if(!desc->sec_state.encrypted) {
Serial.println("Encrypt connection failed - disconnecting");
/** Find the client with the connection handle provided in desc */
NimBLEDevice::getClientByID(desc->conn_handle)->disconnect();
return;
}
};
};
/** Define a class to handle the callbacks when advertisments are received */
class AdvertisedDeviceCallbacks: public NimBLEAdvertisedDeviceCallbacks {
void onResult(NimBLEAdvertisedDevice* advertisedDevice) {
if ((advertisedDevice->getAdvType() == BLE_HCI_ADV_TYPE_ADV_DIRECT_IND_HD)
|| (advertisedDevice->getAdvType() == BLE_HCI_ADV_TYPE_ADV_DIRECT_IND_LD)
|| (advertisedDevice->haveServiceUUID() && advertisedDevice->isAdvertisingService(NimBLEUUID(HID_SERVICE))))
{
Serial.print("Advertised HID Device found: ");
Serial.println(advertisedDevice->toString().c_str());
/** stop scan before connecting */
NimBLEDevice::getScan()->stop();
/** Save the device reference in a global for the client to use*/
advDevice = advertisedDevice;
/** Ready to connect now */
doConnect = true;
}
};
};
/** Notification / Indication receiving handler callback */
// Notification from 4c:75:25:xx:yy:zz: Service = 0x1812, Characteristic = 0x2a4d, Value = 1,0,0,0,0,
void notifyCB(NimBLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify){
std::string str = (isNotify == true) ? "Notification" : "Indication";
str += " from ";
/** NimBLEAddress and NimBLEUUID have std::string operators */
str += std::string(pRemoteCharacteristic->getRemoteService()->getClient()->getPeerAddress());
str += ": Service = " + std::string(pRemoteCharacteristic->getRemoteService()->getUUID());
str += ", Characteristic = " + std::string(pRemoteCharacteristic->getUUID());
str += ", Value = ";
Serial.print(str.c_str());
for (size_t i = 0; i < length; i++) {
Serial.print(pData[i], HEX);
Serial.print(',');
}
Serial.print(' ');
if (length == 6) {
// BLE Trackball Mouse from Amazon returns 6 bytes per HID report
Serial.printf("buttons: %02x, x: %d, y: %d, wheel: %d",
pData[0], *(int16_t *)&pData[1], *(int16_t *)&pData[3], (int8_t)pData[5]);
}
else if (length == 5) {
// https://github.com/wakwak-koba/ESP32-NimBLE-Mouse
// returns 5 bytes per HID report
Serial.printf("buttons: %02x, x: %d, y: %d, wheel: %d hwheel: %d",
pData[0], (int8_t)pData[1], (int8_t)pData[2], (int8_t)pData[3], (int8_t)pData[4]);
}
Serial.println();
}
/** Callback to process the results of the last scan or restart it */
void scanEndedCB(NimBLEScanResults results){
Serial.println("Scan Ended");
}
/** Create a single global instance of the callback class to be used by all clients */
static ClientCallbacks clientCB;
/** Handles the provisioning of clients and connects / interfaces with the server */
bool connectToServer()
{
NimBLEClient* pClient = nullptr;
/** Check if we have a client we should reuse first **/
if(NimBLEDevice::getClientListSize()) {
/** Special case when we already know this device, we send false as the
* second argument in connect() to prevent refreshing the service database.
* This saves considerable time and power.
*/
pClient = NimBLEDevice::getClientByPeerAddress(advDevice->getAddress());
if(pClient){
if(!pClient->connect(advDevice, false)) {
Serial.println("Reconnect failed");
return false;
}
Serial.println("Reconnected client");
}
/** We don't already have a client that knows this device,
* we will check for a client that is disconnected that we can use.
*/
else {
pClient = NimBLEDevice::getDisconnectedClient();
}
}
/** No client to reuse? Create a new one. */
if(!pClient) {
if(NimBLEDevice::getClientListSize() >= NIMBLE_MAX_CONNECTIONS) {
Serial.println("Max clients reached - no more connections available");
return false;
}
pClient = NimBLEDevice::createClient();
Serial.println("New client created");
pClient->setClientCallbacks(&clientCB, false);
/** Set initial connection parameters: These settings are 15ms interval, 0 latency, 120ms timout.
* These settings are safe for 3 clients to connect reliably, can go faster if you have less
* connections. Timeout should be a multiple of the interval, minimum is 100ms.
* Min interval: 12 * 1.25ms = 15, Max interval: 12 * 1.25ms = 15, 0 latency, 51 * 10ms = 510ms timeout
*/
pClient->setConnectionParams(12,12,0,51);
/** Set how long we are willing to wait for the connection to complete (seconds), default is 30. */
pClient->setConnectTimeout(5);
if (!pClient->connect(advDevice)) {
/** Created a client but failed to connect, don't need to keep it as it has no data */
NimBLEDevice::deleteClient(pClient);
Serial.println("Failed to connect, deleted client");
return false;
}
}
if(!pClient->isConnected()) {
if (!pClient->connect(advDevice)) {
Serial.println("Failed to connect");
return false;
}
}
Serial.print("Connected to: ");
Serial.println(pClient->getPeerAddress().toString().c_str());
Serial.print("RSSI: ");
Serial.println(pClient->getRssi());
/** Now we can read/write/subscribe the charateristics of the services we are interested in */
NimBLERemoteService* pSvc = nullptr;
NimBLERemoteCharacteristic* pChr = nullptr;
NimBLERemoteDescriptor* pDsc = nullptr;
pSvc = pClient->getService(HID_SERVICE);
if(pSvc) { /** make sure it's not null */
// This returns the HID report descriptor like this
// HID_REPORT_MAP 0x2a4b Value: 5,1,9,2,A1,1,9,1,A1,0,5,9,19,1,29,5,15,0,25,1,75,1,
// Copy and paste the value digits to http://eleccelerator.com/usbdescreqparser/
// to see the decoded report descriptor.
pChr = pSvc->getCharacteristic(HID_REPORT_MAP);
if(pChr) { /** make sure it's not null */
Serial.print("HID_REPORT_MAP ");
if(pChr->canRead()) {
std::string value = pChr->readValue();
Serial.print(pChr->getUUID().toString().c_str());
Serial.print(" Value: ");
uint8_t *p = (uint8_t *)value.data();
for (size_t i = 0; i < value.length(); i++) {
Serial.print(p[i], HEX);
Serial.print(',');
}
Serial.println();
}
}
else {
Serial.println("HID REPORT MAP char not found.");
}
// Subscribe to characteristics HID_REPORT_DATA.
// One real device reports 2 with the same UUID but
// different handles. Using getCharacteristic() results
// in subscribing to only one.
std::vector<NimBLERemoteCharacteristic*>*charvector;
charvector = pSvc->getCharacteristics(true);
for (auto &it: *charvector) {
if (it->getUUID() == NimBLEUUID(HID_REPORT_DATA)) {
Serial.println(it->toString().c_str());
if (it->canNotify()) {
if(!it->subscribe(true, notifyCB)) {
/** Disconnect if subscribe failed */
Serial.println("subscribe notification failed");
pClient->disconnect();
return false;
}
}
}
}
}
Serial.println("Done with this device!");
return true;
}
void setup ()
{
Serial.begin(115200);
Serial.println("Starting NimBLE HID Client");
/** Initialize NimBLE, no device name spcified as we are not advertising */
NimBLEDevice::init("");
/** Set the IO capabilities of the device, each option will trigger a different pairing method.
* BLE_HS_IO_KEYBOARD_ONLY - Passkey pairing
* BLE_HS_IO_DISPLAY_YESNO - Numeric comparison pairing
* BLE_HS_IO_NO_INPUT_OUTPUT - DEFAULT setting - just works pairing
*/
//NimBLEDevice::setSecurityIOCap(BLE_HS_IO_KEYBOARD_ONLY); // use passkey
//NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_YESNO); //use numeric comparison
/** 2 different ways to set security - both calls achieve the same result.
* no bonding, no man in the middle protection, secure connections.
*
* These are the default values, only shown here for demonstration.
*/
NimBLEDevice::setSecurityAuth(true, false, true);
//NimBLEDevice::setSecurityAuth(/*BLE_SM_PAIR_AUTHREQ_BOND | BLE_SM_PAIR_AUTHREQ_MITM |*/ BLE_SM_PAIR_AUTHREQ_SC);
/** Optional: set the transmit power, default is 3db */
NimBLEDevice::setPower(ESP_PWR_LVL_P9); /** +9db */
/** Optional: set any devices you don't want to get advertisments from */
// NimBLEDevice::addIgnored(NimBLEAddress ("aa:bb:cc:dd:ee:ff"));
/** create new scan */
NimBLEScan* pScan = NimBLEDevice::getScan();
/** create a callback that gets called when advertisers are found */
pScan->setAdvertisedDeviceCallbacks(new AdvertisedDeviceCallbacks());
/** Set scan interval (how often) and window (how long) in milliseconds */
pScan->setInterval(45);
pScan->setWindow(15);
/** Active scan will gather scan response data from advertisers
* but will use more energy from both devices
*/
pScan->setActiveScan(true);
/** Start scanning for advertisers for the scan time specified (in seconds) 0 = forever
* Optional callback for when scanning stops.
*/
pScan->start(scanTime, scanEndedCB);
}
void loop ()
{
/** Loop here until we find a device we want to connect to */
if (!doConnect) return;
doConnect = false;
/** Found a device we want to connect to, do it now */
if(connectToServer()) {
Serial.println("Success! we should now be getting notifications!");
} else {
Serial.println("Failed to connect, starting scan");
NimBLEDevice::getScan()->start(scanTime,scanEndedCB);
}
}
烧录完成后,切换键盘到蓝牙模式,然后ESP32 S3 会和键盘配对,之后就可以读取到按键信息了:
Starting NimBLE HID Client
Advertised HID Device found: Name: RAPOO BT4.0 KB, Address: b4:ee:25:f3:86:99, appearance: 961, serviceUUID: 0x1812
Scan Ended
New client created
Connected
Connected to: b4:ee:25:f3:86:99
RSSI: -64
HID_REPORT_MAP 0x2a4b Value:
Done with this device!
Success! we should now be getting notifications!
b4:ee:25:f3:86:99 Disconnected - Starting scan
Advertised HID Device found: Name: RAPOO BT4.0 KB, Address: b4:ee:25:f3:86:99, appearance: 961, serviceUUID: 0x1812
Scan Ended
Connected
Reconnected client
Connected to: b4:ee:25:f3:86:99
RSSI: -43
HID_REPORT_MAP 0x2a4b Value:
Done with this device!
Success! we should now be getting notifications!
b4:ee:25:f3:86:99 Disconnected - Starting scan
Advertised HID Device found: Name: RAPOO BT4.0 KB, Address: b4:ee:25:f3:86:99, appearance: 961, serviceUUID: 0x1812
Scan Ended
Connected
Reconnected client
Connected to: b4:ee:25:f3:86:99
RSSI: -42
HID_REPORT_MAP 0x2a4b Value: 5,1,9,6,A1,1,85,1,5,7,19,E0,29,E7,15,0,25,1,75,1,95,8,81,2,95,1,75,8,81,3,95,5,75,1,5,8,19,1,29,5,91,2,95,1,75,3,91,3,95,6,75,8,15,0,26,FF,0,5,7,19,0,29,FF,81,0,C0,5,C,9,1,A1,1,85,2,15,0,25,1,75,1,95,1E,A,24,2,A,25,2,A,26,2,A,27,2,A,21,2,A,2A,2,A,23,2,A,8A,1,9,E2,9,EA,9,E9,9,CD,9,B7,9,B6,9,B5,A,83,1,A,94,1,A,92,1,A,9,2,9,B2,9,B3,9,B4,9,8D,9,4,9,30,A,7,3,A,A,3,A,B,3,A,B1,1,9,B8,81,2,95,1,75,2,81,3,C0,
Characteristic: uuid: 0x2a4d, handle: 27 0x001b, props: 0x1a
Characteristic: uuid: 0x2a4d, handle: 31 0x001f, props: 0x1a
Characteristic: uuid: 0x2a4d, handle: 35 0x0023, props: 0x0e
Done with this device!
Success! we should now be getting notifications!
Notification from b4:ee:25:f3:86:99: Service = 0x1812, Characteristic = 0x2a4d, Value = 0,0,14,2B,0,0,0,0,
Notification from b4:ee:25:f3:86:99: Service = 0x1812, Characteristic = 0x2a4d, Value = 0,0,2B,0,0,0,0,0,
Notification from b4:ee:25:f3:86:99: Service = 0x1812, Characteristic = 0x2a4d, Value = 0,0,0,0,0,0,0,0,
Notification from b4:ee:25:f3:86:99: Service = 0x1812, Characteristic = 0x2a4d, Value = 0,0,14,0,0,0,0,0,
Notification from b4:ee:25:f3:86:99: Service = 0x1812, Characteristic = 0x2a4d, Value = 0,0,0,0,0,0,0,0,
Notification from b4:ee:25:f3:86:99: Service = 0x1812, Characteristic = 0x2a4d, Value = 0,0,2C,0,0,0,0,0,
这是让 CH567 USB0 Host 支持 Boot Protocol 的鼠标,需要对设备发送 Get_Protocol 和 Set_Protocol。
基于之前的USB0_HOSTMS ,代码改动如下:
1.声明使用的 COMMAND
const UINT8 SetupClrFeature[] = { 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }; //Clear feature
//LabzDebug_Start
const UINT8 SetupGetProtocol[] = { 0xA1, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00 }; //GET Protocol
const UINT8 SetupSetProtocol[] = { 0x21, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //SET Protocol
//LabzDebug_End
__attribute__ ((aligned(4))) UINT8 UHBuffer0[U0H_MAXPACKET_LEN]; //数据发送缓存区
2.在EnumDevice( PUSBDEV pusbdev )函数中加入:
//LabzDebug_Start
//GET_PROTOCOL
printf("Get Protocol..\n");
CopySetupReqPkg( (PUINT8)SetupGetProtocol);
printf("setup: "); for(i=0; i<8; i++) printf("%02x ", ((PUINT8)pSetupReq)[i]); printf("\n");
s = U0HCtrlTransfer( pusbdev, NULL, NULL, NULL ); // Ö´ÐпØÖÆ´«Êä
if ( s != USB_INT_SUCCESS ) return( s );
printf("in: "); for(i=0; i<len; i++) printf("%02x ", UHRecvBuf[i]); printf("\n");
//SET_PROTOCOL
printf("Set Protocol\n");
CopySetupReqPkg( (PUINT8)SetupSetProtocol );
printf("setup: "); for(i=0; i<8; i++) printf("%02x ", ((PUINT8)pSetupReq)[i]); printf("\n");
s = U0HCtrlTransfer( pusbdev, NULL, NULL, NULL ); // Ö´ÐпØÖÆ´«Êä
if ( s != USB_INT_SUCCESS ) return( s );
//LabZDebug_End
最近在研究 MIPI C-PHY 信号发生器,这个设备相比 USB 总线分析仪更加冷门。

MIPI是Mobile Industry Processor Interface 的缩写。MIPI协议实际上是一系列接口的协议,主要包含显示(DSI)、摄像头(CSI)等等。上图的设备是用于显示这个设备是用来产生 CSI MIPI 信号的。例如,我们的笔记本都会有摄像头,然后它通常位于盖子的上方,这样就需要通过线缆将CSI 信号从主板引到上方。这时候通常PM 会提出问题:经过了这么远的距离和好几个接头,是否会对摄像头成像质量有影响?如果确实有影响那么就必须通过增加Retimer或者Redriver的方式提升信号质量,在这种加钱的问题上 PM 是绝对不会放松的。使用这次的设备可以进行评估,在线缆的摄像头端连接上这个设备,假装有一个摄像头模组,通过发送不同的质量的信号,例如:1200mv或者780mv的MIPI信号,看看能否正常显示出来,从而得知线缆连接能够满足要求。
下面就是这个设备在测试过程中发送的信号,比如:加入抖动,改变信号电压等等。




使用方法也比较简单,首先请 Hardware 工程师连接输出端到线缆上;之后打开软件,选择型号

再选择测试类型,比如:自己编写一个或者打开已有的测试项目(正常情况下都是打开已有的测试项目,这是来自厂家,MIPI联盟的标准测试)

加载后点击 RUN 就可以进行测试了

测试会要求测试者和这个软件通过对话框进行交互,反馈当前被测试端显示是否正常。
最终生成Excel 格式的测试结果

参考:
1.这个型号设备的官网 https://introspect.ca/product/sv3c-cptx/
上次我们在 CH567 的 USB1 上实现了 USB CDC 的功能,这一次尝试在 USB0上实现同样的同能。相比之前的程序,需要修改的位置有:
__attribute__( ( interrupt ( "id="XSTR(INT_ID_SATA) ) ) )void SATA_Handler(void)
{
USB0DevIntDeal( );
}
2. \src\main\main.c 中打开 USB0 的中断
Interrupt_init( 1<<INT_ID_USB0 ); /* 系统总中断开启 */
USB0DeviceInit(); /* USB0Device Init */
printf("USB0 Device Init!\n");
while(1)
{
printf("Run\n");
mDelaymS(5000);
if (UsbConfig!=0)
{
memcpy( UsbEp3INBuf, &Msg[0], sizeof( Msg ));
R16_UEP3_T_LEN1 = sizeof( Msg );
R8_UEP3_TX_CTRL1 = (R8_UEP3_TX_CTRL1 & ~ MASK_UEP_T_RES) | UEP_T_RES_ACK;
while (R8_USB0_MIS_ST&bUMS_SIE_FREE==0) {}
}
};
3. ch56x_usb0dev372.h 中全部 USB1 替换为 USB0
4. ch56x_usb0dev372.c 中全部 USB1 替换为 USB0
这次使用 CopperCube 制作2个球体,然后可以通过 FireBeetle 控制这两个球体的颜色。
1.创建一个新的场景,删除场景中自带的立方体,然后创建一个球体(Sphere)

2.新建的球体是自带贴图的,这个贴图来自前面立方

3.选中球体,在Textures 中选择第一个空贴图,然后在属性的 Materials 中点击更换贴图

4.之后球体上面的贴图就为空了

5.为了便于观察,我们给图赋予一个颜色,选中物体后右键,在弹出菜单中 选择 “Modify Selection”->”Set vertex Colors”。 在弹出的调色板上选择你喜欢的颜色

6.球体变成了红色,选中球体后再使用右键调出菜单进行: clone

7.现在场景中有2个红色球体了,为了便于观察,改成动态光照,在Materials 中选择 Dynamic

8.在场景中创景一个光源

9.让光源动起来,具体方法在上次的文章中介绍过

10.之后保存场景为FBTest.ccb文件

11.编写一个响应键盘的JavaScripe 文档,当收到不同的按键时,改变球体的颜色。文件命名为 FBTest.js 放到和上面 FBTest.ccb 同一个目录下
// register key events
ccbRegisterKeyDownEvent("keyPressedDown");
function keyPressedDown(keyCode)
{
//z
if (keyCode == 90)
{
var sN = ccbGetSceneNodeFromName("sphereMesh1");
print(ccbGetSceneNodeMeshBufferCount(sN) );
for (var x=0; x<ccbGetMeshBufferVertexCount(sN,0); ++x) {
ccbSetMeshBufferVertexColor(sN, 0, x, 0x00ff0000);
}
}
//x
if (keyCode == 88)
{
var sN = ccbGetSceneNodeFromName("sphereMesh1");
print(ccbGetSceneNodeMeshBufferCount(sN) );
for (var x=0; x<ccbGetMeshBufferVertexCount(sN,0); ++x) {
ccbSetMeshBufferVertexColor(sN, 0, x, 0x0000FF00);
}
}
//c
if (keyCode == 67)
{
var sN = ccbGetSceneNodeFromName("sphereMesh2");
print(ccbGetSceneNodeMeshBufferCount(sN) );
for (var x=0; x<ccbGetMeshBufferVertexCount(sN,0); ++x) {
ccbSetMeshBufferVertexColor(sN, 0, x, 0x0000FF00);
}
}
//v
if (keyCode == 86)
{
var sN = ccbGetSceneNodeFromName("sphereMesh2");
print(ccbGetSceneNodeMeshBufferCount(sN) );
for (var x=0; x<ccbGetMeshBufferVertexCount(sN,0); ++x) {
ccbSetMeshBufferVertexColor(sN, 0, x, 0x000000FF);
}
}
print(keyCode );
}
/**
This example turns the ESP32 into a Bluetooth LE keyboard that writes the words, presses Enter, presses a media key and then Ctrl+Alt+Delete
*/
#include <BleKeyboard.h>
#define PINA 12
#define PINB 4
#define PINC 16
#define PIND 17
BleKeyboard bleKeyboard;
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE work!");
pinMode(PINA, INPUT_PULLUP);
pinMode(PINB, INPUT_PULLUP);
pinMode(PINC, INPUT_PULLUP);
pinMode(PIND, INPUT_PULLUP);
bleKeyboard.begin();
}
void loop() {
if (bleKeyboard.isConnected()) {
if (digitalRead(PINA) == LOW) {
Serial.println("Sending 'z'");
bleKeyboard.print("z");
delay(200);
}
if (digitalRead(PINB) == LOW) {
Serial.println("Sending 'x'");
bleKeyboard.print("x");
delay(200);
}
if (digitalRead(PINC) == LOW) {
Serial.println("Sending 'c'");
bleKeyboard.print("c");
delay(200);
}
if (digitalRead(PIND) == LOW) {
Serial.println("Sending 'v'");
bleKeyboard.print("v");
delay(200);
}
}
}