MFC串口通讯,处理数据,更新一段时间会卡死。求原因

hit?? 2016-09-05 09:53:30
还在编写中,任务,初学,不成熟。读模块数据。
为什么在编译后运行时,读取模块数据若一定时间不关闭串口,会卡死。
接收的十六进制数据会不断更新,但是处理后的数据一段时间后停止更新。卡死,无法点击关闭串口。(如果我在那个时间内来回点打开或关闭串口,数据正常显示更新)
并且一段时间后更新的十六进制数会两组数据一换行。我希望是一组数据,一换行,开始时的确是这样。
模块在非十六进制下,用其他串口软件读取是一段有规律的乱码,接尾是什么.com,十六进制下是正常的数据。
求大神们解答。
void C串口V2Dlg::OnCommMscomm1()
{
// TODO: 在此处添加消息处理程序代码

COleVariant myVar;
COleSafeArray safearray_inp;
LONG len, k;
BYTE rxdata[2048]; //设置BYTE数组 An 8-bit integerthat is not signed.
CString strtemp,str;
INT i = 0,flag,j;
FLOAT sum ;

if (m_mscom.get_CommEvent() == 2)
{
myVar.Attach(m_mscom.get_Input()); //读缓冲区
safearray_inp = myVar; //VARIANT型变量转换为ColeSafeArray型变量
len = safearray_inp.GetOneDimSize(); //得到有效数据长度
for (k = 0; k<len; k++)
safearray_inp.GetElement(&k, rxdata + k);//转换为BYTE型数组
for (k = 0; k<len; k++) //将数组转换为Cstring型变量
{
BYTE bt = *(char*)(rxdata + k); //字符型

strtemp.Format("%02X ",bt ) ; //将字符以十六进制方式送入临时变量strtemp存放,加入一个空隔

if (strtemp == "5A " && i == 0)//帧头处换行
{
strtemp.Format("\r\n%02X ", bt);
i = 1;
}
else if (strtemp == "5A " && i == 1)//第二个帧头标志下一位要验证数据类型
{
i = 2;
}
else if (i == 2)//验证数据类型
{
if (strtemp == "15 ")
flag = 1;
else if (strtemp == "25 ")
flag = 2;
else if (strtemp == "35 ")
flag = 3;
else if (strtemp == "45 ")
flag = 4;
else if (strtemp == "65 ")
flag = 6;
i = 3;
}
else if (i == 3)//多少位数据位
{
if (strtemp == "06 ")
j = 6;
else if (strtemp == "08 ")
j = 8;
i = 4;
}
else if (i == 4 && j>0)//处理数据
{
switch (flag)
{
case 1://加速度计 待更改。。。
{
str = strtemp;
if (j % 2 == 0)
{
sum = strtoul(str, NULL, 16) * pow(2, 8);//将16进制字符串转化为10进制unsigned long,高8位

}
else
{
sum = sum + strtoul(str, NULL, 16);//加上低八位
}
switch (j)//更新显示加速度计实际数据
{
case 5:
{str.Format("%.2f", sum); m_accX = str; sum = 0; break; }
case 3:
{str.Format("%.2f", sum); m_accY = str; sum = 0; break; }
case 1:
{str.Format("%.2f", sum); m_accZ = str; sum = 0; break; }
default:break;
}
break;
}
case 2: //陀螺仪 待更改。。。
{
str = strtemp;
if (j % 2 == 0)
{
sum = strtoul(str, NULL, 16) * pow(2, 8);
}
else
{
sum = sum + strtoul(str, NULL, 16);
}
switch (j)//更新显示陀螺仪实际数据
{
case 5:
{str.Format("%.2f", sum); m_gyroX = str; sum = 0; break; }
case 3:
{str.Format("%.2f", sum); m_gyroY = str; sum = 0; break; }
case 1:
{str.Format("%.2f", sum); m_gyroZ = str; sum = 0; break; }
default:break;
}
break;
}
case 4://欧拉角 待更改。。。
{
str = strtemp;
if (j % 2 == 0)
{
sum = strtoul(str, NULL, 16) * pow(2, 8);
}
else
{
sum = sum + strtoul(str, NULL, 16);
}
switch (j)//更新显示欧拉角实际数据,
{
case 5:
{str.Format("%.2f", sum / 100); m_yaw = str; sum = 0; break; }
case 3:
{str.Format("%.2f", sum / 100); m_pitch = str; sum = 0; break; }
case 1:
{str.Format("%.2f", sum / 100); m_roll = str; sum = 0; break; }
default:break;
}
break;
}
case 6://四元数 待更改。。。
{
str = strtemp;
if (j % 2 == 0)
{
sum = strtoul(str, NULL, 16) * pow(2, 8);
}
else
{
sum = sum + strtoul(str, NULL, 16);
}
switch (j)//更新显示四元数实际数据
{
case 7:
{str.Format("%.4f", sum / 10000); m_q0 = str; sum = 0; break; }
case 5:
{str.Format("%.4f", sum / 10000); m_q1 = str; sum = 0; break; }
case 3:
{str.Format("%.4f", sum / 10000); m_q2 = str; sum = 0; break; }
case 1:
{str.Format("%.4f", sum / 10000); m_q3 = str; sum = 0; break; }
default:break;
}
break;
}
}
j--;
}
else if (j == 0)//j=0时,数据位已经处理完,到达了校验位,i清零,flag清零
{
i = 0;
flag = 0;
}

m_EditReceive += strtemp; //加入接收编辑框对应字符串
}

m_EditReceive += "\r\n";
UpdateData(FALSE); //更新编辑框内容
}
GetDlgItem(IDC_EDIT1)->SendMessage(WM_VSCROLL, MAKEWPARAM(SB_BOTTOM, 0), 0);//滚动条自动下翻

}
...全文
1638 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Cacar 2016-09-20
  • 打赏
  • 举报
