dsp modubus ASCII协议rs485串口程序例程
时间: 2023-11-24 20:08:23 浏览: 133
以下是一个简单的DSP Modbus ASCII协议的RS485串口程序例程,供参考:
```c
#include "DSP2833x_Device.h"
#include "DSP2833x_Examples.h"
#define UART_TX_PIN GPIO24
#define UART_RX_PIN GPIO25
#define MAX_DATA_LENGTH 64
Uint16 data[MAX_DATA_LENGTH];
Uint16 dataLength;
void init_RS485(void);
void init_UART(void);
void send_RS485(Uint16 *data, Uint16 length);
void receive_RS485(Uint16 *data, Uint16 *length);
void send_UART(Uint16 data);
void receive_UART(Uint16 *data);
void main(void)
{
init_RS485();
init_UART();
while(1)
{
receive_RS485(data, &dataLength);
// process received data
send_RS485(data, dataLength);
}
}
void init_RS485(void)
{
EALLOW;
GpioCtrlRegs.GPAMUX2.bit.GPIO20 = 0;
GpioCtrlRegs.GPADIR.bit.GPIO20 = 1;
GpioDataRegs.GPACLEAR.bit.GPIO20 = 1; // set to receive mode
GpioCtrlRegs.GPAMUX2.bit.GPIO21 = 0;
GpioCtrlRegs.GPADIR.bit.GPIO21 = 1;
GpioDataRegs.GPACLEAR.bit.GPIO21 = 1; // set to receive mode
EDIS;
}
void init_UART(void)
{
EALLOW;
GpioCtrlRegs.GPAMUX2.bit.GPIO24 = 1;
GpioCtrlRegs.GPADIR.bit.GPIO24 = 1; // set as output
GpioCtrlRegs.GPAMUX2.bit.GPIO25 = 1;
GpioCtrlRegs.GPADIR.bit.GPIO25 = 0; // set as input
SciaRegs.SCICCR.all = 0x0007; // 1 stop bit, No loopback
// No parity,8 char bits,
// async mode, idle-line protocol
SciaRegs.SCICTL1.all = 0x0003; // enable TX, RX, internal SCICLK,
// Disable RX ERR, SLEEP, TXWAKE
SciaRegs.SCICTL2.bit.TXINTENA = 0;
SciaRegs.SCICTL2.bit.RXBKINTENA = 0;
SciaRegs.SCICTL2.bit.TXEMPTY = 1;
SciaRegs.SCIHBAUD = 0x0000;
SciaRegs.SCILBAUD = 0x002E; // baud rate 9600 @ LSPCLK = 150MHz
SciaRegs.SCICTL1.all = 0x0023; // Relinquish SCI from Reset
SciaRegs.SCIFFTX.all = 0xC000;
SciaRegs.SCIFFRX.all = 0x0021;
EDIS;
}
void send_RS485(Uint16 *data, Uint16 length)
{
Uint16 i;
EALLOW;
GpioDataRegs.GPASET.bit.GPIO20 = 1; // set to transmit mode
GpioDataRegs.GPASET.bit.GPIO21 = 1;
DELAY_US(100);
for(i=0; i<length; i++)
{
send_UART(data[i]);
}
SciaRegs.SCIFFTX.bit.TXFFINTCLR = 1;
SciaRegs.SCIFFTX.bit.TXFFINT = 1;
DELAY_US(100);
GpioDataRegs.GPACLEAR.bit.GPIO20 = 1; // set to receive mode
GpioDataRegs.GPACLEAR.bit.GPIO21 = 1;
EDIS;
}
void receive_RS485(Uint16 *data, Uint16 *length)
{
Uint16 i;
EALLOW;
GpioDataRegs.GPASET.bit.GPIO20 = 1; // set to transmit mode
GpioDataRegs.GPACLEAR.bit.GPIO21 = 1;
DELAY_US(100);
GpioDataRegs.GPACLEAR.bit.GPIO20 = 1; // set to receive mode
GpioDataRegs.GPACLEAR.bit.GPIO21 = 1;
DELAY_US(100);
*length = SciaRegs.SCIFFRX.bit.RXFFST;
for(i=0; i<*length; i++)
{
receive_UART(data+i);
}
EDIS;
}
void send_UART(Uint16 data)
{
while(SciaRegs.SCIFFTX.bit.TXFFST != 0) {}
SciaRegs.SCITXBUF = data;
}
void receive_UART(Uint16 *data)
{
while(SciaRegs.SCIRXST.bit.RXRDY == 0) {}
*data = SciaRegs.SCIRXBUF.all;
}
```
需要注意的是,此程序仅供参考,具体实现需要根据实际情况进行调整和修改。同时,还需要根据Modbus ASCII协议的要求进行数据的读写和校验。
阅读全文