问题
I am having issues writing AT commands to a GSM module. It works flawless when i use minicom -b 115200 -D /dev/ttySP0 --term=vt100 But i cant figure out how to do the same thing in C code. I do not receive any errors, but the module does no react to the commands. Anyone know what could be wrong?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#define BAUDRATE B115200
#define COM1 "/dev/ttySP0"
static int fd;
static struct termios oldtio,newtio;
//==============================================================
int tty_read(char *buf,int nbytes)
{
int temp;
temp = read(fd,buf,nbytes);
printf("Read string: %s\n", buf);
return temp;
}
//==============================================================
int tty_end()
{
tcsetattr(fd,TCSANOW,&oldtio);
close(fd);
}
//==============================================================
int tty_writecmd(char *buf,int nbytes)
{
int i;
for(i=0; i<nbytes; i++) {
write(fd,&buf[i],1);
usleep(100);
}
write(fd,"\n",1); //Tried \0 \r aswell
usleep(300000);
return tcdrain(fd);
}
//==============================================================
int baud = B115200;
int tty_init()
{
fd = open(COM1, O_RDWR );
if (fd <0) {
perror(COM1);
exit(1);
}
tcgetattr(fd,&oldtio);
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = baud | CRTSCTS | CS8 | CLOCAL | CREAD ;
newtio.c_iflag = IGNPAR | ICRNL;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;
newtio.c_cc[VINTR] = 0;
newtio.c_cc[VQUIT] = 0;
newtio.c_cc[VERASE] = 0;
newtio.c_cc[VKILL] = 0;
newtio.c_cc[VEOF] = 4;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 1;
newtio.c_cc[VSWTC] = 0;
newtio.c_cc[VSTART] = 0;
newtio.c_cc[VSTOP] = 0;
newtio.c_cc[VSUSP] = 0;
newtio.c_cc[VEOL] = 0;
newtio.c_cc[VREPRINT] = 0;
newtio.c_cc[VDISCARD] = 0;
newtio.c_cc[VWERASE] = 0;
newtio.c_cc[VLNEXT] = 0;
newtio.c_cc[VEOL2] = 0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
return 0;
}
int main(int argc, char *argv[])
{
char recv[10];
char command[] = "AT+CSQ";
tty_init();
printf("Write: %d\n", tty_writecmd(command, sizeof(command)));
usleep(40000);
printf("Read: %d\n", tty_read(recv ,sizeof(recv)));
tty_end();
}
回答1:
The first thing you should do is to run
stty -F /dev/ttySP0
Do this while minicom is running and while your program is running. Check everything and compare. There are lots of things that can cause you issues.
Once you have those matching, you want to make sure the data you send is going out.
cat /proc/tty/driver/serial
Compare the tx value before and after you send data to make sure it is going out.
If it is, then you can check the rx value. If you get no response, you are probably going to need an oscilloscope to inspect the data on the lines. If you can't do this, then triple check the baud rate and flow control.
来源:https://stackoverflow.com/questions/15430023/writing-at-commands-embedded-linux