GPRS模块的使用&Java串口操作(2)

本文介绍如何在Java中配置串口并操作GPRS模块,包括加载驱动、初始化串口、读写操作。同时,文章讨论了在GPRS模块进行拨号时UDP数据接收的问题及可能的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

续上,GPRS模块的使用&Java串口操作(2)
本章关注  Java串口配置和操作

配置:
  Win32串口编程前期准备 
1,去sun的官方网站下载开发包 javacomm20-win32.zip并解压
2,copy c:\commapi\win32com.dll →c:\jdk1.4.2\bin 
3,copy c:\commapi\javax.comm.properties →  c:\jdk1.1.6\lib 
4,copy c:\commapi\comm.jar →  c:\jdk1.1.6\lib
5, VIP:步骤,例化-导入驱动importDriver()!-初始化
6. 使用完关闭closePort();

这里重点提下,第五步,网上大多忽略此步骤编程时串口可能初始化不成功
public void importDriver() {
//加载驱动
String driverName = "com.sun.comm.Win32Driver";
CommDriver driver = null;
try {
    System.loadLibrary("win32com");
    driver = (CommDriver)Class.forName(driverName).newInstance();
    driver.initialize();
  } catch (InstantiationException e1) {
    e1.printStackTrace();
  } catch (IllegalAccessException e1) {
    e1.printStackTrace();
  } catch (ClassNotFoundException e1) {
    e1.printStackTrace();
  }    
//列出可用串口    
        CommPortIdentifier portId;
        Enumeration en =CommPortIdentifier.getPortIdentifiers();
        // iterate through the ports.
        while (en.hasMoreElements()) {        
            portId =(CommPortIdentifier) en.nextElement();
            if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println(portId.getName());
            }
        }
    }


使用一般过程:
testPort = new SerialBean("COM1");
testPort.importDriver();
if (testPort.initialize()==1){//initialSuccess
  //写串口
testPort.writePort(mesg);
  //读串口
      String  replys =testPort. getPack();

  //关串口
testPort.closePort(); 
}

UDP指令包接收与处理:
假设UDP连接成功,服务器发送控制指令到GPRS模块
指令1:setTextmode——设置GPRS模块为Text模式
指令2:发短信——指令格式: txt-phone-textcontent 

//处理指令1:
//setTextmode——设置GPRS模块为Text模式
if(replyMeg.contains("setTextmode")){
//打电话:ATDXXX;
System.out.println("设置短信为text mode");
System.out.println(replyMeg);
      setAction ="AT+CMGF=1";
testPort.writePort(setAction+"\r");//以“\r”结束输入并发送
waitforRec();//wait for a few seconds
replyMeg =testPort.getPack();
System.out.println(replyMeg);
}
//处理指令2:
//send SMS totarget phone
//指令格式;txt-phone-textcontent 
if(replyMeg.contains("txt")){
String[] msgs =replyMeg.split("-");
if(msgs.length==3){
System.out.println("准备发送短信给"+msgs[1]);
setAction ="AT+CMGS="+yh+msgs[1]+yh;
testPort.writePort(setAction+"\r");//此处仍以回车\r,not回车换行符\r\n
waitforRec();
replyMeg =testPort.getPack();
System.out.println(replyMeg);
//最好加一判断是否成功收到 > 符号
//开始发送 SMSContent
setAction =msgs[2];
testPort.writePort(setAction+cz);//cz为ctrl-Z字符,详见 上一篇
waitforRec();
replyMeg =testPort.getPack();
System.out.println(replyMeg);
}
}

意外发现:

当GPRS模块在进行拨号打电话操作时,UDP数据接收不到。只有当电话挂断后,才能正常接收Server数据!
不知道有木有人遇到过呢?求解决方法~

参考:
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值