❶ 如何用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函数得到的是字符数组的真实长度,不包括后面的'