❶ 如何用AT命令發送簡訊
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<termios.h>
#include<errno.h>
#include<iconv.h>//編碼轉換
#defineSTTY_DEV"/dev/ttyS0"
#defineBUFF_SIZE512
#defineMSG_SIZE140//一條簡訊的容量
charphone[20]="+8613476090094";//定義簡訊發送的目標手機號碼
charsms_number[20]="+8613800200500";//定義短消息服務中心號碼
charsms_gb2312[MSG_SIZE]="BestRegards!";//定義短消息內容
charsms_utf8[MSG_SIZE];
char*sms_in=sms_gb2312;//要把輸入的gb2312編碼轉換成unicode編碼
char*sms_out=sms_utf8;
intgb2312_len,utf8_len;
intSetOption(intfd);//設置串口通信的參數
voidTransPhone();//轉換手機號碼格式
voidTransSmsc();//轉換SMSC號碼
intTransMsg();//轉換簡訊消息內容
intmain()
{
intstty_fd,n;
charbuffer[BUFF_SIZE];
//打開串口
stty_fd=open(STTY_DEV,O_RDWR);
if(-1==stty_fd){
perror("opendevice");
return0;
}
printf("Opendevicesuccess! ");
//設置串口參數
if(0!=SetOption(stty_fd)){
close(stty_fd);
return0;
}
printf("SetSerialoptionsuccess! ");
TransPhone();
TransSmsc();
if(1!=TransMsg()){
perror("ConvertShortMsg");
close(stty_fd);
return0;
}
printf("Messageconvertsuccess! ");
//設置使用PDU模式
strcpy(buffer,"AT+CMGF=0 ");//0表示PDU模式,1表示文本模式
write(stty_fd,buffer,strlen(buffer));//寫入配置命令
n=read(stty_fd,buffer,BUFF_SIZE);//向串口寫入AT+CMGF=0後,如果系統支持PDU模式,返迴向串口返回「OK"
if(n<=0){
perror("setpmode");
close(stty_fd);
return0;
}
if(0!=strncmp(buffer,"OK",2)){
perror("setpmode");
close(stty_fd);
return0;
}
//發送消息
sprintf(buffer,"AT+CMGS=%d ",utf8_len);//寫入發送消息命令
write(stty_fd,buffer,strlen(buffer));
write(stty_fd,sms_utf8,utf8_len);//寫入消息內容
printf("SendmessageOK! ");
close(stty_fd);
}
intSetOption(intfd)
{
structtermiosopt;
//獲取當前串口配置
tcgetattr(fd,&opt);
tcflush(fd,TCIOFLUSH);
//設置波特率
cfsetispeed(&opt,B19200);
cfsetospeed(&opt,B19200);
//設置數據位--8位數據位
opt.c_cflag&=~CSIZE;
opt.c_cflag|=CS8;
//設置奇偶位--無奇偶校驗
opt.c_cflag&=~PARENB;
opt.c_iflag&=~INPCK;
//設置停止位--1位停止位
opt.c_cflag&=~CSTOPB;
//設置超時時間--15秒
opt.c_cc[VTIME]=150;
opt.c_cc[VMIN]=0;
//設置寫入設備
if(0!=tcsetattr(fd,TCSANOW,&opt)){
perror("setbaudrate");
return-1;
}
tcflush(fd,TCIOFLUSH);
return0;
}
voidTransPhone()
{
inti,str_len,tmp;
if(phone[0]='+'){//去掉號碼開頭的『+』
for(i=0;i<strlen(phone)-1;i++)//strlen函數得到的是字元數組的真實長度,不包括後面的'