下面是我的串口接收程序的一部分:
Select Case MSComm1.CommEvent'事件发生
Case 2
inbuff = MSComm1.Input '读入到缓冲区
ll = UBound(inbuff)
Label10.Caption = Label10.Caption + UBound(inbuff) + 1
ReDim indata(1 To (ll + 1))
For ii = 0 To UBound(inbuff)
strHex = strHex &Right("0" &Hex(inbuff(ii)), 2) &" " '如果只有一个字符,则前补0, 如F显示0F,最后补空格方便显示观察如: 00 0F FE
TextReceive = strHex ‘显示到 文本框
Next ii
Open "12.txt" For Append As #1 ‘打开 文本文件
m = (ll + 1) / 2
Print #1, Now"收到"m"个数据"
Close #1
For ii = 1 To Len(strHex) Step 6
indata((ii + 5) / 6) = Val("&H" &Mid(strHex, ii, 2)) * 4 + Val("&H" &Mid(strHex, ii + 3, 2))
Next ii
n1 = Val(Text1.Text) '电源电压
n2 = Val(Text2.Text) '第一路电压衰减倍数
n3 = Val(Text3.Text) '第二路电压衰减倍数
na = n1 * n2 / 1024
nb = n1 * n3 / 1024
X = (ll + 1) / 2 - 1
For ii = 1 To X Step 2 '存入文本中,每行两个数据
V1 = indata(ii) * na
V2 = indata(ii + 1) * nb
V3 = Format(V1, "0.000")
V4 = Format(V2, "0.000")
Open "12.txt" For Append As #1
Print #1, ii &"电压 " &V3 &" v " &(ii + 1) &"电压 " &V4 &" v"
Close #1
Next
'写入EXCEL表格中
Set xlsApp = New Excel.Application
Set xlsBook = xlsApp.Workbooks.Open(App.Path &"\Book3.xls")
Set xlsSheet = xlsBook.Worksheets(1)
range = 2 '第二列为起始列,但每次写入时,range并不一定是2,而是在原有基础上另起1列
'第一列,写入奇数数据
Do Until xlsSheet.Cells(2, range) = ""
range = range + 1
Loop
xlsSheet.Cells(1, range) = Date '第1行
xlsSheet.Cells(2, range) = Time '第2行
xlsSheet.Cells(3, range) = "回路1电压(V)" '第3 行
For ii = 1 To X Step 2 '从第4行开始存数据
V1 = indata(ii) * na
V3 = Format(V1, "0.000")
xlsSheet.Cells((ii + 1) / 2 + 3, range) = V3 '第4行
Next ii
'另起一列,写入偶数数据
Do Until xlsSheet.Cells(2, range) = ""
range = range + 1
Loop
xlsSheet.Cells(2, range) = Time '第2行
xlsSheet.Cells(3, range) = "回路2电压(V)" '第3行
For ii = 2 To X + 1 Step 2 '从第4行开始存数据
V2 = indata(ii) * nb
V4 = Format(V2, "0.000")
xlsSheet.Cells(ii / 2 + 3, range) = V4
Next ii
xlsBook.Save
xlsBook.Application.Quit
strHex = "" '处理完成后清空字符串,等待下一次接收
'TextReceive = ""
End Select
你通过串口助手要接受字符串或一组数据需要在单片机端开辟一个缓冲区,否则可能丢失数据。以下程序是较为通用的串口收发例程,开辟一个16字节的缓冲区,两个指针,一个存数指针,一个取数指针,两指针相等,证明没有新的接收数据。
#include<reg51.h>
#define uchar unsigned char
uchar buf[16],getptr,putptr
void uart_isr() interrupt 4
{
if(RI)
{
RI=0
buf[putptr]=SBUF
putptr++
putptr&=0x0f
}
}
main()
{
TMOD=0x20
SCON=0x50
TH1=TL1=0xfd
TR1=1
ES=1
EA=1
putptr=0
getptr=0
while(1)
{
if(getptr!=putptr)//取数指针和存数指针如果不等
{
SBUF=buf[getptr]
getptr++
getptr&=0x0f
while(!TI)
TI=0
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)