회원가입 ID/PW 찾기

펌웨어 & 코딩언어 HOTrs232 통신프로그램..

예딩2010.12.06 18:1412.06조회 수 5951댓글 0이 게시물을

AA

오픈소스가많다는데 소켓프로그래밍밖에안보여서요..ㅠㅠ

rs231을 통한 일대일 채팅프로그램을 구현해야되는데..제대로 안되네요

글을 쓰면 연속적으로 써지는게 아니라

워키토키 방식으로 한줄씩 돌아가면서 순차적으로 글을써야만해요ㅠㅠ..이거어떻게고치죠?

 

#include <iostream.h>
#include <windows.h>
#include <string.h>
// using namespace std;

HANDLE hComm;
DCB m_dcb;

int Open_Port(char* szPort)
{
 //The CreateFile function opens a munications port
 hComm = CreateFile( szPort,  //pointer to name of the file
  //If a port does not exist, an error will occur (ERROR_FILE_NOT_FOUND)
  GENERIC_READ | GENERIC_WRITE, // access (read-write) mode. 
  0, // exclusive access.  Communications ports cannot be shared in the same manner that files are shared
  0, // default security attributes
  OPEN_EXISTING, //Opens the file. The function fails if the file does not exist.
  0,//FILE_FLAG_OVERLAPPED,
  0);
//If the function succeeds, the return value is an open handle to the specified file. 
//If the file does not exist before the call, GetLastError returns zero.


 // check serial port
 if (hComm == INVALID_HANDLE_VALUE)
 {
  // Handle the error
  cout << "CreateFile failed with error" << endl <<endl;
  return 1;
 }
 else
 {
  cout << "CreatFile is Success" << endl<<endl;  
 }

 return 0;
 
}

int Init_serial()
{

 //get serial communications device
 //baud rate, stop bits, byte size, Parity check

//There are three ways to initialize a DCB structure.
//The first method is to use the function GetCommState.
//This function returns the current DCB in use for the communications port. 
 if(GetCommState(hComm,&m_dcb))  // handle to communications device
          // pointer to device-control block structure   
 {
  cout << "Check Serial Satus" << endl;
  cout << "baud rate : " << m_dcb.BaudRate << endl;
  cout << "stop bit : " << m_dcb.StopBits  << endl;
  cout << "data size : " << m_dcb.ByteSize << endl;
  cout << "Ready to Serial" << endl<< endl;
 }
 else
 {
  cout << "Fail to Set serial" <<endl<<endl;
 }
 

 /*
 typedef struct _DCB { // dcb
    DWORD BaudRate;            // current baud rate
    DWORD fParity: 1;          // enable parity checking
    BYTE ByteSize;             // number of bits/byte, 4-8
    BYTE Parity;               // 0-4=no,odd,even,mark,space
    BYTE StopBits;             // 0,1,2 = 1, 1.5, 2
 } DCB;
 */


 // set serial device
 m_dcb.BaudRate = 115200;
 m_dcb.ByteSize = 8;
 m_dcb.StopBits = ONESTOPBIT;
 m_dcb.Parity   = NOPARITY;

//The SetCommState function configures a communications device according to the specifications
//in a device-control block (a DCB structure).
//The function reinitializes all hardware and control settings,
//but it does not empty output or input queues
 if(SetCommState(hComm,&m_dcb))  // handle to communications device
          // pointer to device-control block structure
 {
  cout << "Serial device is set" << endl;
  cout << "baud rate : " << m_dcb.BaudRate << endl;
  cout << "stop bit  : " << (int)m_dcb.StopBits  << endl;
  cout << "Parity    : " << (int)m_dcb.Parity    << endl;
  cout << "data size : " << (int)m_dcb.ByteSize  << endl<<endl;
 }
 else
 {
  cout << "Fail to Serial set" << endl;
  cout << "=============================" << endl;
  return 1;
 }

 return 0;
}

int Comp_str(char *a)
{
 int pt=0;

 if(strcmp(a,"/quit"))
  pt= 1;

 // cout << "Result of Compare : " << pt << endl;


 return pt;
}

int main()
{
 char *szPort;
 const int buff_size=2048;
 char buf[buff_size]="";
 char sbuf[buff_size]="";
 unsigned long byte_read=0;
 unsigned long byte_written=0;

 int protocol =0;
 int val;
 szPort="COM2";
  
 // Create File for Com Port
 if(Open_Port(szPort))
 {
  cout << " Fail to Create File for ComPort" << endl;
  return 1;
 }

 // Initialize Serial Port
 if(Init_serial())
 {
  cout << " Fail to Initialize Serial Port" << endl;
  return 1;
 }

 while(1)
   {

    cin.getline(buf, 20);
 
 

 val=WriteFile(hComm,  // handle to file to write to
    buf,    // pointer to data to write to file
    strlen(buf),  // number of bytes to write
    &byte_written,  // pointer to number of bytes written
    NULL); // pointer to structure for overlapped I/O
    if(val==0);
    
    cout << "send data : " <<buf << endl;
    
 

 val=ReadFile(hComm,  // handle of file to read
    sbuf,    // pointer to buffer that receives data
    sizeof(sbuf),  // number of bytes to read 
    &byte_read,   // pointer to number of bytes read
    NULL);    // pointer to structure for data

    if(val==0);
    {
     cout <<" recv_data : "<<sbuf << endl;
     memset(sbuf, 0, buff_size);
    }    
    
    
 }
     
 

 cout <<"End of Chatting" << endl;
 

 //The ReadFile function reads data from a file, starting at the position indicated by the file pointer.

 // device close
 CloseHandle(hComm);   // handle to object to close

 return 0;
}

댓글 0

하드웨어 설계 및 개발에 대하여 개발자들이 자유롭게 토론하는 공간입니다.
- Q&A, 자유주재 토론, 관련 정보 공유
- 분야 : 마이크로프로세서 응용, 전기/전자(아날로그/디지털) 회로 설계, C/C++ 프로그래밍, 펌웨어,
         PCB Artwork, 트러블슈팅 등 하드웨어 설계에 관한 전반인 내용
※ 게시글에 맞는 분류를 선택하여 글을 작성해 주시면 쾌적한 사이트 운영에 많은 도움이 됩니다.
※ 하드웨어 인사이트는 회원들간의 거래정보를 게재할 뿐이지, 그 어떤 책임과 의무도 가지지 않습니다.

search
번호 분류 제목 글쓴이 조회 수 날짜
708 마이크로프로세서 HOT이제 입문하게된 초보입니다. 어떤식으로 공부해야할까요?2 피어싱 1656 2011.01.04
707 마이크로프로세서 HOTatmega128 교육키트 사는 거 별로 비추천인가요?ㅠ7 rjmans 2256 2011.01.03
706 마이크로프로세서 HOTatmega128 교육키트를 살까하는데요,.. 추천좀 ㅠㅠ2 rjmans 3430 2011.01.02
705 마이크로프로세서 HOTat90can128관련질문입니다.2 레고 2964 2010.12.31
704 마이크로프로세서 HOTCC2430 만능기판에 꾸며 다운로드 하기 로미옹 2059 2010.12.28
703 마이크로프로세서 HOTRS232 를 이용한 ATmega128통신7 데닉시 3519 2010.12.27
702 마이크로프로세서 HOTSTM32F103R8T6 ADC 입력1 컴맹9506 4084 2010.12.27
701 마이크로프로세서 HOT노트북 전원에 따른 노이즈 발생 문제3 초당당 2965 2010.12.23
700 마이크로프로세서 HOTATmega128 전원공급에 관한 질문입니다.3 데닉시 3255 2010.12.22
699 마이크로프로세서 HOT마이크로마우스 관련 질문좀 드릴께요1 모범생 1414 2010.12.20
698 마이크로프로세서 HOTdot matrix 회로도인데요 ..문제점좀 찾아주세요 ㅠㅠ4 서울서비 2682 2010.12.17
697 마이크로프로세서 HOTAVR Studio 용량 제한 문제좀 해결해주세요..ㅠㅠ2 에류시온 1587 2010.12.15
696 마이크로프로세서 HOTAVR 을 이용한 도트매트릭스,적외선, LCD 회로 설계..ㅜ5 따지긴 4563 2010.12.15
695 마이크로프로세서 HOTor cad 자료에 대해서3 서울서비 1527 2010.12.12
694 마이크로프로세서 HOTatmega16을 이용한 작업을 하려고 합니다. 개발환경이 궁금합니다.2 고니77 3472 2010.12.10
693 마이크로프로세서 HOT고수님께 질문드리겠습니다..2 촌철살인 5501 2010.12.10
692 마이크로프로세서 HOT8051 주파수 측정기 소스때문에..5 지안이기여워 2949 2010.12.10
691 마이크로프로세서 HOTㅣ297+7026 으로 스텝모터제어 질문입니다 건들면터져 3233 2010.12.04
690 마이크로프로세서 HOT기본적인건데 틀을 잘못잡겠네요 ㅠㅠ3 김나나 2605 2010.12.04
689 마이크로프로세서 HOT스위치를 이용해서 LCD 문자 입력하기2 김나나 2133 2010.12.04
Prev 1 ... 10 11 12 13 14 15 16 17 18 19 ... 50 Next
  • 약속을 잘하는 사람은 잊어버리기도 잘한다.
    - T.플러
  • * 납포인트 정보 *
  • 글 작성 : 3
  • 댓글 작성 : 1
  • 내 글이 추천받음 : 1
저작권법에 위배되는 콘텐츠는 등록 불가하며, 저작물에 대한 권리는 저작자에게 있습니다.
Copyright 2006-2021 © hardwareis.com, All rights reserved.