c#界面 libmodbus封装使用实例(update)

在libmodbus基础上增加封装读取配置文件ini的功能(未能按照section待完善),增加三轴控制功能,包括复位、步进调试等,功能已经完成,界面如下:

c#界面 libmodbus封装使用实例(update)_第1张图片

记录关键代码如下:



c语言底层库 rotControl.c , rotControl.h

void readIni()
{
	m_platform_setup.comIndex = (short)getValue("Serial");
	/*m_platform_setup.comIndex = hw_config->value("/COM/COM").toInt();  //QT移植
	m_platform_setup.Axis1_PulsePerRoll = hw_config->value("/AXIS1/PulsePerRoll").toInt();
	m_platform_setup.Axis1_Ratio = hw_config->value("/AXIS1/Ratio").toInt();
	m_platform_setup.Axis1_RangeMax = hw_config->value("/AXIS1/RangeMax").toInt();
	m_platform_setup.Axis1_RangeMin = hw_config->value("/AXIS1/RangeMin").toInt();

	m_platform_setup.Axis2_PulsePerRoll = hw_config->value("/AXIS2/PulsePerRoll").toInt();
	m_platform_setup.Axis2_Ratio = hw_config->value("/AXIS2/Ratio").toInt();
	m_platform_setup.Axis2_RangeMax = hw_config->value("/AXIS2/RangeMax").toInt();
	m_platform_setup.Axis2_RangeMin = hw_config->value("/AXIS2/RangeMin").toInt();

	m_platform_setup.Axis3_PulsePerRoll = hw_config->value("/AXIS3/PulsePerRoll").toInt();
	m_platform_setup.Axis3_Ratio = hw_config->value("/AXIS3/Ratio").toInt();
	m_platform_setup.Axis3_RangeMax = hw_config->value("/AXIS3/RangeMax").toInt();
	m_platform_setup.Axis3_RangeMin = hw_config->value("/AXIS3/RangeMin").toInt();*/
}

void paraInit()
{
	b_stop = false;
	b_isInitial = false;
	m_ctx = NULL;	

	readIni();
}

/*https://www.cnblogs.com/lvdongjie/p/4553815.html*/
void usleep(ULONG ulMicroSeconds)
{
	LARGE_INTEGER varFrequency = { 0 }, varCounter_Start = { 0 }, varCounter_End = { 0 };
	LONGLONG llCount = 0;

	QueryPerformanceFrequency(&varFrequency);
	QueryPerformanceCounter(&varCounter_Start);

	while (true)
	{
		QueryPerformanceCounter(&varCounter_End);

		llCount = varCounter_End.QuadPart - varCounter_Start.QuadPart;

		if (1000000 * llCount > ulMicroSeconds*varFrequency.QuadPart)
		{
			break;
		}
	}
}

