Auto编程语言使用Pcomm库的串口通讯例子

锦州思华年 兄影响,也写了一个串口通讯程序,只是实现了最简单的发送接收功能...

import win;

import string;

 

//加载dll,声明函数

Pcom = raw.loadDll("\Pcomm.dll");

//打开串口,正确返回0;C代码int WINAPI sio_open(int port);

sio_open = Pcom.api("sio_open","int(int port)");

//关闭串口,正确返回0;C代码int WINAPI sio_close(int port);

sio_close = Pcom.api("sio_close","int(int port)" );

//设置串口参数,正确返回0;C代码int WINAPI sio_ioctl(int port, int baud, int mode);

sio_ioctl = Pcom.api("sio_ioctl","int(int port, int baud, int mode)" );

//读取缓冲区数据,返回数据长度,为0表示没有读到数据;C代码int WINAPI sio_read(int port, char *buf, int len);

sio_read = Pcom.api("sio_read","int(int port, pointer buf, int len)");

//写入缓冲区数据,返回数据长度;C代码int WINAPI sio_write(int port, char *buf, int len);

sio_write = Pcom.api("sio_write","int(int port, pointer buf, int len)");

//设置中断函数,用来在接收大量数据的时候产生中断;C代码int WINAPI sio_cnt_irq(int port,VOID (CALLBACK *func)(int port), int count);

sio_cnt_irq = Pcom.api("sio_cnt_irq","int(int port, func(int port), int count)");

 

 

//串口打开函数

comopen = function(port,baud,parity,stopbits,wordlength){

var ret = 0;

var i = 0;

 

ret = sio_open(port);//打开串口

if(ret != 0){

win.msgboxTimeout("错误码:"+ret,"串口打开错误");

return 0;

}

 

ret = sio_ioctl (port, baud, parity| stopbits | wordlength );//设置串口参数:波特率、奇偶校验、停止位、数据位

if(ret != 0){

win.msgboxTimeout("错误码:"+ret,"串口设置错误");

return 0;

}

}

 

// 串口发送数据函数

 

comwrite = function(port,str,buf){

str = string.replace(str,"\s","");//去除空格及换行符

for(i=1;#str;2){

buf[(i+1)/2] = eval("0X"+string.sub(str,i,i+1));

}

var len = sio_write(port,buf,#str/2)

return len;

}

 

 

//串口接收数据函数

 

comread = function(port,buf){

var len = sio_read(port,buf,#buf);

var str = ""

for(i=1;len;1){

str = str++" "++string.right(string.format("%02X", buf[ i ]),2);//默认转换成有符号字节,因此取最右边两位

}

return str,len;

}

 

 

io.open();

var port = 1;

var baud = 0x0c;//波特率9600

/*baud = (bits/sec)

0 = 50 6 = 600 12 = 9600 18 = 460800

1 = 75 7 = 1200 13 = 19200 19 = 921600

2 = 110 8 = 1800 14 = 38400

3 = 134.5 9 = 2400 15 = 57600

4 = 150 10 = 4800 16 = 115200

5 = 300 11 = 7200 17 = 230400

*/

var wordlength = 0x03;//数据位bit_8

/*bit_cnt (bit 0, 1) = 0x00 = bit_5

0x01 = bit_6

0x02 = bit_7

0x03 = bit_8

*/

var parity = 0x18; //奇偶校验EVEN

/*parity (bit 3,4 5) = 0x00 = none

0x08 = odd

0x18 = even

0x28 = mark

0x38 = space

*/

var stopbits = 0x00;//停止位stop_1

/*stop_bit (bit 2) = 0x00 = stop_1

0x04 = stop_2

*/

 

 

comopen(port,baud,parity,stopbits,wordlength);//打开串口并设置串口参数

var cdata = raw.malloc(256); //分配内存

 

io.print("请输入发送指令,然后回车")

var str = io.getText();

len = comwrite(port,str,cdata); //发送

io.print("发送"+len+"字节:"+str);

win.delay(80);

str1, len1 = comread(port,cdata) //接收

io.print("接收"+len1+"字节:"+str1);

win.delay(80);

 

sio_close(port); //关闭串口

 

execute("pause") //按任意键继续

io.close();//关闭控制台