打开一个bin文件,读取里面的内容,然后将内容按照每组256个字节进行分组,
byte[] buf = new byte[];发送第一组256个字节内容,前面加上FF B5 最终变成
FF B5 +256 总共258个内容进行发送,然后等待收到回复确认(可以用timer控件),
开始发送第二组数据FF B6 +256字节 总共258个发送出去。然后等待收到回复确认,开始发送第三组内容 FF B5 +256,收到回复,再发送FF B6 +256字节,收到回复,以此下去,直到发完所有字节。
class Program
{
static void Main(string[] args)
{
SerialPort com = new SerialPort() { BaudRate = 115200, PortName = "COM1", DataBits = 8 };
com.DataReceived += Com_DataReceived;
com.Open();
//读取二进制文件
FileStream binStream = File.OpenRead("filepath");
//发送buffer
byte[] buffer = new byte[258];
buffer[0] = 0XFF;
buffer[1] = 0XB5;
SetLock(true);
//读数据到发送buffer中
while (binStream.Read(buffer, 2, 256) != 0)
{
//等待回复
while (!GetStatus())
{
Thread.Sleep(10);
}
//发送
com.Write(buffer, 0, buffer.Length);
SetLock(false);
}
}
static bool cansend = true;
static object sendLock = new object();
static void SetLock(bool status)
{
lock(sendLock)
{
cansend = status;
}
}
static bool GetStatus()
{
bool status = false;
lock (sendLock)
{
status = cansend;
}
return status;
}
private static void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//接收回复
SetLock(true);
}
未测试,不清楚能否跑通
#include
int main()
{
FILE *fp;
char buf[258];
char *p=buf+2;
fp = fopen("in.dat", "rb");
while(fread(p, 256,1,fp)>0)
{
buf[0]=xxx;
buf[1]=xxx;//这里加你自定义内容
sendtoserial(buf,258);//根据你平台, 写串口
}
fclose(fp);
}