VS2015 给Console 程序加上图标的方法

默认情况下, Console 程序的图标是下面这种。这次介绍一下如何用其他的图标来替换之。


1.创建一个 Win32 Console 程序。在 Resource Files上点右键:

2.在弹出的菜单上选择 AddàResource…, 这样就为项目创建了一个 Resource文件

3.双击生成的 rc文件

4.跳转之后在文件上使用右键,选择 “Add Resources….”

5.选择 Icon,然后 Import

6.弹出的对话框上选择你需要的 icon文件

7.导入之后,在导入的图标上单击右键,选择 Properties….

8.改ID为IDC_MAINFRAME

生成的EXE 如下:

参考:

1. https://blog.csdn.net/weixin_30603633/article/details/96342177

Step to UEFI (248)安装一个自定义的 ACPI Table

UEFI Spec 介绍了一个 EFI_ACPI_TABLE_PROTOCOL,定义如下:

EFI_ACPI_TABLE_PROTOCOL

从介绍可以看出,我们能够使用这个 PROTOCOL 添加(Install)或者删除(Uninstall)一个 ACPI Table。

首先准备一个 ACPI Table, 这里顶一个一个叫做 LBZT 的 Table。

DefinitionBlock ("LABZT.AML", "LBZT", 2, "", "", 0x0)
{
 Name(BUF1, Buffer(){0x00,0x01,0x02,0x03,0x04,0x05})
 Name(BUF2, "www.lab-z.com")
}

DefinitionBlock语法定义如下【参考1】:

DefinitionBlock 语法定义

AMLFileName 是给编译器看的,用于指定输出的 AML 文件名;

TableSignature 是 ACPI Table 的名字(4字节)

ComplianceRevision, 2以及大于2是指定64位;1或者0指定32位(这里我不清楚具体差别,做了一个实验,比如定义:Name(BUF3, 0x1122334455),当ComplianceRevision为0时,编译之后结果发生截断,实际定义是Name(BUF3, 0x22334455);但是当ComplianceRevision为2时,编译结果和代码相同)。如果在处理较大的数值时,需要特别注意这里。

OEMID OEM自定义 ID

TableID  OEM自定义Table 名称(8Bytes)

OEMRevision OEM自定义数值

接下来我们首先自定义一个 ACPI Table 如下:

DefinitionBlock ("LABZ64.AML", "LABZ", 2, "", "", 0x0)
{
 Name(BUF1, Buffer(){0x00,0x01,0x02,0x03,0x04,0x05})
 Name(BUF2, "www.lab-z.com")
 Name(BUF3, 0x1122334455)
}

编译之:

iasl.exe 编译 ASL

得到的是一个二进制文件LABZ64.aml

查看生成的 AML 文件

使用工具转化为C的定义,我们就可以在代码中直接使用了。测试代码如下:

#include  <Uefi.h>
#include  <Library/UefiLib.h>
#include  <Library/ShellCEntryLib.h>
#include  <Library/UefiBootServicesTableLib.h>
#include  <Protocol/AcpiTable.h>

extern EFI_BOOT_SERVICES         *gBS;

EFI_GUID gEfiAcpiTableProtocolGuid ={ 
                0xFFE06BDD, 0x6107, 0x46A6, 
                { 0x7B, 0xB2, 0x5A, 0x9C, 0x7E, 0xC5, 0x27, 0x5C }};
                
/* Contents of file LABZ64.aml */
const long int LABZ64_aml_size = 85;
const unsigned char LABZ64_aml[85] = {
    0x4C, 0x41, 0x42, 0x5A, 0x55, 0x00, 0x00, 0x00, 0x02, 0x7A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x4E, 0x54, 0x4C,
    0x18, 0x10, 0x19, 0x20, 0x08, 0x42, 0x55, 0x46, 0x31, 0x11, 0x09, 0x0A, 0x06, 0x00, 0x01, 0x02,
    0x03, 0x04, 0x05, 0x08, 0x42, 0x55, 0x46, 0x32, 0x0D, 0x77, 0x77, 0x77, 0x2E, 0x6C, 0x61, 0x62,
    0x2D, 0x7A, 0x2E, 0x63, 0x6F, 0x6D, 0x00, 0x08, 0x42, 0x55, 0x46, 0x33, 0x0E, 0x55, 0x44, 0x33,
    0x22, 0x11, 0x00, 0x00, 0x00
};
                
int
EFIAPI
main (
  IN int Argc,
  IN char **Argv
  )
{
        EFI_STATUS              Status;
        EFI_ACPI_TABLE_PROTOCOL *AcpiTableProtocol;
        UINTN                   TableKey;
        
        Status = gBS->LocateProtocol(
                           &gEfiAcpiTableProtocolGuid, 
                           NULL,
                           (VOID **)&AcpiTableProtocol);
        if (EFI_ERROR(Status)) {
            Print(L"Cannot find ACPI_TABLE_PROTOCOL \r\n");
            return Status;
        }
        
        AcpiTableProtocol->InstallAcpiTable(
                                AcpiTableProtocol,
                                (VOID *)LABZ64_aml,
                                LABZ64_aml_size,
                                &TableKey);
        gBS->CloseProtocol ( 
                        AcpiTableProtocol,
                        &gEfiAcpiTableProtocolGuid,
                        gImageHandle,
                        NULL );
        return EFI_SUCCESS;
}

实体机上进行测试,运行 att.efi 之后可以使用 Acpiview 命令查看到如下:

--------------- LABZ Table --------------- 

Address  : 0x44B1D000
Length   : 85
  
00000000 : 4C 41 42 5A 55 00 00 00 - 02 7A 00 00 00 00 00 00   LABZU....z......
00000010 : 00 00 00 00 00 00 00 00 - 00 00 00 00 49 4E 54 4C   ............INTL
00000020 : 18 10 19 20 08 42 55 46 - 31 11 09 0A 06 00 01 02   ... .BUF1.......
00000030 : 03 04 05 08 42 55 46 32 - 0D 77 77 77 2E 6C 61 62   ....BUF2.www.lab
00000040 : 2D 7A 2E 63 6F 6D 00 08 - 42 55 46 33 0E 55 44 33   -z.com..BUF3.UD3
00000050 : 22 11 00 00 00                                      "....

Table Checksum : OK

ACPI Table Header                    :
  Signature                          : LABZ
  Length                             : 85
  Revision                           : 2
  Checksum                           : 0x7A
  Oem ID                             :       
  Oem Table ID                       :         
  Oem Revision                       : 0x0
  Creator ID                         : INTL
  Creator Revision                   : 0x20191018

Table Statistics:
	0 Error(s)
	0 Warning(s)

再进一步,启动到 Windows后用 RW 进行查看也可以看到 LABZ Table

这里是新加入的 ACPI Table

完整代码下载:

参考:

1. https://acpica.org/sites/acpica/files/asl_tutorial_v20190625.pdf

Step to UEFI (247)从 SecCoreStartupWithStack 到 Pei

书接上回,下面的语句输出了第一条 Debug Log,它位于 SecMain.c 中:

  DEBUG ((DEBUG_INFO,
    "SecCoreStartupWithStack(0x%x, 0x%x)\n",
    (UINT32)(UINTN)BootFv,
    (UINT32)(UINTN)TopOfCurrentStack
));

接下来就使用下面的语句跳转到SecStartupPhase2中:

//
// Initialize Debug Agent to support source level debug in SEC/PEI phases before memory ready.

//
InitializeDebugAgent (DEBUG_AGENT_INIT_PREMEM_SEC, &amp;amp;SecCoreData, SecStartupPhase2);

这个函数位于 \MdeModulePkg\Library\DebugAgentLibNull\DebugAgentLibNull.c,从代码上看到就是一个跳转而已:

/**
  Initialize debug agent.

  This function is used to set up debug environment to support source level debugging.
  If certain Debug Agent Library instance has to save some private data in the stack,
  this function must work on the mode that doesn't return to the caller, then
  the caller needs to wrap up all rest of logic after InitializeDebugAgent() into one
  function and pass it into InitializeDebugAgent(). InitializeDebugAgent() is
  responsible to invoke the passing-in function at the end of InitializeDebugAgent().

  If the parameter Function is not NULL, Debug Agent Library instance will invoke it by
  passing in the Context to be its parameter.

  If Function() is NULL, Debug Agent Library instance will return after setup debug
  environment.

  @param[in] InitFlag     Init flag is used to decide the initialize process.
  @param[in] Context      Context needed according to InitFlag; it was optional.
  @param[in] Function     Continue function called by debug agent library; it was
                          optional.

**/
VOID
EFIAPI
InitializeDebugAgent (
  IN UINT32                InitFlag,
  IN VOID                  *Context, OPTIONAL
  IN DEBUG_AGENT_CONTINUE  Function  OPTIONAL
  )
{
  if (Function != NULL) {
    Function (Context);
  }
}

继续在 SecMain.c中执行SecStartupPhase2() 函数,这个函数负责找到 PEI Core 的 Entry Point

/**
  Caller provided function to be invoked at the end of InitializeDebugAgent().

  Entry point to the C language phase of SEC. After the SEC assembly
  code has initialized some temporary memory and set up the stack,
  the control is transferred to this function.

  @param[in] Context    The first input parameter of InitializeDebugAgent().

**/
VOID
EFIAPI
SecStartupPhase2(
  IN VOID                     *Context
  )

其中的跳转代码如下:

  //
  // Transfer the control to the PEI core
  //
  (*PeiCoreEntryPoint) (SecCoreData, (EFI_PEI_PPI_DESCRIPTOR *)&amp;mPrivateDispatchTable);

其中 PeiCoreEntryPoint 类型是 EFI_PEI_CORE_ENTRY_POINT ,定义可以在 \mdepkg\include\pi\PiPeiCis.h 看到:

/**
  The entry point of PEI Foundation.

  This function is the entry point for the PEI Foundation, which
  allows the SEC phase to pass information about the stack,
  temporary RAM and the Boot Firmware Volume. In addition, it also
  allows the SEC phase to pass services and data forward for use
  during the PEI phase in the form of one or more PPIs. These PPI's
  will be installed and/or immediately signaled if they are
  notification type. There is no limit to the number of additional
  PPIs that can be passed from SEC into the PEI Foundation. As part
  of its initialization phase, the PEI Foundation will add these
  SEC-hosted PPIs to its PPI database such that both the PEI
  Foundation and any modules can leverage the associated service
  calls and/or code in these early PPIs.

  @param SecCoreData    Points to a data structure containing
                        information about the PEI core's
                        operating environment, such as the size
                        and location of temporary RAM, the stack
                        location and the BFV location.

  @param PpiList        Points to a list of one or more PPI
                        descriptors to be installed initially by
                        the PEI core. An empty PPI list consists
                        of a single descriptor with the end-tag
                        EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST.
                        As part of its initialization phase, the
                        PEI Foundation will add these SEC-hosted
                        PPIs to its PPI database such that both
                        the PEI Foundation and any modules can
                        leverage the associated service calls
                        and/or code in these early PPIs.


**/
typedef
VOID
(EFIAPI *EFI_PEI_CORE_ENTRY_POINT)(
  IN CONST  EFI_SEC_PEI_HAND_OFF    *SecCoreData,
  IN CONST  EFI_PEI_PPI_DESCRIPTOR  *PpiList
);

接下来的跳转进入\MdePkg\Library\PeiCoreEntryPoint\PeiCoreEntryPoint.c 中的ModuleEntryPoint()

/**
  The entry point of PE/COFF Image for the PEI Core.

  This function is the entry point for the PEI Foundation, which allows the SEC phase
  to pass information about the stack, temporary RAM and the Boot Firmware Volume.
  In addition, it also allows the SEC phase to pass services and data forward for use
  during the PEI phase in the form of one or more PPIs.
  There is no limit to the number of additional PPIs that can be passed from SEC into
  the PEI Foundation. As part of its initialization phase, the PEI Foundation will add
  these SEC-hosted PPIs to its PPI database such that both the PEI Foundation and any
  modules can leverage the associated service calls and/or code in these early PPIs.
  This function is required to call ProcessModuleEntryPointList() with the Context
  parameter set to NULL.  ProcessModuleEntryPoint() is never expected to return.
  The PEI Core is responsible for calling ProcessLibraryConstructorList() as soon as
  the PEI Services Table and the file handle for the PEI Core itself have been established.
  If ProcessModuleEntryPointList() returns, then ASSERT() and halt the system.

  @param SecCoreData  Points to a data structure containing information about the
                      PEI core's operating environment, such as the size and
                      location of temporary RAM, the stack location and the BFV
                      location.

  @param PpiList      Points to a list of one or more PPI descriptors to be
                      installed initially by the PEI core. An empty PPI list
                      consists of a single descriptor with the end-tag
                      EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST.
                      As part of its initialization phase, the PEI Foundation will
                      add these SEC-hosted PPIs to its PPI database, such that both
                      the PEI Foundation and any modules can leverage the associated
                      service calls and/or code in these early PPIs.

**/
VOID
EFIAPI
_ModuleEntryPoint(
  IN CONST  EFI_SEC_PEI_HAND_OFF    *SecCoreData,
  IN CONST  EFI_PEI_PPI_DESCRIPTOR  *PpiList
)
{
  ProcessModuleEntryPointList (SecCoreData, PpiList, NULL);

  //
  // Should never return
  //
  ASSERT(FALSE);
  CpuDeadLoop ();
}

