树莓派c语言modbus,树莓派串口利用modbus通信

1、安装

sudo apt-get install libmodbus-dev

2、搭建modbus环境

https://blog.csdn.net/starelegant/article/details/72782946

3、编写测试程序

https://blog.csdn.net/qq_23670601/article/details/82155378#%E5%88%9D%E8%AF%95%E5%8C%96RTU%E7%8E%AF%E5%A2%83%E6%8C%87%E9%92%88%20modbus_t%20*modbus_new_rtu(const%20char%20*device%2C%20int%20baud%2C%20char%20parity%2C%20int%20data_bit%2C%20int%20stop_bit)

#include #include #include int main()

{

modbus_t *mb;

uint16_t tab_reg[32]={0};

mb=modbus_new_rtu("/dev/ttyS0",115200,'N',8,1);

if(0==modbus_rtu_get_serial_mode(mb))

{

modbus_rtu_set_serial_mode(mb,MODBUS_RTU_RS232);

printf("serial is RS232\n");

}

else {

printf("serial is RS485\n");

modbus_rtu_set_serial_mode(mb,MODBUS_RTU_RS485);

}

modbus_set_slave(mb,1);

// modbus_rtu_set_rts(mb,MODBUS_RTU_RTS_UP);

modbus_connect(mb);

int regs=modbus_read_registers(mb,0,8,tab_reg);

printf("%d %d %d %d %d\n",regs,tab_reg[0],tab_reg[1],tab_reg[2],tab_reg[3]);

modbus_close(mb);

modbus_free(mb);

return 0;

}

4、gcc modbus_rtu.c -o modbus_rtu -lmodbus

如果用了wiringPi库,还要加上-lwiringPi

5、测试

树莓派c语言modbus,树莓派串口利用modbus通信_第1张图片

你可能感兴趣的:(树莓派c语言modbus)