八个字节,串口LED写入代码。及判断单双字节,动态取字。

代码
//1.打开指定串口
HANDLE hComm = CreateFile("COM1", // 串口名称(COMx)
GENERIC_READ | GENERIC_WRITE, // 串口属性为可读/写
0, // 串口设备必须被独占性的访问
NULL, // 无安全属性
OPEN_EXISTING, // 串口设备必须使用OPEN_EXISTING参数
FILE_ATTRIBUTE_NORMAL, // 同步式 I/O
0); // 对于串口设备而言此参数必须为0
if (hComm == INVALID_HANDLE_VALUE)
{
//如果该串口不存在或者正被另外一个应用程序使用,
//则打开失败,本程序退出
Application->MessageBox("打开串口出错。", "", MB_OK +
MB_ICONINFORMATION);

}
//2.设置串口参数:波特率、数据位、校验位、停止位等信息
DCB dcb;
GetCommState(hComm,
&dcb); //获取该端口的默认参数
//修改波特率
dcb.BaudRate = 4800;
//重新设置参数
// dcb.StopBits = 1;
dcb.ByteSize = 8;
SetCommState(hComm,
&dcb);
//3.往串口写数据

string text = Edit1->Text.c_str() ; //将要写入的数据
DWORD len = text.length();
string midText="";

char lpBase[16] ; //将要写入的基本数据
int dmod=0;
dmod
= Ceil((double)len/(double)8);
char lpBuffer[8] = ""; //将要写入的数据
DWORD nNumberOfBytesToWrite; //将要写入的数据长度
DWORD nBytesSent; //实际写入的数据长度
int i=1;
int pos=0,poe=8,poall=0;
// while (i<=dmod){
while (poall<len){

lpBase[
0]='\0';
lpBase[
0]=0X05;
lpBase[
1]=0X00;
lpBase[
2]=0X00;
lpBase[
3]=0X01;
lpBase[
4]=0X00;
lpBase[
5]=0X00;
lpBase[
6]=0X00;
lpBase[
7]=0X00+i-1;
lpBase[
8]=0X00;
lpBase[
9]=0X01;
lpBase[
10]=0X00;
lpBase[
11]=0X01;
lpBase[
12]=0X10;
lpBase[
13]=0X00;
lpBase[
14]=0X00;
lpBase[
15]=0X00;
WriteFile(hComm,lpBase,
16,&nBytesSent, NULL);
// if (poe==0) {
// poe = 8;
// }
midText = text.substr(pos,8);
poe
= substr2(midText,midText.length());
poall
= poall+poe;
midText
= text.substr(pos,poe);
pos
= poall;

char *buf = new char[8];
memset(buf,
0,8);
strcpy(buf,midText.c_str());
WriteFile(hComm, buf,
8, &nBytesSent, NULL);
delete [] buf; buf
= NULL;
i
++;
}

//写入结束符
char lpBufferEnd[16] ; //将要写入的数据

lpBufferEnd[
0]=0X05;
lpBufferEnd[
1]=0X00;
lpBufferEnd[
2]=0X00;
lpBufferEnd[
3]=0X01;
lpBufferEnd[
4]=0X00;
lpBufferEnd[
5]=0X00;
lpBufferEnd[
6]=0X00;
lpBufferEnd[
7]=0X00+dmod;
lpBufferEnd[
8]=0XFF;
lpBufferEnd[
9]=0XFF;
lpBufferEnd[
10]=0XFF;
lpBufferEnd[
11]=0XFF;
lpBufferEnd[
12]=0XFF;
lpBufferEnd[
13]=0XFF;
lpBufferEnd[
14]=0XFF;
lpBufferEnd[
15]=0XFF;
WriteFile(hComm,lpBufferEnd,
16,&nBytesSent, NULL);
//4.关闭串口
CloseHandle(hComm);

 

代码
//---------------------------------------------------------------------------

int __fastcall TForm1:: substr2(string str, int len)
{
if (len<8) {
return len;
}
char a[8];
str.copy(a,len,
0);
int big=0;
for (int i=0; i < 8; i++) {
if (int(a[i])>0) {
big
++;
}
}
if (big %2 ==0) {
return 8;
}
return 7;
}

 

posted on 2010-03-17 08:30  yxh  阅读(458)  评论(0)    收藏  举报