我正在做一个有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来响应。
现在我只得到0。如果我再次发送“at\r”,我得到K。
我已经在超级终端GSM模块上验证了它是否正常工作。如果我发送“at”并输入,它将以“OK”响应。
另外,我已经在其他程序上验证了我的C代码,它工作正常。
我想知道为什么它不能与GSM模块正常工作。

最佳答案

你需要在阅读结果前打电话睡觉。250毫秒就足够了

07-24 09:55