您的位置:首页 > 编程语言 > C语言/C++

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

2015-07-11 16:45 471 查看
// 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!\n");

HANDLE m_hUSBDevice  = INVALID_HANDLE_VALUE;
DWORD  dwNumDevices  = 0;

SI_GetNumDevices(&dwNumDevices);
printf("zengjf debug: dwNumDevices = %d.\n", dwNumDevices);
if ( dwNumDevices ==0 )
return FALSE;

if ( SI_Open(1, &m_hUSBDevice) == SI_SUCCESS )
printf("zengjf debug: SI_Open USBDevice success.\n");
else
printf("zengjf debug: SI_Open USBDevice fails.\n");

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.\n", hasRead);

// 以16进制的形式打印出接收到的一帧数据
printf("printf all data:\n\t");
for ( DWORD i = 0; i < hasRead; i++ )
printf(" %02x ", testData[i] & 0xff);
printf("\n");

// 判断接收到的数据是远程帧,还是数据帧
if ( testData[0] & ( 1 << 6 ) )
printf("Frame Format: Remote Frame.\n");
else
printf("Frame Format: Data Frame.\n");

// 输出数据长度
printf("Frame data length: %d.\n", testData[0] & 0xf);

// 输出是扩展帧,还是标准帧
if ( testData[0] & (1 << 7) ) {

printf("Frame Type: Extend Frame.\n");
// 解析扩展帧的ID
printf("ID: %X.\n", (((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 ].\n", testData+5);

} else {

printf("Frame Type: Standard Frame.\n");
// 解析标准帧的ID
printf("ID: %X.\n", (((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 ].\n", testData+3);

}

} else {
printf("zengjf debug: SI_Read USBDevice fails.\n");
break;
}
}

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 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: