串口通信程序问题 [英] Problem with Serial Port communication program

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

问题描述

大家好!

我设法提出了一些代码,用于让串口设备与计算机通信,我发送一些数据并将相同的数据发回给我(作为测试程序)。但是,设备会发回一些不同的数据。



代码如下:



Hi guys!
I managed to come up with some code for making a Serial Port Device communicate with a computer wherein I send it some data and it sends the same data back to me (as a test program). However, the device sends back some different data.

THe code is as follows :

#include <stdafx.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <math.h>
#include <dos.h>
#define MAX 5000 //max length of delay time period
#define COM1 (unsigned short)0x3F8 // Serial Port COM1
#define COM2 (unsigned short)0x2F8 // Serial Port COM2

int TestSerial();
int Delay(int num);

int main(void)
{
  int rc=0;
  printf("\n");
  rc=TestSerial();
  if(rc!=0)
    printf("Error in TestSerial()!\n");
  else
    printf("Success with TestSerial!\n");
  return 0;
}

int TestSerial()
{
  int index, value, result=0;
  printf("Begin to execute outp() & inp() ... \n");
  for(index=0; index<10;index++)
  {
     printf("Data sent to COM1 is : %d \n",index);
     _outp(COM1,index);
     Delay(500);
     value=_inp(COM1);
     printf("Data returned from COM1 is : %d \n",value);
     if(value!=index)
     {
       printf("Error in loop testing of COM1! \n");
       result=-1;
       return result;
     }
  }
  return result;
}

int Delay(int num)
{
  int m,n,cycle=MAX;
  for(m=0;m<=num*cycle; m++)
    n=m-1;
  return 0;
}



我面临的问题是设备每次都返回不同的数据(这不是1-9的发送数据)。你能帮帮我吗?

另外,我想到了一种方法,在_outp()中我发送了一个特定于该设备的命令 - 比如它只是一个C指令..但是那种限制了我的程序的使用范围。 :(



PS我只使用#include<>但HTML预览会阻止相应的使用。




The problem I am facing is that the device returns different data EVERY time (which is not the sent data of 1-9). Could you please help me out ?
Also, I thought of a way where in _outp() I send a comman that is specific to the device - say it is an instruction in C only .. but then that kind of limits the scope of my program''s usage. :(

P.S. I have used #include <> only but the HTML preview prevents the appropriate usage.

推荐答案

要获得可能有用的代码,您应该:



  • 初始化串口(波特率,位数,奇偶校验,流量控制)。
  • 执行虚拟读取以清除状态寄存器位。
  • 通过测试线路状态寄存器的第0位(数据就绪)检查新数据是否可用的代码替换延迟循环。
To get code that might work you should:

  • Initialize the serial port (baud rate, number of bits, parity, flow control).
  • Perform a dummy read to clear the status register bits.
  • Replace the delay loop by code that checks if new data are available by testing bit 0 (Data Ready) of the line status register.


谢谢Jochen!:D

我接受了你的建议和链接..完成了tha软件开发!
thanks Jochen! :D
I took your advice and link .. finished that software development!


这篇关于串口通信程序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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