int rot_plat_home(int id, int vel)
{
	if (!b_isInitial) {
		return -1;
	}
	int ret = 0;
	if (id == Rot_Axis_1) {
		ret = modbus_write_bit(m_ctx, Emgency, OFF);
		ret = modbus_write_bit(m_ctx, CylinderEnable, OFF);
		ret = modbus_write_bit(m_ctx, CylinderRotateSwitch, OFF);

		ret = modbus_write_bit(m_ctx, AlarmClear_1, ON);
		ret = modbus_write_bit(m_ctx, AlarmClear_1, OFF);
		ret = modbus_write_bit(m_ctx, AlarmClear_1, ON);

		ret = modbus_write_bit(m_ctx, ResetVel_1, ON); 

		if (ret == -1) {
		return -1;
		}

		int overtime = 20;
		int i=0;
		do
		{
			ret=modbus_read_bits(m_ctx, ResetStatus, 1, m_buf_8);
			Sleep(1000);
			i++;
		} while ((m_buf_8[0] == 0)&&(i= overtime)
		{
			i = 0;
			return -2;
		}

		return ret;		
	}
	else if (id == Rot_Axis_2)
	{
		ret = modbus_write_bit(m_ctx, AlarmClear_2, ON);
		ret = modbus_write_bit(m_ctx, AlarmClear_2, OFF);
		ret = modbus_write_bit(m_ctx, AlarmClear_2, ON);
		ret = modbus_write_bit(m_ctx, ResetVel_2, ON);
		if (ret == -1) {
			return -1;
		}
	}
	else if (id == Rot_Axis_3) {
		ret = modbus_write_bit(m_ctx, CylinderEnable, ON);
		usleep(50);
		ret = modbus_write_bit(m_ctx, CylinderRotateSwitch, OFF);//气缸

		int overtime = 10;
		int i = 0;
		do
		{
			ret = modbus_read_bits(m_ctx, Cylinder0Status, 1, m_buf_8);
			Sleep(1000);
		} while ((m_buf_8[0] == 0) && (i++= overtime)
		{
			i = 0;
			return i;
		}

		/*int cnt = 0; revised 20180421
		while ((0 != modbus_read_bits(m_ctx, Cylinder0Status, 1, m_buf_8)) && cnt++ < 30)
		{
		}
		if (cnt >= 30) {
			return -1;
		}
		else
		{
			return (cnt < 30);
		}*/
	}
	//else if (id == Rot_Axis_All)
	//{

	//}

	return ret;
}
int rot_plat_moveto(int id, int pos, int vel, int acc)
{
	int ret = 0;
	if (!b_isInitial) {
		return -1;
	}
	if (id == Rot_Axis_1) {
		ret = modbus_write_bit(m_ctx, MoveAbsMode, ON);
		ret = modbus_write_bit(m_ctx, MoveStepMode, OFF);
		uint16_t ang[2];
		ang[0] = (uint16_t)(pos);
		ang[1] = (uint16_t)(pos >> 16);
		ret = modbus_write_registers(m_ctx, ObjAngles_1, 2, ang);

		modbus_read_registers(m_ctx, ObjAngles_1, 2, m_buf_16);

		if (m_buf_16[0] != ang[0] || m_buf_16[1] != ang[1]) {
			ret = -1;
		}

		uint16_t ve[2];
		ve[0] = (uint16_t)(vel);
		ve[1] = (uint16_t)(vel >> 16);
		ret = modbus_write_registers(m_ctx, ObjVel_1, 2, ve);
		modbus_read_registers(m_ctx, ObjVel_1, 2, m_buf_16);
		if (m_buf_16[0] != ve[0] || m_buf_16[1] != ve[1]) {
			ret = -1;
		}

		if (ret == -1) {
			return -1;
		}
		if (acc != 0) {
			modbus_write_register(m_ctx, AccTime_1, (uint16_t)acc);
			ret = modbus_write_bit(m_ctx, AccUpdate, ON);
			ret = modbus_write_bit(m_ctx, AccUpdate, OFF);
		}
		ret = modbus_write_bit(m_ctx, MoveSwitch_1, ON);
		int cnt = 0;
		// 		while ((0!=modbus_read_bits(m_ctx, Busy_1, 1, m_buf_8)) && cnt++ < 50)
		// 		{
		// 		}
		do
		{
			Sleep(20);
			modbus_read_bits(m_ctx, Busy_1, 1, m_buf_8);

		} while (m_buf_8[0] != 0 && cnt++<50);

		if (cnt >= 50)
			return cnt;

		ret = modbus_write_bit(m_ctx, MoveSwitch_1, OFF);
		cnt = 0;
		do
		{
			modbus_read_bits(m_ctx, Arrived_1, 1, m_buf_8);
		} while (m_buf_8[0] == 0 && cnt++<50);

		if (cnt >= 50)
			return cnt;
		// 		while (m_buf_8[0]==0 && cnt++ < 100)
		// 		{
		// 			modbus_read_bits(m_ctx, Arrived_1, 1, m_buf_8);
		// 			//usleep(100);
		// 		}

	}
	else if (id == Rot_Axis_2) {
		ret = modbus_write_bit(m_ctx, MoveAbsMode, ON);
		ret = modbus_write_bit(m_ctx, MoveStepMode, OFF);
		uint16_t ang[2];
		ang[0] = (uint16_t)(pos);
		ang[1] = (uint16_t)(pos >> 16);
		ret = modbus_write_registers(m_ctx, ObjAngles_2, 2, ang);
		uint16_t ve[2];
		ve[0] = (uint16_t)(vel);
		ve[1] = (uint16_t)(vel >> 16);
		ret = modbus_write_registers(m_ctx, ObjVel_2, 2, ve);
		if (ret == -1) {
			return -1;
		}
		if (acc != 0) {
			modbus_write_register(m_ctx, AccTime_2, (uint16_t)acc);
			ret = modbus_write_bit(m_ctx, AccUpdate, ON);
			ret = modbus_write_bit(m_ctx, AccUpdate, OFF);
		}
		ret = modbus_write_bit(m_ctx, MoveSwitch_2, ON);
		int cnt = 0;
		do
		{
			Sleep(20);
			modbus_read_bits(m_ctx, Busy_2, 1, m_buf_8);
		} while (m_buf_8[0] != 0 && cnt++<50);

		if (cnt >= 50)
			return cnt;
		// 		while ((0 != modbus_read_bits(m_ctx, Busy_2, 1, m_buf_8)))
		// 		{
		// 		}
		ret = modbus_write_bit(m_ctx, MoveSwitch_2, OFF);
		cnt = 0;
		do
		{
			modbus_read_bits(m_ctx, Arrived_2, 1, m_buf_8);
		} while ((m_buf_8[0] == 0) && (cnt++<50));

		// 		while ((0 != modbus_read_bits(m_ctx, Arrived_2, 1, m_buf_8)) && cnt++ < 100)
		// 		{
		// 			usleep(100);
		// 		}

		if (cnt >= 50)
			return cnt;
	}
	else if (id == Rot_Axis_3) {
		if (pos > 0) {
			ret = modbus_write_bit(m_ctx, CylinderEnable, ON);
			ret = modbus_write_bit(m_ctx, CylinderRotateSwitch, ON);

			if (ret == -1) {
				return -1;
			}

			int cnt = 0;

			do
			{
				modbus_read_bits(m_ctx, Cylinder90Status, 1, m_buf_8);
				//usleep(1);
			} while ((m_buf_8[0] == 0) && (cnt++<50));

			if (cnt >= 50)
				return cnt;
			/*do
			{
				modbus_read_bits(m_ctx, Cylinder90Status, 1, m_buf_8);
			} while (m_buf_8[0] == 0);*/

			// 			while ((0 != modbus_read_bits(m_ctx, Cylinder90Status, 1, m_buf_8)) && cnt++ < 30)
			// 			{
			// 			}
			// 			if (cnt >= 30) {
			// 				return -1;
			// 			}
			// 			else
			// 			{
			// 				return (cnt < 30);
			// 			}
		}
		else
		{
			ret = modbus_write_bit(m_ctx, CylinderEnable, ON);
			ret = modbus_write_bit(m_ctx, CylinderRotateSwitch, OFF);

			if (ret == -1) {
				return -1;
			}
			int cnt = 0;

			do
			{
				modbus_read_bits(m_ctx, Cylinder0Status, 1, m_buf_8);
			} while ((m_buf_8[0] == 0) && (cnt++<50));

			if (cnt >= 50)
				return cnt;
			// 			int cnt = 0;
			// 			while ((0 != modbus_read_bits(m_ctx, Cylinder90Status, 1, m_buf_8)) && cnt++ < 30)
			// 			{
			// 			}
			// 			if (cnt >=30) {
			// 				return -1;
			// 			}
			// 			else
			// 			{
			// 				return (cnt < 30);
			// 			}
		}

	}

	return ret;
}
int rot_plat_step(int id, int step, int vel, int acc)
{
	int ret = 0;
	if (!b_isInitial) {
		return -1;
	}
	if (id == Rot_Axis_1) {
		//ret = modbus_write_bit(m_ctx, MoveAbsMode, ON);
		// = modbus_write_bit(m_ctx, MoveStepMode, OFF);
		ret = modbus_write_bit(m_ctx, MoveAbsMode, OFF);
		ret = modbus_write_bit(m_ctx, MoveStepMode, ON);
		uint16_t ang[2];
		ang[0] = (uint16_t)(step);
		ang[1] = (uint16_t)(step >> 16);
		ret = modbus_write_registers(m_ctx, ObjAngles_1, 2, ang);
		uint16_t ve[2];
		ve[0] = (uint16_t)(vel);
		ve[1] = (uint16_t)(vel >> 16);
		ret = modbus_write_registers(m_ctx, ObjVel_1, 2, ve);
		if (ret == -1) {
			return -1;
		}
		ret = modbus_write_bit(m_ctx, MoveSwitch_1, ON);
		int cnt = 0;
		do
		{
			modbus_read_bits(m_ctx, Busy_1, 1, m_buf_8);
			Sleep(20);
		} while (m_buf_8[0] != 0 && cnt++<50);

		if (cnt >= 50)
			return cnt;

		/*while ((0 != modbus_read_bits(m_ctx, Busy_1, 1, m_buf_8)) && cnt++ < 50)
		{
		}*/
		ret = modbus_write_bit(m_ctx, MoveSwitch_1, OFF);
		cnt = 0;
		/*while ((0 != modbus_read_bits(m_ctx, Arrived_1, 1, m_buf_8)) && cnt++ < 100)
		{
			usleep(100);
		}*/
		do
		{
			modbus_read_bits(m_ctx, Arrived_1, 1, m_buf_8);
			usleep(100);
		} while (m_buf_8[0] == 0 && cnt++<100);

		if (cnt >= 50)
			return cnt;

		//ret = (cnt < 100);
	}
	else if (id == Rot_Axis_2) {
		ret = modbus_write_bit(m_ctx, MoveAbsMode, OFF);
		ret = modbus_write_bit(m_ctx, MoveStepMode, ON);
		uint16_t ang[2];
		ang[0] = (uint16_t)(step);
		ang[1] = (uint16_t)(step >> 16);
		ret = modbus_write_registers(m_ctx, ObjAngles_2, 2, ang);
		uint16_t ve[2];
		ve[0] = (uint16_t)(vel);
		ve[1] = (uint16_t)(vel >> 16);
		ret = modbus_write_registers(m_ctx, ObjVel_2, 2, ve);
		if (ret == -1) {
			return -1;
		}
		ret = modbus_write_bit(m_ctx, MoveSwitch_2, ON);
		int cnt = 0;
		do
		{
			modbus_read_bits(m_ctx, Busy_2, 1, m_buf_8);
			Sleep(50);
		} while (m_buf_8[0] != 0 && cnt++<50);

		if (cnt >= 50)
			return cnt;
		/*while ((0 != modbus_read_bits(m_ctx, Busy_2, 1, m_buf_8)) && cnt++ < 50)
		{
		}*/
		ret = modbus_write_bit(m_ctx, MoveSwitch_2, OFF);
		cnt = 0;
		do
		{
			modbus_read_bits(m_ctx, Arrived_2, 1, m_buf_8);
			usleep(100);
		} while (m_buf_8[0] == 0 && cnt++<100);

		if (cnt >= 50)
			return cnt;

		/*while ((0 != modbus_read_bits(m_ctx, Arrived_2, 1, m_buf_8)) && cnt++ < 100)
		{
			usleep(100);
		}*/

		//ret = (cnt < 100);
	}

	else if (id == Rot_Axis_3)
	{
		ret = modbus_read_bits(m_ctx, Cylinder0Status, 1, m_buf_8);
		if (m_buf_8[0] == 1)
		{
			ret = modbus_write_bit(m_ctx, CylinderEnable, ON);
			ret = modbus_write_bit(m_ctx, CylinderRotateSwitch, ON);//气缸控制转到90度位置

			int overtime = 60;
			int i = 0;
			do
			{
				ret = modbus_read_bits(m_ctx, Cylinder90Status, 1, m_buf_8);
				Sleep(50);
			} while ((m_buf_8[0] == 0) && (i++= overtime)
			{
				i = 0;
				return i;
			}
		}
		else
		{
			ret = modbus_read_bits(m_ctx, Cylinder90Status, 1, m_buf_8);
			if (m_buf_8[0] == 1)
			{
				ret = modbus_write_bit(m_ctx, CylinderEnable, ON);
				ret = modbus_write_bit(m_ctx, CylinderRotateSwitch, OFF);//气缸控制转到0度位置

				int overtime = 20;
				int i = 0;
				do
				{
					ret = modbus_read_bits(m_ctx, Cylinder0Status, 1, m_buf_8);
					Sleep(50);
				} while ((m_buf_8[0] == 0) && (i++= overtime)
				{
					i = 0;
					return i;
				}
			}
		}

	}
	return ret;
}
int rot_plat_VelMove(int id, bool dir, int vel, int acc)
{
	int ret;
	if (!b_isInitial) {
		return -1;
	}
	if (id == Rot_Axis_1) {
		ret = modbus_write_bit(m_ctx, MoveAbsMode, ON);
		ret = modbus_write_bit(m_ctx, MoveStepMode, OFF);
		uint16_t ang[2];
		if (dir) {
			ang[0] = (uint16_t)(MaxInt32);
			ang[1] = (uint16_t)(MaxInt32 >> 16);
		}
		else
		{
			ang[0] = (uint16_t)(MinInt32);
			ang[1] = (uint16_t)(MinInt32 >> 16);
		}

		ret = modbus_write_registers(m_ctx, ObjAngles_1, 2, ang);
		uint16_t ve[2];
		ve[0] = (uint16_t)(vel);
		ve[1] = (uint16_t)(vel >> 16);
		ret = modbus_write_registers(m_ctx, ObjVel_1, 2, ve);
		if (ret == -1) {
			return -1;
		}
		if (acc != 0) {
			modbus_write_register(m_ctx, AccTime_1, (uint16_t)acc);
			ret = modbus_write_bit(m_ctx, AccUpdate, ON);
			ret = modbus_write_bit(m_ctx, AccUpdate, OFF);
		}
		ret = modbus_write_bit(m_ctx, MoveSwitch_1, ON);
		int cnt = 0;
		/*while ((0 != modbus_read_bits(m_ctx, Busy_1, 1, m_buf_8)) && cnt++ < 50)
		{
		}*/

		do
		{
			modbus_read_bits(m_ctx, Busy_1, 1, m_buf_8);
			usleep(100);
		} while (m_buf_8[0] == 0 && cnt++<50);

		if (cnt >= 50)
			return cnt;

		ret = modbus_write_bit(m_ctx, MoveSwitch_1, OFF);
		cnt = 0;
		/*while ((0 != modbus_read_bits(m_ctx, Arrived_1, 1, m_buf_8)) && cnt++ < 100)
		{
			usleep(100);
		}*/
		do
		{
			modbus_read_bits(m_ctx, Arrived_1, 1, m_buf_8);
			usleep(100);

		} while (m_buf_8[0] == 0 && cnt++<100);

		if (cnt >= 100)
			return cnt;


		//ret = (cnt < 100);
	}
	else if (id == Rot_Axis_2) {
		ret = modbus_write_bit(m_ctx, MoveAbsMode, ON);
		ret = modbus_write_bit(m_ctx, MoveStepMode, OFF);
		uint16_t ang[2];
		if (dir) {
			ang[0] = (uint16_t)(MaxInt32);
			ang[1] = (uint16_t)(MaxInt32 >> 16);
		}
		else
		{
			ang[0] = (uint16_t)(MinInt32);
			ang[1] = (uint16_t)(MinInt32 >> 16);
		}

		ret = modbus_write_registers(m_ctx, ObjAngles_2, 2, ang);
		uint16_t ve[2];
		ve[0] = (uint16_t)(vel);
		ve[1] = (uint16_t)(vel >> 16);
		ret = modbus_write_registers(m_ctx, ObjVel_2, 2, ve);
		if (ret == -1) {
			return -1;
		}
		if (acc != 0) {
			modbus_write_register(m_ctx, AccTime_2, (uint16_t)acc);
			ret = modbus_write_bit(m_ctx, AccUpdate, ON);
			ret = modbus_write_bit(m_ctx, AccUpdate, OFF);
		}
		ret = modbus_write_bit(m_ctx, MoveSwitch_2, ON);
		ret = modbus_write_bit(m_ctx, ServoEnable_2, ON);
		int cnt = 0;
		/*while ((0 != modbus_read_bits(m_ctx, Busy_2, 1, m_buf_8)) && cnt++ < 50)
		{
		}*/
		do
		{
			modbus_read_bits(m_ctx, Busy_2, 1, m_buf_8);
			usleep(100);
		} while (m_buf_8[0] != 0 && cnt++<50);

		if (cnt >= 50)
			return cnt;
		
		ret = modbus_write_bit(m_ctx, MoveSwitch_2, OFF);
		ret = modbus_write_bit(m_ctx, ServoEnable_2, OFF);
		cnt = 0;
		/*while ((0 != modbus_read_bits(m_ctx, Arrived_2, 1, m_buf_8)) && cnt++ < 100)
		{
			usleep(100);
		}*/

		do
		{
			modbus_read_bits(m_ctx, Arrived_2, 1, m_buf_8);
			usleep(100);
		} while (m_buf_8[0] == 0 && cnt++<100);

		if (cnt >= 100)
			return cnt;

		//ret = (cnt < 100);
	}

	return ret;
}
int rot_plat_Stop(int id)
{
	int ret = 0;
	if (!b_isInitial) {
		return -1;
	}
	ret = modbus_write_bit(m_ctx, Emgency, ON);
	int cnt = 0;
	/*while ((0 != modbus_read_bits(m_ctx, EmgencyStatus, 1, m_buf_8)) && cnt++ < 50)
	{
	}*/
	do
	{
		modbus_read_bits(m_ctx, EmgencyStatus, 1, m_buf_8);
	} while (m_buf_8[0] == 0 && cnt++<50);
	ret = modbus_write_bit(m_ctx, Emgency, OFF);

	return ret;
}

int rot_plat_Alarm(int id)
{
	int ret = 0;

	if (id == Rot_Axis_1)
		ret = modbus_read_bits(m_ctx, Alarm_1, 1, m_buf_8);
	else if (id == Rot_Axis_2)
		ret = modbus_read_bits(m_ctx, Alarm_2, 1, m_buf_8);
	else if (id == Rot_Axis_3)
		ret = 1;

	return ret;
}

bool modbusInit()
{	
	const char *device = getValue("Serial");
	//sprintf(device, "COM%s", device);
	if (m_ctx == NULL) {
		m_ctx = modbus_new_rtu(device, Baudrate, Parity, Databit, Stopbit);
	}
	int ret = modbus_set_slave(m_ctx, SLAVE); // set slave adress
	if (ret == -1) {
		return false;
	}
	ret = modbus_connect(m_ctx);
	if (ret == -1) {
		return false;
	}
	b_isInitial = true;
	//rot_plat_home(Rot_Axis_1, 0);

	return b_isInitial;
}

bool rotInit()
{	
	paraInit();//系统参数初始化以及读取配置文件	
	if (modbusInit())
	{
		b_isInitial = true;		
	}
	return b_isInitial;
}

void closeModbus()
{
	if(m_ctx!=NULL)
	{
		modbus_close(m_ctx);
		modbus_free(m_ctx); 
	}
	
}
/*
* Copyright © 
*
* antoy wu
* 2018-4-16 21:16:30
*/

#ifndef ROTCONTROL_H
#define ROTCONTROL_H

/* Add this for macros that defined unix flavor */
#if (defined(__unix__) || defined(unix)) && !defined(USG)
#include 
#endif

#ifndef _MSC_VER
#include 
#else
#include "stdint.h"
#endif

#include "modbus-version.h"
#include 
#include "RotationPlatformDefine.h"

#if defined(_MSC_VER)
# if defined(DLLBUILD)
/* define DLLBUILD when building the DLL */
#  define ROT_API __declspec(dllexport)
# else
#  define ROT_API __declspec(dllimport)
# endif
#else
# define MODBUS_API
#endif

char*       messageStr;
volatile bool b_stop;
bool		  b_isInitial;

modbus_t*	m_ctx;
int				m_rc;
int				m_nb_fail;
int				m_nb_loop;
int				m_addr;
int				m_nb;
uint8_t*		m_tab_rq_bits;
uint8_t*		m_tab_rp_bits;
uint16_t*		m_tab_rq_registers;
uint16_t*		m_tab_rw_rq_registers;
uint16_t*		m_tab_rp_registers;

uint16_t		m_tab_reg[32] = { 0 };
uint8_t		    m_rec_reg[32] = { 0 };
uint8_t			m_buf_8[32] = { 0 };
uint16_t		m_buf_16[32] = { 0 };

int32_t			m_cur_pos[3] = { 0 };
int32_t			m_cur_vel[3] = { 0 };
int32_t			m_cur_acc[3] = { 0 };
bool			b_busy;
bool			b_alarm;
bool			b_emgency;

PlatformSetup m_platform_setup;


ROT_API bool rotInit();
ROT_API int rot_plat_home(int id, int vel);
ROT_API int rot_plat_moveto(int id, int pos, int vel, int acc);
ROT_API int rot_plat_step(int id, int step, int vel, int acc);
ROT_API int rot_plat_VelMove(int id, bool dir, int vel, int acc);
ROT_API int rot_plat_Stop(int id);
ROT_API int rot_plat_Alarm(int id);
ROT_API void closeModbus();

#endif  /* ROTCONTROL_H */

C# 上位机界面 CRotPlatformControl.cs  IMUDebugTool.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace RotPlatformControl_CsDll
{
    public class CRotPlatformControl
    {
        [DllImport("modbus.dll", EntryPoint = "sum", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int sum(int a, int b);

        [DllImport("modbus.dll", EntryPoint = "getValue", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr getValue(IntPtr intPtrKey);

        [DllImport("modbus.dll", EntryPoint = "setValue", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr setValue(IntPtr intPtrKey, IntPtr intPtrValue);

        [DllImport("modbus.dll", EntryPoint = "rotInit", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern bool rotInit();

        [DllImport("modbus.dll", EntryPoint = "rot_plat_home", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int rot_plat_home(int id, int vel);

        [DllImport("modbus.dll", EntryPoint = "rot_plat_moveto", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int rot_plat_moveto(int id, int pos, int vel, int acc);

        [DllImport("modbus.dll", EntryPoint = "rot_plat_step", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int rot_plat_step(int id, int step, int vel, int acc);

        [DllImport("modbus.dll", EntryPoint = "rot_plat_VelMove", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int rot_plat_VelMove(int id, bool dir, int vel, int acc);

        [DllImport("modbus.dll", EntryPoint = "rot_plat_Stop", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int rot_plat_Stop(int id);

        [DllImport("modbus.dll", EntryPoint = "rot_plat_Alarm", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int rot_plat_Alarm(int id);

        [DllImport("modbus.dll", EntryPoint = "closeModbus", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int closeModbus();
    }

    public class CModbusDefine
    {
        public const int SLAVE = 1;
        public const int CharOvertime = 3;
        public const int ReplayOvertime = 300;

        public const int Baudrate = 19200;
        public const int Databit = 8;
        public const int Stopbit = 1;
        public const char Parity = 'E';

        public const int Rot_Axis_1 = 0;
        public const int Rot_Axis_2 = 1;
        public const int Rot_Axis_3 = 2;
        public const int Rot_Axis_ALL = 3;

        public const ushort ResetVel_1 = 110;
        public const ushort ResetVel_2 = 114;
        public const ushort ResetHomeVel_1 = 112;
        public const ushort ResetHomeVel_2 = 116;

        public const ushort AccTime_1 = 118;
        public const ushort AccTime_2 = 120;
        public const ushort HomeAccTime_1 = 119;
        public const ushort HomeAccTime_2 = 121;

        public const ushort ObjCycles_1 = 130;
        public const ushort ObjCycles_2 = 150;
        public const ushort ObjAngles_1 = 132;
        public const ushort ObjAngles_2 = 152;
        public const ushort ObjVel_1 = 122;
        public const ushort ObjVel_2 = 124;

        public const ushort CylinderOvertime = 154;
        public const ushort ResetOvertime = 156;

        public const ushort CurCycles_1 = 220;
        public const ushort CurCycles_2 = 224;
        public const ushort CurAngles_1 = 222;
        public const ushort CurAngles_2 = 226;

        public const ushort SystemReboot = 100;//pulse
        public const ushort SystemClear = 101;//pulse
        public const ushort Emgency = 102;
        public const ushort EmgencyStatus = 103;
        public const ushort Door = 106;
        public const ushort CommStatus = 107;

        public const ushort ResetSwitch = 110;
        public const ushort ResetStatus = 111;

        public const ushort ResetVelupdate = 115;//pulse
        public const ushort AccUpdate = 116;//pulse


        //cylinder
        public const ushort CylinderEnable = 120;
        public const ushort CylinderRotateSwitch = 121;
        public const ushort Cylinder0Status = 122;
        public const ushort Cylinder90Status = 123;
        public const ushort CylinderBusy = 124;

        //axis status
        public const ushort Busy_1 = 130;
        public const ushort Busy_2 = 150;
        public const ushort Arrived_1 = 131;
        public const ushort Arrived_2 = 151;
        public const ushort Alarm_1 = 132;
        public const ushort Alarm_2 = 152;

        //axis control
        public const ushort MoveStepMode = 142;
        public const ushort MoveAbsMode = 143;
        public const ushort ServoEnable_1 = 140;
        public const ushort ServoEnable_2 = 160;
        public const ushort AlarmClear_1 = 144;//pulse
        public const ushort AlarmClear_2 = 164;
        public const ushort MoveSwitch_1 = 141;
        public const ushort MoveSwitch_2 = 161;
        public const  ushort RunStatus = 170;
        public const  ushort SystemAlarm = 171;

        default parameters config (pulse)
        //public const unsigned short Default1Read = 203;//pulse
        //public const unsigned short Default1Write = 204;//pulse

        //public const unsigned short Default2Read = 205;//pulse
        //public const unsigned short Default2Write = 206;//pulse

        public const int MaxInt32 = 2147483647;
        public const int MinInt32 = -2147483648;
    }

    public class CRotDefine
    {
       
        ...

        //[Precision]
        public const int Precision_Axis1=0;
        public const int Precision_Axis2=90;
        public const int Precision_Axis3=0;
        //[Accuracy]
        public const int Accuracy_step1_Axis1=90;
        public const int Accuracy_step2_Axis1=180;
        public const int Accuracy_step3_Axis1=270;
        public const int Accuracy_step4_Axis1=360;

        public const int Vel = 7000; //轴速度
        public const int Acc = 0;//轴加速度
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using DeviceLibrary.PlatformBase;
using RotPlatformControl_CsDll;
using DeviceLibrary.ImuPlatformMirage2B;
using BaseLibrary.Extension;
using BaseLibrary.Object;

namespace Mirage2B_IMU_Test
{
    public partial class IMUDebugTool : Form
    {
        public bool isRotInit = false;
        public IRotPlatform _platform = new ImuRotPlatformMirage2B();
        //public CRotPlatformControl CRPC = new CRotPlatformControl();
        //public CModbusDefine CMD = new CModbusDefine();
        //public CRotDefine CRD=new CRotDefine();

        public IMUDebugTool()
        {
            InitializeComponent();
            InitData();
            InitializeRotPlatform();
        }
        private void InitData()
        {
            _platform.Load();
        }

        private void InitializeRotPlatform()
        {
            isRotInit = CRotPlatformControl.rotInit();
            lblMessage.Text = $"转台Mobus初始化状态为 {isRotInit}";

            radioButtonRotX.Checked = false;
            radioButtonRotY.Checked = false;
            radioButtonRotZ.Checked = false;
            radioButtonALL.Checked = true;

            comboBoxMoveToPos.Text = "InstallPos";
            comboBoxStepMoveStep.Text = "60";
            comboBoxVelMoveVelocity.Text = "60";

            InitDgv_AxisStatus();
            InitDgv_AxisPos();
        }
        private void IMUDebugTool_FormClosing(object sender, FormClosingEventArgs e)
        {
            CRotPlatformControl.closeModbus();
        }

        private void buttonHome_Click(object sender, EventArgs e)
        {
            log("转台开始复位!");
            Cursor.Current = Cursors.WaitCursor;
            int id = 0;
            if (radioButtonRotX.Checked)
            {
                id = CModbusDefine.Rot_Axis_1;
            }

            else if (radioButtonRotY.Checked)
            {
                id = CModbusDefine.Rot_Axis_2;
            }

            else if (radioButtonRotZ.Checked)
            {
                id = CModbusDefine.Rot_Axis_3;
            }

            else if (radioButtonALL.Checked)
            {
                id = CModbusDefine.Rot_Axis_ALL;
                if ((getHomeResult(CModbusDefine.Rot_Axis_1) == 1) && (getHomeResult(CModbusDefine.Rot_Axis_2) == 1) && (getHomeResult(CModbusDefine.Rot_Axis_3) == 1))
                    log($"三轴转台复位成功!");
                else
                    log($"三轴转台复位失败!");
            }

            if (id < 3)
            {
                getHomeResult(id);
            }

            Cursor.Current = Cursors.Default;
        }

        private int getHomeResult(int id)
        {
            int res = CRotPlatformControl.rot_plat_home(id, 0);
            if (res == 1)
                log($"轴{id}复位成功");
            else
                log($"轴{id}复位失败!code:{res}");


            return res;
        }


        private void buttonStop_Click(object sender, EventArgs e)
        {
            log("转台开始停止!");
            int res = CRotPlatformControl.rot_plat_Stop(CModbusDefine.Rot_Axis_1);
            if (res == 1)
                lblMessage.Text = $"转台停止成功";
        }


        private void setIniTest()
        {
            string strKey = "Hello";
            string strValue = "Kitty";
            string res = setvalue(strKey, strValue);
            lblMessage.Text = res.ToString();
        }


        private string Getvalue(string strKey)
        {
            IntPtr key = Marshal.StringToHGlobalAnsi(strKey);
            IntPtr temp = CRotPlatformControl.getValue(key);
            string res = Marshal.PtrToStringAnsi(temp).ToString();
            temp = IntPtr.Zero;
            return res;
        }


        private string setvalue(string strKey, string strValue)
        {
            IntPtr key = Marshal.StringToHGlobalAnsi(strKey);
            IntPtr value = Marshal.StringToHGlobalAnsi(strValue);
            IntPtr temp = CRotPlatformControl.setValue(key, value);
            string res = Marshal.PtrToStringAnsi(temp).ToString();
            temp = IntPtr.Zero;
            return res;
        }

        private void log(string strMsg)
        {
            ShowMsg(strMsg, Color.Blue);
        }
        private void error(string strErrMsg)
        {
            ShowMsg(strErrMsg, Color.Red);
        }

        private delegate void ShowMsgHandle(string msgString, Color color);
        private void ShowMsg(string msgString, Color color)
        {
            if (!lblMessage.InvokeRequired)
            {
                lblMessage.Text = msgString;
                lblMessage.ForeColor = color;
                lblMessage.Refresh();
            }
            else
            {
                Invoke(new ShowMsgHandle(ShowMsg), msgString, color);
            }
        }


        #region controls init
        private void InitDgv_AxisStatus()
        {
            if (_platform == null)
            {
                return;
            }
            dgvAxisStatus.Columns.Clear();
            dgvAxisStatus.Columns.Add("Properties", "Properties");
            dgvAxisStatus.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;

            foreach (var axis in _platform.Axis.Values)
            {
                var index = dgvAxisStatus.Columns.Add(axis.Name, axis.Name);
                dgvAxisStatus.Columns[index].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            foreach (var prop in RotPlcAxis.GetProps())
            {
                var row = dgvAxisStatus.Rows.Add();
                dgvAxisStatus.Rows[row].Cells[0].Value = prop;
            }
            UpdateDgv_Axis();
        }

        private void UpdateDgv_Axis()
        {
            if (_platform == null)
            {
                return;
            }
            var axisIndex = 1;
            foreach (var axis in _platform.Axis.Values)
            {
                var row = 0;
                foreach (var status in axis.GetStatus())
                {
                    dgvAxisStatus.Rows[row++].Cells[axisIndex].Value = status;
                }
                axisIndex++;
            }
        }

        private void InitDgv_AxisPos()
        {
            if (_platform == null)
            {
                return;
            }
            foreach (var axis in _platform.Axis.Values)
            {
                comboBoxMoveToPos.Items.Clear();
                comboBoxPosName.Items.Clear();
                foreach (var posname in axis.Positions.Keys)
                {
                    comboBoxMoveToPos.Items.Add(posname);
                    comboBoxPosName.Items.Add(posname);
                }
                break;
            }

            dgvAxisPos.Columns.Clear();
            dgvAxisPos.Columns.Add("Properties", "Properties");
            dgvAxisPos.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
            foreach (var axis in _platform.Axis.Values)
            {
                var index = dgvAxisPos.Columns.Add(axis.Name, axis.Name);
                dgvAxisPos.Columns[index].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            dgvAxisPos.Rows.Clear();
            dgvAxisPos.Rows.Add(100);

            var axisIndex = 1;
            foreach (var axis in _platform.Axis.Values)
            {
                var row = 0;
                foreach (var pos in axis.Positions)
                {
                    dgvAxisPos.Rows[row].Cells[0].Value = $"[{row}] {pos.Key}";
                    dgvAxisPos.Rows[row++].Cells[axisIndex].Value = pos.Value;
                }
                axisIndex++;
            }
        }
        #endregion

        private void buttonMoveTo_Click(object sender, EventArgs e)
        {
            log("转台开始移动到指定位置!");
            Cursor.Current = Cursors.WaitCursor;
            int id = 0;
            if (radioButtonRotX.Checked)
            {
                id = CModbusDefine.Rot_Axis_1;
            }


            else if (radioButtonRotY.Checked)
            {
                id = CModbusDefine.Rot_Axis_2;
            }


            else if (radioButtonRotZ.Checked)
            {
                id = CModbusDefine.Rot_Axis_3;
            }

            else if (radioButtonALL.Checked)
            {
                id = CModbusDefine.Rot_Axis_ALL;
                error($"请选择单轴!MoveTo功能只能选择单轴,不能选择全部三轴!");
            }

            if (id < 3)
            {
                getMoveToResult(id);
            }

            Cursor.Current = Cursors.Default;
        }

        private int getMoveToResult(int id)
        {
            //int res = CRotPlatformControl.rot_plat_Alarm(id);
            //if (res != 1)
            //{
            //    log($"轴{id}报警");
            //    return res;
            //}
            int pos = Convert.ToInt32(comboBoxMoveToPos.Text);
            int res = CRotPlatformControl.rot_plat_moveto(id, pos * 100, 7000, 0);
            if (res == 1)
                log($"轴{id}移动至指定位置{pos}成功!");
            else
                log($"轴{id}移动至指定位置{pos}失败!code:{res}");
            return res;
        }

        private void buttonStep_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            int id = 0;
            if (radioButtonRotX.Checked)
            {
                id = CModbusDefine.Rot_Axis_1;
            }


            else if (radioButtonRotY.Checked)
            {
                id = CModbusDefine.Rot_Axis_2;
            }

            else if (radioButtonRotZ.Checked)
            {
                id = CModbusDefine.Rot_Axis_3;
                //error($"请选择X或Y轴!Step功能不支持Z轴!");
            }

            else if (radioButtonALL.Checked)
            {
                id = CModbusDefine.Rot_Axis_ALL;
                error($"请选择单轴!MoveTo功能只能选择单轴,不能选择全部三轴!");
            }


            if (id < 3)
            {
                getStepResult(id);
            }


            Cursor.Current = Cursors.Default;

        }


        private int getStepResult(int id)
        {
            int step = Convert.ToInt32(comboBoxStepMoveStep.Text);
            int res = CRotPlatformControl.rot_plat_step(id, step, 7000, 0);
            if (res == 1)
               log($"轴{id}单步{step}移动成功!");
            else
               error($"轴{id}单步{step}移动失败!code:{res}");
            return res;
       }


        private void buttonVel_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            int id = 0;
            if (radioButtonRotX.Checked)
            {
                id = CModbusDefine.Rot_Axis_1;
            }

            else if (radioButtonRotY.Checked)
            {
                id = CModbusDefine.Rot_Axis_2;
            }

            else if (radioButtonRotZ.Checked)
            {
                id = CModbusDefine.Rot_Axis_3;
                error($"请选择X/0或Y/1轴!Step功能不支持Z/2轴!");
            }

            else if (radioButtonALL.Checked)
            {
                id = CModbusDefine.Rot_Axis_ALL;
                error($"请选择单轴!MoveTo功能只能选择单轴,不能选择全部三轴!");
            }

            if (id < 2)
            {
                getVelMoveResult(id);
            }
            Cursor.Current = Cursors.Default;
        }

        private int getVelMoveResult(int id)
        {
            int vel = Convert.ToInt32(comboBoxVelMoveVelocity.Text);
            bool dir=(vel>0) ? true : false;
            int res = CRotPlatformControl.rot_plat_VelMove(id, dir, vel, 0);
            if (res == 1)
                log($"轴{id}按照速度{vel}运动设置成功!");
            else
                error($"轴{id}按照速度{vel}运动设置失败!code:{res}");


            return res;
        }


        private void buttonTeach_Click(object sender, EventArgs e)
        {

        }


        private void buttonDelete_Click(object sender, EventArgs e)
        {

        }
    }
}



你可能感兴趣的:(c#)