带API的RS232 [英] RS232 with API

查看:74
本文介绍了带API的RS232的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我的英语不好.如果您无法理解我的意思,请告诉我!因为我需要您的帮助.
当我通过带有API的RS232与主板通信时,但是长时间运行后,我的程序将在ReadFile()中停止.下面有一个粗体字,碰巧是黑体字.我找不到答案,也无法解决.我已经设置了超时时间,但是好像没有激活.即使时间过去了,但是我的程序也不会继续进行.我的程序出了点问题.请给我一个建议.谢谢.
(我简化了某些类,因为它是所有API的功能)

I''m sorry and my english is poor. If you can''t understand what i mean and tell me, please! Because of I need your help.
When I communication to board through RS232 with API, but my program will be stopped in ReadFile() after running for a long time. There is a progarm below and happen to boldface. I can''t find a answer and can''t solve it. I have setted up timeout but it seems like don''t active. Even through time is over but my program don''t go next step. Something wrong with my program. Please give me a advice. Thanks.
(some classes I simplied it because it''s all API''s function)

const Int32 INVALID_HANDLE_VALUE = -1;
System.IntPtr handle = (IntPtr)INVALID_HANDLE_VALUE;
DCB dcb = new DCB();  //class of DCB
CommTimeouts timeouts = new CommTimeouts(); //

private void Run()
{
   readthread = true;
   byte[] bufferr = new byte[230];
   int reclength = SendByte[5] * 2 + 5;
   System.Text.ASCIIEncoding Encoding = new System.Text.ASCIIEncoding();
   int written = 0;
   int readed = 0;
   int secondnow;
   int secondold;
   byte[] SendByte = new byte[8];

   do
   {
      if (handle == (IntPtr)INVALID_HANDLE_VALUE)
      {
        handle = CreateFile("COM7", GENERIC_READ | GENERIC_WRITE, 0, 0, 
                 OPEN_EXISTING, 0, 0);
        Thread.Sleep(1);
        GetCommState(handle, dcb);
        dcb.BaudRate = 57600;
        dcb.Parity = 0;         //無
        dcb.ByteSize = 8;       //資料位元
        dcb.StopBits = 1;
        SetCommState(handle, dcb);
        
        timeouts.ReadIntervalTimeout = 0;
        timeouts.ReadTotalTimeoutMultiplier = 0;
        timeouts.ReadTotalTimeoutConstant = 500;       
        timeouts.WriteTotalTimeoutMultiplier = 0;                      
        timeouts.WriteTotalTimeoutConstant = 500;                    
        IntPtr a = API_RS232.SetCommTimeouts(handle,ref timeouts);
        Thread.Sleep(1);
      }

      if (handle != (IntPtr)INVALID_HANDLE_VALUE)
      {
        WriteFile(handle,SendByte,(uint)SendByte.Length,ref written, 0);
        Thread.Sleep(50);
      }

      if (handle != (IntPtr)INVALID_HANDLE_VALUE)
      {
        ReadFile(handle, bufferr,(uint)reclength,ref readed,  
                     0);                   
      }

      Thread.Sleep(50);
    }

推荐答案

为什么(几乎)从不检查API返回值?
:)
Why do you (almost) never check API return values?
:)


这篇关于带API的RS232的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