最近需要开发一个上位机测试软件,对下通过CAN总线读写来自车载控制模块的报文,并对其数据进行解析存储。本文分享了琢磨一天的学习结果,实现基于CANlib SDK的简单收发报文,下位机采用Kvaser CabKing工具,界面采用MFC。
1、了解CANlib收发流程,来个官方simple example
#include
#include
void main(void)
{
canHandle h;
canInitializeLibrary();
h = canOpenChannel(0, canWANT_EXCLUSIVE);
if (h < 0) {
char msg[64];
canGetErrorText((canStatus)h, msg, sizeof(msg));
fprintf(stderr, "canOpenChannel failed (%s)\n", msg);
exit(1);
}
canSetBusParams(h, BAUD_250K, 0, 0, 0, 0, 0);
canSetBusOutputControl(h, canDRIVER_NORMAL);
canBusOn(h);
canWrite(h, 123, "HELLO!", 6, 0);
canWriteSync(h, 500);
canBusOff(h);
canClose(h);
}
》CANlib API包含很多专用功能,许多功能都返回一个canStatus类型标志位;
》一般第一个函数调用canInitializeLibrary();用来初始化库文件;
》接下来canOpenChannel():打开通道,该函数返回一个通道标识符,后期一般会用作判断;
》下一步设置通道参数,canSetBusParams();参数略多,具体参考官方文档,其中总线速率常见1M、500K、250K、125K、100K等;
》参数设置完,canBusOn();激活CAN通道;
》发送消息canWrite();同理读取消息采用canRead();读取特定id消息canReadSpecific();
》关闭总线关闭通道(注意顺序)。
2、建VS工程,设置环境属性(本示例Visual Studio 2015)
(1)建立基于对话框MFC工程,把canlib32.lib和canlib.h等头文件放入工程目录,
(2)设置包含目录(设置为刚才放置头文件路径)、库目录(设置为放置lib文件路径)、附加依赖项(属性页->配置属性->链接器->输入->附加依赖项,编辑加上:canlib32.lib),至此CANlib环境设置完成,
3、页面设计(这里自由发挥了,见谅我画的很丑),每个元素注意规范ID号,为方便区分一般默认ID加_功能,如message编辑框ID:IDC_EDIT_msg
4、页面逻辑及CAN收发,开始撸代码
CANlibdemoMFCDlg.h
// CANlibdemoMFCDlg.h : 头文件
//
#pragma once
#include "canlib.h"
#include
using namespace std;
// CCANlibdemoMFCDlg 对话框
class CCANlibdemoMFCDlg : public CDialogEx
{
// 构造
public:
CCANlibdemoMFCDlg(CWnd* pParent = NULL); // 标准构造函数
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_CANLIBDEMOMFC_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnCbnSelchangeCombo1chan();
afx_msg void OnBnClickedButtonsend();
afx_msg void OnTimer(UINT_PTR nIDEvent);
int My_WcharToChar(char* pDest, CString& pSource);
canHandle h;
canHandle g;
CString m_channel;
CString m_speed;
CString m_mseeage;
CString m_inteval;
CString m_addr;
int channel, inteval, addr;
char m_arRecBuffer[8];
long id;
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedButtonlisten();
};
CANlibdemoMFCDlg.cpp
// CANlibdemoMFCDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "CANlibdemoMFC.h"
#include "CANlibdemoMFCDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CCANlibdemoMFCDlg 对话框
CCANlibdemoMFCDlg::CCANlibdemoMFCDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_CANLIBDEMOMFC_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CCANlibdemoMFCDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CCANlibdemoMFCDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_TIMER()
ON_WM_QUERYDRAGICON()
ON_CBN_SELCHANGE(IDC_COMBO1_chan, &CCANlibdemoMFCDlg::OnCbnSelchangeCombo1chan)
ON_BN_CLICKED(IDC_BUTTON_send, &CCANlibdemoMFCDlg::OnBnClickedButtonsend)
ON_BN_CLICKED(IDOK, &CCANlibdemoMFCDlg::OnBnClickedOk)
ON_BN_CLICKED(IDC_BUTTON_listen, &CCANlibdemoMFCDlg::OnBnClickedButtonlisten)
END_MESSAGE_MAP()
// CCANlibdemoMFCDlg 消息处理程序
BOOL CCANlibdemoMFCDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
CComboBox* pComb = (CComboBox*)GetDlgItem(IDC_COMBO1_chan);
pComb->InsertString(0, CString("0"));
pComb->InsertString(1, CString("1"));
pComb->SetCurSel(0);
pComb = (CComboBox*)GetDlgItem(IDC_COMBO_speed);
pComb->InsertString(0, CString("1M"));
pComb->InsertString(1, CString("500k"));
pComb->InsertString(2, CString("250k"));
pComb->InsertString(3, CString("125k"));
pComb->InsertString(4, CString("100k"));
pComb->InsertString(5, CString("83k"));
pComb->SetCurSel(0);
pComb = (CComboBox*)GetDlgItem(IDC_COMBO_intv);
pComb->InsertString(0, CString("1"));
pComb->InsertString(1, CString("2"));
pComb->InsertString(2, CString("3"));
pComb->InsertString(3, CString("4"));
pComb->InsertString(4, CString("5"));
pComb->SetCurSel(0);
canInitializeLibrary();
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CCANlibdemoMFCDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CCANlibdemoMFCDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CCANlibdemoMFCDlg::OnQueryDragIcon()
{
return static_cast(m_hIcon);
}
void CCANlibdemoMFCDlg::OnCbnSelchangeCombo1chan()
{
// TODO: 在此添加控件通知处理程序代码
}
void CCANlibdemoMFCDlg::OnBnClickedButtonsend()
{
// TODO: 在此添加控件通知处理程序代码
CString button;
GetDlgItemText(IDC_BUTTON_send, button);
if (button == _T("发送"))
{
GetDlgItemText(IDC_COMBO1_chan, m_channel);
GetDlgItemText(IDC_COMBO_speed, m_speed);
GetDlgItemText(IDC_EDIT_msg, m_mseeage);
GetDlgItemText(IDC_COMBO_intv, m_inteval);
GetDlgItemText(IDC_EDIT_addr, m_addr);
channel = _ttoi(m_channel);
addr = _ttoi(m_addr);
inteval = _ttoi(m_inteval);
h = canOpenChannel(channel, 0x20);
if (h < 0)
{
exit(1);
}
canSetBusParams(h, BAUD_250K, 0, 0, 0, 0, 0);
canSetBusOutputControl(h, canDRIVER_NORMAL);
canBusOn(h);
SetTimer(1, inteval*1000, NULL);
SetDlgItemText(IDC_BUTTON_send, _T("结束"));
}
else if (button == _T("结束"))
{
KillTimer(1);
SetDlgItemText(IDC_BUTTON_send, _T("发送"));
canBusOff(h);
canClose(h);
}
}
void CCANlibdemoMFCDlg::OnTimer(UINT_PTR nIDEvent)
{
unsigned int dlc;
unsigned int flags;
DWORD time;
char pChar[8] = "";
switch(nIDEvent)
{
case 1:
My_WcharToChar(pChar, m_mseeage);
canWrite(h, addr, pChar, 8, 0);
canWriteSync(h, 500);
break;
case 2:
memset(m_arRecBuffer, 0, sizeof(m_arRecBuffer));
int result = canRead(g, &id, m_arRecBuffer, &dlc, &flags, &time);
if (result == canOK)
{
if ((dlc == 8)&&(id!=addr))
{
CString str = _T("");
str.Format(_T("%d"), id);
SetDlgItemText(IDC_EDIT_id, str);
int m_nMotorPos = m_arRecBuffer[0] & 0xff;
str.Format(_T("%d"), m_nMotorPos);
SetDlgItemText(IDC_EDIT_b0, str);
m_nMotorPos = m_arRecBuffer[1] & 0xff;
str.Format(_T("%d"), m_nMotorPos);
SetDlgItemText(IDC_EDIT_b1, str);
m_nMotorPos = m_arRecBuffer[2] & 0xff;
str.Format(_T("%d"), m_nMotorPos);
SetDlgItemText(IDC_EDIT_b2, str);
m_nMotorPos = m_arRecBuffer[3] & 0xff;
str.Format(_T("%d"), m_nMotorPos);
SetDlgItemText(IDC_EDIT_b3, str);
m_nMotorPos = m_arRecBuffer[4] & 0xff;
str.Format(_T("%d"), m_nMotorPos);
SetDlgItemText(IDC_EDIT_b4, str);
m_nMotorPos = m_arRecBuffer[5] & 0xff;
str.Format(_T("%d"), m_nMotorPos);
SetDlgItemText(IDC_EDIT_b5, str);
m_nMotorPos = m_arRecBuffer[6] & 0xff;
str.Format(_T("%d"), m_nMotorPos);
SetDlgItemText(IDC_EDIT_b6, str);
m_nMotorPos = m_arRecBuffer[7] & 0xff;
str.Format(_T("%d"), m_nMotorPos);
SetDlgItemText(IDC_EDIT_b7, str);
}
}
break;
}
CDialogEx::OnTimer(nIDEvent);
}
int CCANlibdemoMFCDlg::My_WcharToChar(char* pDest, CString& pSource)
{
wchar_t* pawstr = NULL;
pawstr = pSource.GetBuffer(pSource.GetLength() + 1);
wcstombs(pDest, pawstr, pSource.GetLength() + 1);
return TRUE;
}
void CCANlibdemoMFCDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
CDialogEx::OnOK();
}
void CCANlibdemoMFCDlg::OnBnClickedButtonlisten()
{
// TODO: 在此添加控件通知处理程序代码
CString listen;
GetDlgItemText(IDC_BUTTON_listen, listen);
if (listen == _T("监听"))
{
SetDlgItemText(IDC_BUTTON_listen, _T("结束"));
g = canOpenChannel(1, 0x20);
if (g < 0)
{
exit(1);
}
canSetBusParams(g, BAUD_250K, 0, 0, 0, 0, 0);
canSetBusOutputControl(g, canDRIVER_NORMAL);
canBusOn(g);
SetTimer(2, 100, NULL);
}
else if (listen == _T("结束"))
{
KillTimer(2);
SetDlgItemText(IDC_BUTTON_listen, _T("监听"));
canBusOff(g);
canClose(g);
}
}
5、结果展示
(1)定时发送固定id和message报文
demo端发送:
Kvaser CAN King端接收到:
(2)监听来自Kvaser CAN King的报文
Kvaser CAN King端发送:
demo端接收到:
最后:
本文适合MFC和CAN新手,老油条请忽略。