函数中会调用一个构造函数:

\Build\OvmfX64\NOOPT_VS2015x86\X64\MdeModulePkg\Core\Pei\PeiMain\DEBUG\AutoGen.c
VOID
EFIAPI
ProcessModuleEntryPointList (
  IN CONST  EFI_SEC_PEI_HAND_OFF    *SecCoreData,
  IN CONST  EFI_PEI_PPI_DESCRIPTOR  *PpiList,
  IN VOID                           *Context
  )

{
  PeiCore (SecCoreData, PpiList, Context);
}

最终,跳入位于\MdeModulePkg\Core\Pei\PeiMain\PeiMain.c中的如下函数:

/**
  This routine is invoked by main entry of PeiMain module during transition
  from SEC to PEI. After switching stack in the PEI core, it will restart
  with the old core data.

  @param SecCoreDataPtr  Points to a data structure containing information about the PEI core's operating
                         environment, such as the size and location of temporary RAM, the stack location and
                         the BFV location.
  @param PpiList         Points to a list of one or more PPI descriptors to be installed initially by the PEI core.
                         An empty PPI list consists of a single descriptor with the end-tag
                         EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST. As part of its initialization
                         phase, the PEI Foundation will add these SEC-hosted PPIs to its PPI database such
                         that both the PEI Foundation and any modules can leverage the associated service
                         calls and/or code in these early PPIs
  @param Data            Pointer to old core data that is used to initialize the
                         core's data areas.
                         If NULL, it is first PeiCore entering.

**/
VOID
EFIAPI
PeiCore (
  IN CONST EFI_SEC_PEI_HAND_OFF        *SecCoreDataPtr,
  IN CONST EFI_PEI_PPI_DESCRIPTOR      *PpiList,
  IN VOID                              *Data
  )

前面可以看到,这里是通过 ProcessModuleEntryPointList (SecCoreData, PpiList, NULL); 进行调用的,因此,这里Data==NULL,所以也是第一次运行:

  //
  // Retrieve context passed into PEI Core
  //
  OldCoreData = (PEI_CORE_INSTANCE *) Data;
  SecCoreData = (EFI_SEC_PEI_HAND_OFF *) SecCoreDataPtr;

  //
  // Perform PEI Core phase specific actions.
  //
  if (OldCoreData == NULL) {
    //
    // If OldCoreData is NULL, means current is the first entry into the PEI Core before memory is available.
    //
    ZeroMem (&PrivateData, sizeof (PEI_CORE_INSTANCE));
    PrivateData.Signature = PEI_CORE_HANDLE_SIGNATURE;
    CopyMem (&PrivateData.ServiceTableShadow, &gPs, sizeof (gPs));
  }

其中PrivateData 是 PEI_CORE_INSTANCE           PrivateData; 其中 PEI_CORE_INSTANCE 定义在PeiMain.h 中报错了 Pei Core 的一些信息,比如:当前 Fv中的 FFS 个数等等。第一次进入PeiCore 的时候(OldCoreData == NULL),代码会准备PrivateData的内容。

ESP32 S2 USB Host 读取键盘数据

ESP32-S2 带有一个集成了收发器的全速 USB OTG 外设,符合 USB 1.1 规范。意思是S2即支持 USB Device 又支持Host。于是,这次测试在 Arduino 环境下通过 ESP32 S2 直接支持读取 USB Keyboard 的按键信息。

准备工作有点复杂:

  1. 必须使用 ESP32 2.0.1 环境,如果你使用 2.0.2 会出现编译不过的情况

2.硬件上GPIO19 和 GPIO20 可以分别作为 USB 的 D- 和 D+,这里我直接飞线接到一个 USB 母头上:

3.安装库下面这两个库

准备完成后,即可编译测试 esp32-usb-host-demos-main 中的 usbhidboot 示例代码。

4.编译上传之后如果想看到结果,还需要将 Core Debug Level 设置为 Verbose ,默认的 None 不会有任何输出

比如,我这边看到的结果如下:

Step to UEFI (246)显示 JPEG 图片的 DXE 驱动

之前介绍过如何在UEFI 下显示 BMP【参考1】,PCX【参考2】,PNG【参考3】和 GIF【参考4】。这次介绍的是一个 DXE Driver, 使用之后会在系统中注册 EFI_JPEGDECODER_PROTOCOL,这样 UEFI Application 可以通过这个 Protocol 进行 JPEG 的解码显示。这个代码来自【参考5】,有兴趣的朋友可以到原文进行查看。

代码分为两个,一个是 DXE Driver,另外一个是用于测试的 UEFI Application

首先介绍 DXE Driver 的编译(这次使用的是EDK2 202108 【参考6】):

1. MdeModulePkg\MdeModulePkg.dsc 修改如下:

[Components]
  #LABZ_Debug_Start
  MdeModulePkg/JpegDecoderDxe/JpegDecoderDxe.inf
  MdeModulePkg/Application/JPGDecoderTest/JPGDecoderTest.inf
  #LABZ_Debug_End
  MdeModulePkg/Application/HelloWorld/HelloWorld.inf
  MdeModulePkg/Application/DumpDynPcd/DumpDynPcd.inf
  MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.inf

2. MdeModulePkg\MdeModulePkg.dec 修改如下:

[Protocols]
  ##LABZ_Debug_Start
  gEfiJpegDecoderProtocolGuid          = { 0xa9396a81, 0x6231, 0x4dd7, {0xbd, 0x9b, 0x2e, 0x6b, 0xf7, 0xec, 0x73, 0xc2} }
  ##LABZ_Debug_End
  ## Load File protocol provides capability to load and unload EFI image into memory and execute it.
  #  Include/Protocol/LoadPe32Image.h
  #  This protocol is deprecated. Native EDKII module should NOT use this protocol to load/unload image.
  #  If developer need implement such functionality, they should use BasePeCoffLib.
  gEfiLoadPeImageProtocolGuid    = { 0x5CB5C776, 0x60D5, 0x45EE, { 0x88, 0x3C, 0x45, 0x27, 0x08, 0xCD, 0x74, 0x3F }}

3. 在\MdeModulePkg\Include\Protocol\下面放置 :JpegDecoder.h

4. 在 \MdeModulePkg\ 下面放置JpegDecoderDxe目录

接下来加入一个测试的 UEFI Application。为了简化代码,我首先使用工具将图片转化为C语言的 .h文件,代码直接引用对应内存:

#include <Uefi.h>
#include <Library/PcdLib.h>
#include <Library/UefiLib.h>
#include <Library/UefiApplicationEntryPoint.h>
#include <Library/MemoryAllocationLib.h>
#include <Protocol/GraphicsOutput.h>
#include <JpegDecoder.h>
#include "demo.h"

extern EFI_BOOT_SERVICES         *gBS;
extern EFI_SYSTEM_TABLE          *gST;

EFI_GUID GraphicsOutputProtocolGuid = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
EFI_GRAPHICS_OUTPUT_PROTOCOL          *GraphicsOutput = NULL;

