且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VC++ 6.0 C8051F340 USB PC侧通信 Demo

更新时间:2022-08-12 20:46:55

// HelloWorld.cpp : Defines the entry point for the console application.
//

/***************************************************************************
 *                   VC++ 6.0 C8051F340 USB 通信 Demo
 * 声明:
 *     1. 本程序另外需要C8051F340单片机程序配合;
 *     2. 本程序是在拥有SiUSBXp.h、SiUSBXp.lib、SiUSBXp.dll的基础上做的,
 *         本人目前还并不知道这是从何而来,同事遗留。
 *     
 *                                2015-7-11 晴 深圳 南山平山村 增剑锋
 **************************************************************************/

#include "stdafx.h"
#include <windows.h>
#include <time.h>
#include "SiUSBXp.h"
#include <string.h>

int main(int argc, char* argv[])
{
    printf("Hello World!\n");

    HANDLE m_hUSBDevice  = INVALID_HANDLE_VALUE;
    DWORD  dwNumDevices  = 0;

    // 获取系统当前有多少可用设备
    SI_GetNumDevices(&dwNumDevices);                                
    printf("zengjf debug: dwNumDevices = %d.\n", dwNumDevices);

    // 如果设备数为零,则没必要继续运行
    if(dwNumDevices ==0)                                            
        return -1;

    // 打开第0个可用的设备
    if ( SI_Open(0, &m_hUSBDevice) == SI_SUCCESS)
        printf("zengjf debug: SI_Open USBDevice success.\n");    
    else {
        printf("zengjf debug: SI_Open USBDevice fails.\n");
        return -1;
    }
    
    // 初始化一些要传输的数据和一些将需要的数据
    char    testData[17]  = "zengjf";
    DWORD   hasWritten    = 0;
    DWORD   hasRead       = 0;

    // 将数据写入C8051F340单片机
    if ( SI_Write( m_hUSBDevice, testData, strlen(testData), &hasWritten) == SI_SUCCESS ) 
        printf("zengjf debug: SI_Write USBDevice success, hasWritten length = %d.\n", hasWritten);
    else {
        printf("zengjf debug: SI_Write USBDevice fails.\n");
        return -1;
    }

    // 睡眠1s,等待数据返回,这里是因为已经在C8051F340单片机内部已经设置了,会返回一串字符
    Sleep(1000);

    // 重新清理掉testData中的数据,为接收数据做准备
    memset(testData, 0, sizeof(testData));

    // 读取单片机内部C8051F340单片机发送回来的数据,单片机只发了16个字符,hasRead中保留真事读取字符个数
    if ( SI_Read( m_hUSBDevice, testData, 20, &hasRead) == SI_SUCCESS ) {
        printf("zengjf debug: SI_Read USBDevice success, hasRead length = %d.\n", hasRead);
        printf("zengjf debug: get data from C8051F340 -- testData[ %s ].\n", testData);
    } else {
        printf("zengjf debug: SI_Read USBDevice fails.\n");
        return -1;
    }
    
    // 关闭通信连接
    if ( SI_Close(m_hUSBDevice) == SI_SUCCESS )
        printf("zengjf debug: SI_Close USBDevice success.\n");
    else {
        printf("zengjf debug: SI_Close USBDevice fails.\n");
        return -1;
    }
    
    return 0;
}