Name: Anonymous 2007-11-01 2:38
My friend is writing firmware for some sensor, and to analyze output he had to use rs232 to send data to computer. He wasted almost two weeks on this, because it didn't work. here's the code he ended with. He said he had to use that FILE_FLAG_OVERLAPPED because this is the only way to read from asynchronous serial port, that this is written in winapi documentation and on various websights. T_T. I feel sorry for all good people who are fooled by bullshit on the internet.
// com_port1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <windows.h>
#include <string.h>
void PrintLastError(void){
int ercode = GetLastError();
printf("(-) GetLastError() return %i ", ercode );
switch( ercode ){
case 2: printf("(The system cannot find the file specified)\n"); break;
case 5: printf("(Access is denied)\n"); break;
case 29: printf("(The system cannot write to the specified device)\n"); break;
case 87: printf("(The parameter is incorrect)\n"); break;
case 998: printf("(Invalid access to memory location)\n"); break;
// тут описания для самых распространенных ошибок, остальные пару сотен добавите сами 8)
default: printf("\n");
}
}
char Data;
char Data1[] = "FcU_1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23-24-25-26-27-28-29-30-31-32-23";
unsigned char Flag_end;
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int k=0;
COMSTAT CStat;
HANDLE port1;
//Открытие портa
port1 = CreateFile("COM1",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
// port1 = CreateFile("COM1",GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
// port1 = CreateFile(TEXT("COM1"),GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
if( port1 != INVALID_HANDLE_VALUE )
printf("(+) %s initialized\n", "COM1");
else
printf("(-) %s initialization failed\n", "COM1");
SetupComm(port1,2048,2048);
//отмена приема и передачи,очистка буферов ввода-вывода порта
int retcode
=
PurgeComm(
port1,
PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR
);
// retcode будет содержать код возврата
if( retcode==NULL )
printf("(-) PurgeComm1() failed\n");
else
printf("(+) 1Discarded all characters from the output and input buffer\n");
retcode = ClearCommBreak(port1);
if( retcode==NULL )
{
printf("(-) ClearCommBreak1() failed\n");
PrintLastError();
}
else
printf("(+) 1Restored character transmission and placed the transmission line in a nonbreak state\n");
//-----------------------Настройка DCB--------------------------------------------------------------------------
DCB dcb;
retcode = GetCommState(port1,&dcb);
if( retcode==NULL )
printf("(-) GetCommState1() failed\n");
else
printf("(+) 1Retrieved the current control settings for %s\n", "COM5");
// изменяем только то что нам нужно:
dcb.DCBlength = sizeof(DCB); // длина структуры
dcb.BaudRate = CBR_9600; // установка уровня передачи
//dcb.fBinary = TRUE; // установка режима передачи:бинарный
dcb.Parity = NOPARITY; // установка контроля четности:нет
//dcb.fOutxCtsFlow = TRUE; // контроль уровня CTS:TRUE
//dcb.fOutxDsrFlow = TRUE; // контроль уровня DSR:TRUE
dcb.fDtrControl = DTR_CONTROL_DISABLE; // режим управления сигналом DTR:DTR_CONTROL_ENABLE;
dcb.fDsrSensitivity = FALSE; // fuck you ,spielberg!
dcb.fTXContinueOnXoff = FALSE; // Передача продолжается при переполнении буфера
// и передаче драйвером символа XoffChar;
//dcb.fOutX =FALSE ; // передача не зависит от символа XON/XOFF
//dcb.fInX = 1;
//dcb.fErrorChar = 1;
//dcb.fNull = 1;
//dcb.fRtsControl = 2;
//dcb.fAbortOnError = 1;
//dcb.fDummy2 = 17;
//dcb.wReserved;
//dcb.XonLim;
//dcb.XoffLim;
//dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.StopBits = ONESTOPBIT; // one stop bit
//dcb.XonChar;
//dcb.XoffChar;
//dcb.ErrorChar;
//dcb.EofChar;
//dcb.EvtChar;
//dcb.wReserved1;
//dcb.fDtrControl = DTR_CONTROL_ENABLE;
//dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
// и устанавливаем новый опции порта:
retcode = SetCommState(port1, &dcb);
if( retcode==NULL )
printf("(-) SetCommState1() failed\n");
else
printf("(+) 2Reinitialized all hardware and control settings \n");
//----------------------------------------------------------------------------------------------------------------
//-------------------------------настройка таймаутов--------------------------------------------------------------
COMMTIMEOUTS TIMEOUTS;
retcode = GetCommTimeouts(port1,&TIMEOUTS);
if(retcode == NULL)
{
printf("(-) GetTimeout() failed\n");
}
else
{
printf("(+) GetTimeout() succeed\n");
};
TIMEOUTS.ReadIntervalTimeout=MAXDWORD;
TIMEOUTS.ReadTotalTimeoutConstant=0;
TIMEOUTS.ReadTotalTimeoutMultiplier=0;
TIMEOUTS.WriteTotalTimeoutConstant=0;
TIMEOUTS.WriteTotalTimeoutMultiplier=0;
retcode = SetCommTimeouts(port1,&TIMEOUTS);
if(retcode == NULL)
{
printf("(-) SetTimeout() failed\n");
}
else
{
printf("(+) SetTimeout() succeed\n");
}
//-----------------------------------------------------------------------------------------------------------------