EFI_STATUS
EFIAPI
UefiMain (
        IN EFI_HANDLE        ImageHandle,
        IN EFI_SYSTEM_TABLE  *SystemTable
)
{
        EFI_STATUS                      Status;
        EFI_JPEG_DECODER_PROTOCOL        *JpegDecoderProtocol;
        UINT8* RGB32;
        UINTN DecodedDataSize;
        UINTN Height,Width;
        EFI_JPEG_DECODER_STATUS DecoderStatus;

        Status = gBS->LocateProtocol(
                         &GraphicsOutputProtocolGuid,
                         NULL,
                         (VOID **) &GraphicsOutput);
        if (EFI_ERROR(Status))
        {
                GraphicsOutput = NULL;
                Print(L"Loading Graphics_Output_Protocol error!\n");
                return EFI_SUCCESS;
        }

        Status = gBS->LocateProtocol(
                         &gEfiJpegDecoderProtocolGuid,
                         NULL,
                         (VOID **) &JpegDecoderProtocol);
        if (EFI_ERROR(Status))
        {
                Print(L"Loading Efi_JpegDecoder_Protocol failed!\n");
                return EFI_SUCCESS;
        }

        RGB32 = (UINT8*)AllocatePool(636*373*4);
        JpegDecoderProtocol->DecodeImage(
                JpegDecoderProtocol,
                (UINT8 *)&demo_jpg,
                demo_jpg_size,
                &RGB32,
                &DecodedDataSize,
                &Height,
                &Width,
                &DecoderStatus
        );

        GraphicsOutput->Blt(
                GraphicsOutput,
                (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *) RGB32,
                EfiBltBufferToVideo,
                0, 0,
                0, 0,
                Width, Height, 0);

        Print(L"Height=[%d],Width=[%d]\n",Height,Width);
        FreePool(RGB32);

        return EFI_SUCCESS;
}

简单的说就是在系统中查找EFI_JPEG_DECODER_PROTOCOL   ,然后调用之。需要注意的是在调用的时候需要分配一个内存用于存储解压后的图像,但是这个 PROTOCOL 没有提供获得 JPEG 图片长宽的函数,因此要么直接分配足够大的内存,要么使用者知道图片的尺寸(比如,用于显示的 Logo,在Build的时候一定是知道具体尺寸的)。这里我知道图片尺寸,所以使用下面的方法直接开辟一段内存用于存储:

  RGB32 = (UINT8*)AllocatePool(636*373*4);

使用方法是,首先 load JpegDecoderDxe.efi, 之后运行 jpgt.efi 即可显示:

运行结果:

UEFI Shell下测试显示 JPEG

可以看到,这种方式能够方便的显示 JPEG 格式的图片。

完整的代码下载:

参考:

  1. https://www.lab-z.com/bmplib/ BmpSupportLib
  2. https://www.lab-z.com/pcxdecoder/ UEFI 下 PCX 的解码
  3. https://www.lab-z.com/uefipngdecoder/ UEFI 下的 PNG 解码
  4. https://www.lab-z.com/decodergif/ UEFI 下的 GIF 解码
  5. https://github.com/XENNOK/Insyde_BIOS_Source
  6. https://www.lab-z.com/edk202108/

CH567 的编译和下载

首先介绍一下CH567代码的编译,以自带的EXAMPLE为例:

  1. 在 Project Explorer 上点击鼠标右键,在弹出的菜单上选择 Import
选择 Import

如果没有这个窗口,可以在 Window -> Show View ->Project Explorer 中打开之

打开 Project Explorer

2.再选择Existing Projects into Workspace

导入已经存在的工程

3.这里选择 USB0_DevCH372 作为示例

导入 CH372的例子

4.之后可以用下面这个按钮进行编译,可以编译为 Debug 或者 Release版本

选择编译目标

5.很快就能完成编译

编译成功

在 Output 目录下的 GPIO.bin 就是最终的编译结果。

接下来介绍如何下载到开发板上:

1.CH567 上有2个 USB Port,分别是 USB0 和 USB1。对于CH567 来说,只支持从USB1下载。

电路图上的USB1 和USB0

对应PCB 中,上方是 USB1 下方是 USB0

PCB上的 USB1 和 USB0

2.下载方法是:首先按住DOWNLOAD按钮,然后将USB 线插入USB1中,插入之后松开按钮

DWN 按钮位于 USB1 左侧

3.在设备管理器中能看到新增加的设备(如果没有的话,可能的原因是板子没有上电或者板子有硬件问题)

新出现了一个 USB Module 设备