回复
用vs的profile功能看下哪些代码占用时间过多导致卡死,就知道问题所在了。
赵4老师 2016-09-20
  • 打赏
  • 举报
回复
任何收发两端速度不一致的通讯,都需要在它们之间使用一个足够大的FIFO缓冲区。 对任何FIFO缓冲区的使用,都需要仔细考虑接收端接收时超时无数据和发送端发送时FIFO缓冲区已满这两种情况下该如何做。 这些概念都在这段经典代码中有所体现。 这段经典代码还包括以下必须考虑的因素: ◆跨Windows和Linux平台 ◆多线程锁 ◆多线程日志 ◆日志文件占用的磁盘空间可控 ◆日志中的时间包括毫秒 ◆传输的数据对应的每个字节到底是几 ◆如何退出多线程程序 ◆……
//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#ifdef _MSC_VER
    #pragma warning(disable:4996)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
    #include <windows.h>
    #include <process.h>
    #include <io.h>
    #define  MYVOID             void
    #define  vsnprintf          _vsnprintf
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  MYVOID             void *
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef _MSC_VER
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
void sleep_ms(int ms) {
    Sleep(ms);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
void sleep_ms(int ms) {
    usleep(ms*1000);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;

    if (NULL==pszFmt||0==pszFmt[0]) return;
    vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;

    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
#define ASIZE    200
#define BSIZE    240
#define CSIZE      2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX;
CRITICAL_SECTION cs_BBB;
struct FIFO_BUFFER {
    int  head;
    int  tail;
    int  size;
    char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
    int i,j,k;
    char binstr[80];

    Lock(&cs_HEX);
    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%03d %04x -",cn,i);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j++) {
                sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
            }
            Log("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j++) {
            sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
        }
        Log("%s\n",binstr);
    }
    Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;

    lent=0;
    Lock(cs);
    if (fbuf->size>=len) {
        lent=len;
        if (fbuf->head+lent>BSIZE) {
            len1=BSIZE-fbuf->head;
            memcpy(buf     ,fbuf->data+fbuf->head,len1);
            len2=lent-len1;
            memcpy(buf+len1,fbuf->data           ,len2);
            fbuf->head=len2;
        } else {
            memcpy(buf     ,fbuf->data+fbuf->head,lent);
            fbuf->head+=lent;
        }
        fbuf->size-=lent;
    }
    Unlock(cs);
    return lent;
}
MYVOID thdB(void *pcn) {
    char        *recv_buf;
    int          recv_nbytes;
    int          cn;
    int          wc;
    int          pb;

    cn=(int)pcn;
    Log("%03d thdB              thread begin...\n",cn);
    while (1) {
        sleep_ms(10);
        recv_buf=(char *)Cbuf;
        recv_nbytes=CSIZE;
        wc=0;
        while (1) {
            pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
            if (pb) {
                Log("%03d recv %d bytes\n",cn,pb);
                HexDump(cn,recv_buf,pb);
                sleep_ms(1);
            } else {
                sleep_ms(1000);
            }
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef _MSC_VER
    pthread_exit(NULL);
#endif
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;

    Lock(cs);
    lent=len;
    if (fbuf->size+lent>BSIZE) {
        lent=BSIZE-fbuf->size;
    }
    if (fbuf->tail+lent>BSIZE) {
        len1=BSIZE-fbuf->tail;
        memcpy(fbuf->data+fbuf->tail,buf     ,len1);
        len2=lent-len1;
        memcpy(fbuf->data           ,buf+len1,len2);
        fbuf->tail=len2;
    } else {
        memcpy(fbuf->data+fbuf->tail,buf     ,lent);
        fbuf->tail+=lent;
    }
    fbuf->size+=lent;
    Unlock(cs);
    return lent;
}
MYVOID thdA(void *pcn) {
    char        *send_buf;
    int          send_nbytes;
    int          cn;
    int          wc;
    int           a;
    int          pa;

    cn=(int)pcn;
    Log("%03d thdA              thread begin...\n",cn);
    a=0;
    while (1) {
        sleep_ms(100);
        memset(Abuf,a,ASIZE);
        a=(a+1)%256;
        if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
        send_buf=(char *)Abuf;
        send_nbytes=ASIZE;
        Log("%03d sending %d bytes\n",cn,send_nbytes);
        HexDump(cn,send_buf,send_nbytes);
        wc=0;
        while (1) {
            pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
            Log("%03d sent %d bytes\n",cn,pa);
            HexDump(cn,send_buf,pa);
            send_buf+=pa;
            send_nbytes-=pa;
            if (send_nbytes<=0) break;//
            sleep_ms(1000);
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef _MSC_VER
    pthread_exit(NULL);
#endif
}
int main() {
#ifdef _MSC_VER
    InitializeCriticalSection(&cs_log);
    InitializeCriticalSection(&cs_HEX);
    InitializeCriticalSection(&cs_BBB);
#else
    pthread_t threads[2];
    int threadsN;
    int rc;
    pthread_mutex_init(&cs_log,NULL);
    pthread_mutex_init(&cs_HEX,NULL);
    pthread_mutex_init(&cs_BBB,NULL);
#endif
    Log("Start===========================================================\n");

    BBB.head=0;
    BBB.tail=0;
    BBB.size=0;

#ifdef _MSC_VER
    _beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
    _beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);
#else
    threadsN=0;
    rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
    rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
#endif

    if (!access("No_Loop",0)) {
        remove("No_Loop");
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    while (1) {
        sleep_ms(1000);
        if (No_Loop) break;//
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    sleep_ms(3000);
    Log("End=============================================================\n");
#ifdef _MSC_VER
    DeleteCriticalSection(&cs_BBB);
    DeleteCriticalSection(&cs_HEX);
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_BBB);
    pthread_mutex_destroy(&cs_HEX);
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}
Antony_WU_SZ 2016-09-19
  • 打赏
  • 举报
回复
1.缓冲区由以下二个选项设置: m_ComPort.SetInBufferSize(2048); //设置输入缓冲区的大小,Bytes m_ComPort.SetOutBufferSize(2048); //设置输出缓冲区的大小,Bytes 2.根本不用担心太快会导到缓冲区溢出,因为,你还有一个触发事件,当有多少个数据进就触发一次接收数据的事件。 m_ComPort.SetRThreshold(1); //为1表示有一个字符引发一个事件,引发的事件是:OnCommMscomm(); 你在里面接收数据即可。 m_ComPort.SetInputLen(0); //接收数据 但是如果你的数据非常多而且快速的传送的话,就不要设置为1,例如改大一些10、128、256甚至更大,否则你的接收处理太频繁(因为收到可能还要分析之类的,读取也要时间的)就赶不上速度了。SetInputLen一般用0就可以了。
hit?? 2016-09-13
  • 打赏
  • 举报
回复
引用 1 楼 sevancheng的回复:
问题应该不在这段代码,debug模式下运行程序,打印调试信息试试
我把所有数据分开刷新显示了。把接收模块原始数据的编辑框更新语句删除后,发现其他的计算出的数据刷新正常。那我应该怎么处理接收原始数据的编辑框?
躺着睡的蜗牛 2016-09-07
  • 打赏
  • 举报
回复
编辑框数据到了一定大小会变得很卡 可以试试隔一段时间清空下编辑框或者数据接收到一定大小清空下编辑框
hit?? 2016-09-07
  • 打赏
  • 举报
回复
引用 2 楼 躺着睡的蜗牛的回复:
编辑框数据到了一定大小会变得很卡 可以试试隔一段时间清空下编辑框或者数据接收到一定大小清空下编辑框
一段时间后清空编辑框,还是会卡。就是处理后的欧拉角那些数据显示卡死了。接收的原始数据还是在刷新。突然会刷新很快,然后速度越来越慢,然后原始数据开始有缺失。欧拉角等数据卡死后,cpu占用会逐渐增加。
sevancheng 2016-09-06
  • 打赏
  • 举报
回复
问题应该不在这段代码,debug模式下运行程序,打印调试信息试试

3,245

社区成员

发帖
与我相关
我的任务
社区描述
ATL,Active Template Library活动(动态)模板库,是一种微软程序库,支持利用C++语言编写ASP代码以及其它ActiveX程序。
社区管理员
  • ATL/ActiveX/COM社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