各位先進大家好 小弟遇到問題瓶頸了
主要問題如下
我使用 BCB寫一個RS232通訊可以下命令給馬達控制卡讓它動作
可是不知為何 有時候下命令 馬達會正常轉動 有時候卻只接受第一次所下之命令 讓小弟困惑不已 希望各位先進 可以解答在下問題 感激不進
#include
#include
#pragma hdrstop #include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1;
HANDLE hComY;
DWORD dwError;
BOOL fSuccess;
DCB dcb;
byte sread[1]; int send=0;
int reve=0;
int j=0;
char STX=0x02,ETX=0x03,CR=0x0D,LF=0x0A,SOH=0x01,ACK=0x06,SYN=0x16,FF=0x0C,ENQ=0x05; //---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//--------------------------------------------------------------------------- void __fastcall TForm1::FormCreate(TObject *Sender)
{
hComY = CreateFile("COM2",
GENERIC_READ | GENERIC_WRITE,
0, // comm devices must be opened w/exclusive-access
NULL, // no security attrs
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
if (hComY == INVALID_HANDLE_VALUE)
{
dwError = GetLastError();
}
fSuccess = GetCommState(hComY, &dcb); if (!fSuccess)
{
}
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
fSuccess = SetCommState(hComY, &dcb);
if (!fSuccess)
{
ShowMessage("Error");
}
COMMTIMEOUTS commtimeouts;
commtimeouts.ReadIntervalTimeout = 0;
commtimeouts.ReadTotalTimeoutMultiplier = 0;
commtimeouts.ReadTotalTimeoutConstant = 500;
commtimeouts.WriteTotalTimeoutMultiplier = 0;
commtimeouts.WriteTotalTimeoutConstant = 500; SetCommTimeouts(hComY, &commtimeouts); Memo1->Lines->Clear();
Memo2->Lines->Clear();
Edit1->Text = 0;
Timer2->Enabled =false;
Timer3->Enabled =false;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{ char Data[256];
DWORD Length;
sprintf(Data,"%s%c%s%c","SET P1",CR,"XMR -500",CR);
WriteFile(hComY,Data,255,&Length,0);
Memo2->Lines->Add(Data);
}
//--------------------------------------------------------------------------- void __fastcall TForm1::Button5Click(TObject *Sender)
{
char Data[256];
DWORD Length;
//sprintf(Data,"%s%c%s%c","SET P1",CR,"XMR 500",CR);
sprintf(Data,"%c%s%c%c",SOH,"XMR 500",CR,LF);
WriteFile(hComY,Data,255,&Length,0);
Memo2->Lines->Add(Data);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button13Click(TObject *Sender)
{ char Data[256];
DWORD Length;
sprintf(Data,"%c%s%c%c",SOH,"SET P1",CR,LF);
WriteFile(hComY,Data,255,&Length,0);
Memo2->Lines->Add(Data);
}
//--------------------------------------------------------------------------- void __fastcall TForm1::Button12Click(TObject *Sender)
{
Memo1->Lines->SaveToFile("1.txt");
}
//---------------------------------------------------------------------------
HI ALL