VC++ 6.0 C8051F340 USB 通信 CAN 数据解析

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

/*****************************************************************************
 *              VC++ 6.0 C8051F340 USB 通信 CAN 数据解析
 * 声明:
 *    1. 这是在《VC++ 6.0 C8051F340 USB PC侧通信 Demo》的基础上的代码;
 *    2. 由一可知,本文会只注释了相对重要的内容。
 *    3. 本文主要是通过USB获取CAN的数据,并解析出其中的数据。
* 4. 帧格式可以参考:http://wenku.baidu.com/view/f508511d6bd97f192279e902.html * * 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! "); HANDLE m_hUSBDevice = INVALID_HANDLE_VALUE; DWORD dwNumDevices = 0; SI_GetNumDevices(&dwNumDevices); printf("zengjf debug: dwNumDevices = %d. ", dwNumDevices); if ( dwNumDevices ==0 ) return FALSE; if ( SI_Open(1, &m_hUSBDevice) == SI_SUCCESS ) printf("zengjf debug: SI_Open USBDevice success. "); else printf("zengjf debug: SI_Open USBDevice fails. "); char testData[17] = "zengjf"; DWORD hasWritten = 0; DWORD hasRead = 0; DWORD timeCount = 0; while ( true ) { Sleep(100); // 接收6帧数据就退出程序,作为测试程序,这个量也就差不多了 if ( timeCount++ > 6 ) break; memset(testData, 0, sizeof(testData)); if ( SI_Read( m_hUSBDevice, testData, 40, &hasRead) == SI_SUCCESS ) { printf("zengjf debug: SI_Read USBDevice success, hasRead length = %d. ", hasRead); // 以16进制的形式打印出接收到的一帧数据 printf("printf all data: "); for ( DWORD i = 0; i < hasRead; i++ ) printf(" %02x ", testData[i] & 0xff); printf(" "); // 判断接收到的数据是远程帧,还是数据帧 if ( testData[0] & ( 1 << 6 ) ) printf("Frame Format: Remote Frame. "); else printf("Frame Format: Data Frame. "); // 输出数据长度 printf("Frame data length: %d. ", testData[0] & 0xf); // 输出是扩展帧,还是标准帧 if ( testData[0] & (1 << 7) ) { printf("Frame Type: Extend Frame. "); // 解析扩展帧的ID printf("ID: %X. ", (((testData[1] & 0x0ff) << 21) | ((testData[2] & 0x0ff) << 13) | ((testData[3] & 0x0ff) << 5) | ((testData[4] >> 3) & 0x1f))); // 将二进制数值转换成字符数字 for ( DWORD i = 5; i < hasRead; i++ ) testData[i] += '0'; // 显示所有的接收的数据 printf("zengjf debug: show data from C8051F340 -- testData[ %s ]. ", testData+5); } else { printf("Frame Type: Standard Frame. "); // 解析标准帧的ID printf("ID: %X. ", (((testData[1] & 0x0ff) << 3 ) | ((testData[2] >> 5) & 0x7))); // 将二进制数值转换成字符数字 for ( DWORD i = 3; i < hasRead; i++ ) testData[i] += '0'; // 显示所有的接收的数据 printf("zengjf debug: show data from C8051F340 -- testData[ %s ]. ", testData+3); } } else { printf("zengjf debug: SI_Read USBDevice fails. "); break; } } if ( SI_Close(m_hUSBDevice) == SI_SUCCESS ) printf("zengjf debug: SI_Close USBDevice success. "); else printf("zengjf debug: SI_Close USBDevice fails. "); return 0; }
原文地址:https://www.cnblogs.com/zengjfgit/p/4638952.html