javascript 操作MSCOMM32串口通信

javascript直接操作MSCOMM32发数据只能发0到127,128到255不能发。所以要自己写一个activeX控件来进行数据转换

VB6

activeX源代码

'把A1010D十六进制转成字符发给javascirpt

PublicFunctionreceivedata(ssr)

Dimleng

Dimbb()AsByte

bb=ssr

'leng=Len(bb)

Fori=LBound(bb)ToUBound(bb)

tmpHex=Hex(bb(i))

RtnStr=RtnStr&IIf(bb(i)<&H10,"0"&tmpHex,tmpHex)&""

Next

receivedata=RtnStr

EndFunction

'把A1010D转成字节数组发给mscomm

PublicFunctionsenddata(ss)

Dimarr()AsByte

Dims,i,leng

leng=Len(ss)\3

s=Split(ss,"")

ReDimarr(leng)AsByte

Fori=0Toleng

arr(i)=Val("&H"&s(i))

Nexti

senddata=arr

EndFunction

<!--

html

-->

<html>

<head>

<title>JavaScriptMSCOMM32.OCX</title>

<SCRIPTID=clientEventHandlersJSLANGUAGE=javascript>

//重写mscomm控件的唯一事件处理代码

functioncomm_OnComm()

{

varlen=0;

if(comm.CommEvent==1)//如果是发送事件

{

window.alert("发送成功");//这句正常,说明发送成功了

}

elseif(comm.CommEvent==2)//如果是接收事件

{

varleng=comm.InBufferCount;

varinstr=cnv.receivedata(comm.Input);

document.form1.txtReceive.value=document.form1.txtReceive.value+instr;

}

}

</SCRIPT>

<SCRIPTLANGUAGE=javascriptFOR=commEVENT=OnComm>

//comm控件每遇到OnComm事件就调用comm_OnComm()函数

comm_OnComm()

</SCRIPT>

<scriptlanguage="JavaScript"type="text/JavaScript">

//打开端口并发送命令程序

functionOpenPort()

{

if(comm.PortOpen==false)

{

try{

comm.PortOpen=true;

varsendstr=document.form1.txtsend.value;

comm.Output=cnv.senddata(sendstr);//发送命令

}catch(e){

alert(e);

}

window.alert("成功发出命令!");

}

else

{

varsendstr=document.form1.txtsend.value;

comm.Output=cnv.senddata(sendstr);//发送命令

}

}

</script>

</head>

<OBJECTCLASSid="clsid:5220cb21-c88d-11cf-b347-00aa00a28331">

<PARAMname="LPKPath"VALUE="LPKfilename.LPK">

</OBJECT>

<OBJECTid="cnv"

CLASSid="CLSID:6AE2FA6C-7428-4BBC-A80E-8F3F5AF8517A"

CODEBASE="mycnv.CAB#version=1,0,0,0">

<paramname="_ExtentX"value="8467">

<paramname="_ExtentY"value="6350">

</OBJECT>

<objectCLASSid="clsid:648A5600-2C6E-101B-82B6-000000000014"id="comm"codebase="MSCOMM32.OCX"type="application/x-oleobject"style="LEFT:54px;TOP:14px">

<paramname="CommPort"VALUE="8">

<paramname="DTREnable"VALUE="1">

<paramname="Handshaking"VALUE="0">

<paramname="InBufferSize"VALUE="1024">

<paramname="InputLen"VALUE="0">

<paramname="NullDiscard"VALUE="0">

<paramname="OutBufferSize"VALUE="512">

<paramname="ParityReplace"VALUE="?">

<paramname="RThreshold"VALUE="1">

<paramname="RTSEnable"VALUE="1">

<paramname="SThreshold"VALUE="2">

<paramname="EOFEnable"VALUE="0">

<paramname="InputMode"VALUE="1">

<paramname="DataBits"VALUE="8">

<paramname="StopBits"VALUE="1">

<paramname="BaudRate"VALUE="9600">

<paramname="Settings"VALUE="9600,N,8,1">

</OBJECT>

<body>

<formname="form1">

<inputtype="button"name="Submit"value="提交"onClick="OpenPort()">

<inputtype="text"name="txtsend"value=""size="53">

<p>&nbsp;

<textareaname="txtReceive"value=""rows="19"cols="58"></textarea>

</p>

</form>

</body>

</html>

相关推荐