4.打开下载工具。首先在1的位置切换到 CH56X 页面,然后在2的位置选择芯片型号为 CH567,接下来在3选择要下载的设备(如果没有的话,请检查硬件),最后,在4的位置选择刚才提到编译后生成的文件

5.很快就能完成下载:

下载成功

之后将 USB线连接到 USB0 上,在设备管理器中可以看到如下设备:

CH372 设备

最后多提一下关于串口调试信息的输出,示例代码使用的是 UART3在 PA5上,只需要用USB串口线的 RTX 连接到这个引脚,共地之后使用 115200 波特率。

冷知识:CPU 上电后BIOS运行的第一条指令

我最初看到“CPU 上电后BIOS运行的第一条指令是什么?”这个问题后的第一反应是:一个跳转指令啊。但是实际上并非如此,下面是 Intel TigerLake 平台一个BIOS ROM 末尾处的机器码:

Intel TigerLake 平台第一条BIOS代码

可以看到,上电后 CPU 运行的第一条指令是 0x90(NOP)。

查看 OVMF的代码,在 \OvmfPkg\ResetVector\Ia16\ResetVectorVtf0.asm 中:

;
; The VTF signature
;
; VTF-0 means that the VTF (Volume Top File) code does not require
; any fixups.
;
vtfSignature:
    DB      'V', 'T', 'F', 0

ALIGN   16

resetVector:
;
; Reset Vector
;
; This is where the processor will begin execution
;
    nop
    nop
    jmp     EarlyBspInitReal16
ALIGN   16
fourGigabytes:

同样的,第一条指令也是 NOP。

根据公众号“泰山N思维 ”的说法:

当前BIOS的头两条NOP代码没有特殊的意义,只是为了替换 wbinvd指令(机器码:0f 09,用于flush内部的Cache,并把Cache line数据写回内存)。早期CPU 第一条指令使用wbinvd指令的原因,相对比较“靠谱”的说法是:在CPU开始执行时候,虽然Cache处于Disable状态(CR0.CD),但只代表CPU Core不使用Cache(no-fill-mode),不代表Cache中没有有效的数据,通过wbinvd指令可以invalid无效化Cache中的数据;而新的CPU Invalid的操作已经由硬件执行,不再需要额外操作。后来由于wbinvd指令在某些CPU上会导致hang机问题,并且Intel新的CPU并不需要执行wbinvd指令,所以Intel使用两条nop进行了替换。

就是说这两条指令没有特殊意义,只是因为历史原因需要用2条指令来填充这里。

有兴趣的朋友不妨订阅““泰山N思维  “这个公众号。

泰山N思维 公众号

Step to UEFI (245)Debug Port Protocol 测试

通常情况下,我们在通过串口进行 Debug Message 输出的时候通常直接对 0x3F8 Port进行编程,但是这种方式并不符合 UEFI 规范。正规的做法是通过 EFI_DEBUGPORT_PROTOCOL来实现。在 UEFI 规范中有如下定义:

针对这个 Protocol 编写的测试代码如下:

#include  <Uefi.h>
#include  <Library/UefiLib.h>
#include  <Library/ShellCEntryLib.h>
#include <Protocol/DebugPort.h>
#include  <Library/UefiBootServicesTableLib.h> //global gST gBS gImageHandle

EFI_GUID gEfiDebugPortProtocolGuid = EFI_DEBUGPORT_PROTOCOL_GUID;

int
EFIAPI
main (
        IN int Argc,
        IN char **Argv
)
{
        EFI_STATUS              Status;
        EFI_DEBUGPORT_PROTOCOL  *DebugPort = NULL;
        CHAR8                   *TestMessage="www.lab-z.com";

        Status = gBS->LocateProtocol(
                         &gEfiDebugPortProtocolGuid,
                         NULL,
                         (VOID **) &DebugPort);
        if (EFI_ERROR(Status))
        {
                Print(L"Can't load DebugPortProtocol error!\n");
                return EFI_SUCCESS;
        }

        UINTN   Length=AsciiStrLen(TestMessage);
        DebugPort->Write(
                DebugPort,
                1000,
                &Length,
                (VOID *)TestMessage
        );
        
        gBS->CloseProtocol ( 
                        DebugPort,
                        &gEfiDebugPortProtocolGuid,
                        gImageHandle,
                        NULL );
        
        return EFI_SUCCESS;

}

