📄 pc_rs232.c
字号:
volatile unsigned char tx_buffer[TX_BUFFER_SIZE];//定义串口发送缓冲区
volatile unsigned char tx_wr_index=0,tx_rd_index=0,tx_counter=0;//rx_wr_index写指针,rx_rd_index读指针,rx_counter缓冲区数据个数
//USART发送函数
void USART_Transmit(unsigned char data)//发送数据函数
{
while(tx_counter==TX_BUFFER_SIZE);//输出缓冲区满,等待
asm("cli");
if(tx_counter||((UCSRA & DATA_REGISTER_EMPTY)==0))
{
tx_buffer[tx_wr_index]=data;
if(++tx_wr_index==TX_BUFFER_SIZE)
tx_wr_index=0;
++tx_counter;
}
else
UDR = data;
asm("sei");
}
//发送中断服务程序
ISR(USART_TXC_vect)//USART发送数据中断
{
if(tx_counter)
{
--tx_counter;
UDR=tx_buffer[tx_rd_index];
if(++tx_rd_index==TX_BUFFER_SIZE)
{
tx_rd_index=0;
}
}
}
在C#编写的上位机中,利用串口接收事件响应方法定义
serialPort1.ReceivedBytesThreshold = RECEIVE_LENTH;
在时间响应事件中调用协议分析处理函数serialPortCaculate()来分析协议
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.label_dispzedNum.Invoke(new MethodInvoker(delegate
{ //匿名方法
int inNumSData=0;
try
{
inNumSData = this.serialPort1.BytesToRead;
this.lab_serial_bufin_diplay.Text = inNumSData.ToString();
//串行数据处理
//图像显示
byte dataID = 0x00;
double temp = this.serialPortCaculate(ref dataID);
switch(dataID)
{
case TEMVAL:
break;
default:
this.serialPort1.DiscardInBuffer
()
break;
}
}
catch
{ }
}));
}
///////接收转换协议,接收数据时直接调用
private double serialPortCaculate(ref byte dataID)
{
Byte[] BReceiveTemp = new Byte[RECEIVE_LENTH];
for (int i = 0; i < RECEIVE_LENTH; i++)//接收定长数据字符串
{
BReceiveTemp[i] = Convert.ToByte(this.serialPort1.ReadByte());
}
dataID=BReceiveTemp[1];
switch (BReceiveTemp[1])
{
case TEMVAL:
default :
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -