1

我正在开发一个具有 GSM 模块的项目,它还与计算机进行串行通信。

我在 Visual Studio 2010 上用 C 语言编写了一个代码来串行传输和接收数据。

代码如下: -

#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h> 
#include <commdlg.h>
int nread,nwrite;


int main()
{

COMMTIMEOUTS timeouts;
COMMCONFIG dcbSerialParams;
char *words, *buffRead, *buffWrite;
DWORD dwBytesWritten,dwBytesRead;

HANDLE hSerial= CreateFile(L"COM1", GENERIC_READ | GENERIC_WRITE,
                       0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if ( hSerial == INVALID_HANDLE_VALUE) 
{ 
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
printf(" serial port does not exist \n");
} 
printf(" some other error occured. Inform user.\n");
}


//DCB    dcbSerialParams ;
//GetCommState( hSerial, &dcbSerialParams.dcb);
if (!GetCommState(hSerial, &dcbSerialParams.dcb)) 
{
printf("error getting state \n");
}

dcbSerialParams.dcb.DCBlength = sizeof(dcbSerialParams.dcb);


dcbSerialParams.dcb.BaudRate = CBR_9600;
dcbSerialParams.dcb.ByteSize = 8;
dcbSerialParams.dcb.StopBits = ONESTOPBIT;
dcbSerialParams.dcb.Parity = NOPARITY;

dcbSerialParams.dcb.fBinary = TRUE;
dcbSerialParams.dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcbSerialParams.dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcbSerialParams.dcb.fOutxCtsFlow = FALSE;
dcbSerialParams.dcb.fOutxDsrFlow = FALSE;
dcbSerialParams.dcb.fDsrSensitivity= FALSE;
dcbSerialParams.dcb.fAbortOnError = TRUE;


if (!SetCommState(hSerial, &dcbSerialParams.dcb)) 
{
printf(" error setting serial port state \n");
}


GetCommTimeouts(hSerial,&timeouts);
//COMMTIMEOUTS timeouts = {0};

timeouts.ReadIntervalTimeout = 1000;
timeouts.ReadTotalTimeoutConstant = 1000;
timeouts.ReadTotalTimeoutMultiplier = 1000;
timeouts.WriteTotalTimeoutConstant = 1000;
timeouts.WriteTotalTimeoutMultiplier= 1000;

if(!SetCommTimeouts(hSerial, &timeouts)) 
{
printf("error setting port state \n");
}
while(1)
{
//****************Write Operation*********************//
char data_tx[]="at\r";
words=&data_tx[0];
nwrite = strlen(words);
buffWrite = words;
dwBytesWritten = 0;

if (!WriteFile(hSerial, buffWrite, nwrite, &dwBytesWritten, NULL)) 
{ 
printf("error writing to output buffer \n");
}
printf("Data written to write buffer is\n %s \n",buffWrite);


//***************Read Operation******************//
dwBytesRead = 0;
nread = strlen(words);
buffRead = new char[nread +1];
memset(buffRead, 0, nread+1);   // ensure that string will be null-terminated

if (!ReadFile(hSerial, buffRead, nread, &dwBytesRead, NULL)) 
{
printf("error reading from input buffer \n");
}
printf("Data read from read buffer is \n %s \n ",buffRead);
Sleep(10000);
}
CloseHandle(hSerial);

}

当命令“at\r”从计算机传输到 GSM 模块时,它接收到它应该通过发送OK来响应它。

现在我只得到O。如果我再次发送"at\r"我会得到K

我已经在超级终端上验证了它的 GSM 模块工作正常。如果我发送“at”并输入它,它会以OK响应。

此外,我已经在其他程序上验证了我的 C 代码,它工作正常。

我想知道为什么它不能与 GSM 模块一起正常工作。

4

1 回答 1

0

您需要在读取结果之前调用 sleep 。250 毫秒绰绰有余

于 2016-02-01T21:45:25.630 回答