运行之后主机端的串口程序中可以看到有字符串的输出:

串口工具可以看到输出

完整代码:

做一个Micro USB Host

去年最火爆的就是芯片了,我在21年4月购买的 MAX3421芯片还只要16.6元

MAX3421e 21年3月只要 16.6元

而今天再点进去查看报价已经达到了 130 (咨询下来预期50左右):

MAX3421e 22年2月已经按照 130元报价了

于是萌发了制作一个能够多次复用模块的想法,简单的说设计足够小的 PCB 然后将芯片焊接在上面,将必要的引脚引出,使其成为一个“模块”。

电路图设计如下:

Arduino Micro USB Host 电路图

为了保证体积足够小,使用了贴片式晶振,这个晶振有4个引脚,分别是2个 GND ,1个XO 一个XI;尺寸是 3.2×2.5mm 厚度是 0.7mm,因此这种封装也被称作SMD3225-4P。

SMD3225-4P 的晶振

PCB 设计如下:

Arduino Micro USB Host PCB

为了尽量缩减体积,上面只保留必要的5个电容,同时选用 0603封装的,不得不承认,0603封装能够极大方便布线。

名称用途 用途名称
INT用于MAX3421通知单片机有中断发生SPI的MOSIMOSI
GNDSPI的MOSIMISO
MD-USB Host D-SPI的片选SS
MD+USB Host D+SPI的 CLOCKSCLK
VBCOMP检查USB 设备的 VBUS 是否存在芯片的 RESET Pin, 正常情况下必须为高RESET
GND芯片供电3.3V
引脚说明
PCB 实物

焊接完成后,我们就可以在 FireBeetle 上进行测试了:

首先,FireBeetle  VCC 给USB 母头供电,同时共地,其余引脚连接如下:

名称FireBeetle FireBeetle名称
INTD3IO23MOSI
GNDGNDIO19MISO
MD-USB 母头 D-D7SS
MD+USB 母头 D+IO18SCLK
VBCOMPUSB 母头 5v3.3VRESET
GNDGND3.3V3.3V
对FireBeetle 的连接方式

之后就可以直接使用 USB Host Shield 2.0 的库了,比如运行 \USBHIDBootMouse.ino 这个示例:

#include <hidboot.h>
#include <usbhub.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

class MouseRptParser : public MouseReportParser
{
protected:
	void OnMouseMove	(MOUSEINFO *mi);
	void OnLeftButtonUp	(MOUSEINFO *mi);
	void OnLeftButtonDown	(MOUSEINFO *mi);
	void OnRightButtonUp	(MOUSEINFO *mi);
	void OnRightButtonDown	(MOUSEINFO *mi);
	void OnMiddleButtonUp	(MOUSEINFO *mi);
	void OnMiddleButtonDown	(MOUSEINFO *mi);
};
void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{
    Serial.print("dx=");
    Serial.print(mi->dX, DEC);
    Serial.print(" dy=");
    Serial.println(mi->dY, DEC);
};
void MouseRptParser::OnLeftButtonUp	(MOUSEINFO *mi)
{
    Serial.println("L Butt Up");
};
void MouseRptParser::OnLeftButtonDown	(MOUSEINFO *mi)
{
    Serial.println("L Butt Dn");
};
void MouseRptParser::OnRightButtonUp	(MOUSEINFO *mi)
{
    Serial.println("R Butt Up");
};
void MouseRptParser::OnRightButtonDown	(MOUSEINFO *mi)
{
    Serial.println("R Butt Dn");
};
void MouseRptParser::OnMiddleButtonUp	(MOUSEINFO *mi)
{
    Serial.println("M Butt Up");
};
void MouseRptParser::OnMiddleButtonDown	(MOUSEINFO *mi)
{
    Serial.println("M Butt Dn");
};

USB     Usb;
USBHub     Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser                               Prs;

void setup()
{
    Serial.begin( 115200 );
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    Serial.println("Start");

    if (Usb.Init() == -1)
        Serial.println("OSC did not start.");

    delay( 200 );

    HidMouse.SetReportParser(0, &Prs);
}

void loop()
{
  Usb.Task();
}
面包板上进行测试

本文提到的电路图和PCB 下载(立创 EDA)