agrobot_base/AgroBase/AgroBase/Forms/frmMKS.cs

2362 lines
104 KiB
C#

using AgroBase.Services;
using System;
using System.Collections;
using System.IO.Ports;
using System.Threading.Tasks;
using System.Windows.Forms;
using static AgroBase.Models.Enums;
namespace AgroBase.Forms
{
public partial class frmMKS : Form
{
SerialPort serialPort1 = new SerialPort();
byte Addr;
byte DataSended;
string word16;
int data16;
string word32;
long data32;
string word64;
long data64;
string Text_BUF;
int tCHK;
int rCHK;
byte Readata;
byte[] Buffer;
byte[] SerialBuffer_RX;
int Data_Number;
string str;
string HV, FV;
byte[] FV1 = new byte[] { 0, 0, 0 };
int Temp1 = 0;
#region Bytes
// Instruções
int[] QueryCommand = new int[] {
0x30, 0x33, 0x39, 0x3A, 0x3B, 0x3E, // (0 Valor do codificador de carry 1 Número de pulsos acumulados de entrada 2 Erro de ângulo de posição 3 Estado de habilitação da placa de acionamento em malha fechada 4 Estado de retorno automático ao zero de um círculo ao ligar 5 Indicador de travamento)
0xF3, 0xF3, // (6 Habilitar a placa de acionamento 7 Desabilitar a placa de acionamento)
0xF6, // (8 Modo de controle de velocidade do motor - iniciar)
0xF6, // (9 Modo de controle de velocidade do motor - parar)
0xFF, // (10 Iniciar operação automática ao ligar)
0xFF, // (11 Parar operação automática ao ligar)
0x84, // (12 Configuração de subdivisão - confirmar)
0xFD, // (13 Modo de controle de posição do motor - iniciar)
0x80, // (14 Calibrar o codificador)
0x81, // (15 Confirmar tipo de motor)
0x82, // (16 Confirmar modo de operação)
0x83, // (17 Confirmar valor da corrente (mA))
0x85, // (18 Confirmar configuração de habilitação)
0x86, // (19 Confirmar direção do motor)
0x87, // (20 Confirmar apagamento automático da tela)
0x88, // (21 Confirmar proteção contra travamento)
0x89, // (22 Confirmar interpolação de subdivisão)
0x8A, // (23 Confirmar taxa de transmissão serial)
0x8B, // (24 Confirmar endereço de comunicação do motor)
0xA1, // (25 Confirmar posição Kp)
0xA2, // (26 Confirmar posição Ki)
0xA3, // (27 Confirmar posição Kd)
0xA4, // (28 Confirmar aceleração de início)
0xA5, // (29 Confirmar aceleração de parada)
0x90, // (30 Ativar modo de retorno ao zero)
0x90, // (31 Parâmetros de limite)
0x91, // (32 Retorno ao zero de limite)
0x92, // (33 Retorno direto ao zero)
0x93, // (34 Confirmar direção de retorno ao zero)
0x94, // (35 Retornar ao ponto zero)
0x3F, // (36 Restaurar configuração de fábrica)
0x3D, // (37 Ler parâmetros - cancelar estado de travamento)
0xFD, // (38 Modo de controle de posição do motor - parar)
0x31, // (39 Ler parâmetros - valor do codificador incremental)
0x32, // (40 Ler parâmetros - velocidade real do motor)
0x8C, // (41 Confirmar resposta do escravo)
0x8D, // (42 Confirmar agrupamento do escravo)
0x40, // (43 Informações da versão)
0xF4, // (44 Modo de controle de posição do motor - coordenadas relativas)
0xF5, // (45 Modo de controle de posição do motor - coordenadas absolutas)
0x34, // (46 Ler estado da porta IO)
0x8E, // (47 Confirmar MODBUS)
0x8F, // (48 Confirmar bloqueio de tecla)
0x9A // (49 Retorno ao zero de um círculo)
};
// Bytes comuns
byte[] byte_data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 };
// Bytes de função
byte FWD = 0x80;
byte RWD = 0x00;
byte STOP = 0xF7;
byte EN_ON = 0x01;
byte EN_OFF = 0x00;
byte Save_Speed = 0xC8;
byte Clear_Speed = 0xCA;
// Dados
byte Speed;
byte Speed2;
ushort Subdivision;
byte[] Pulse;
byte[] RelAxis;
byte[] AbsAxis;
byte[] Kp;
byte[] Ki;
byte[] Kd;
byte[] ACC;
byte[] MaxT;
byte[] Start_ACC = { 0x10 }, Stop_ACC = { 0x10 };
byte[] Speed_1, Speed_2;
byte[] Current;
ushort Max_Current;
// Recepção de estado
byte EN_STATE_ON = 0x01;
byte EN_STATE_OFF = 0x00;
byte Stall_YES = 0x01;
byte Stall_ON = 0x02;
#endregion
// String de estado
readonly string Mot_18 = "1.8°";
readonly string Mot_09 = "0.9°";
readonly string CR_OPEN = "CR_OPEN";
readonly string CR_CLOSE = "CR_CLOSE";
readonly string CR_vFOC = "CR_vFOC";
readonly string SR_OPEN = "SR_OPEN";
readonly string SR_CLOSE = "SR_CLOSE";
readonly string SR_vFOC = "SR_vFOC";
string Text1_window = "Erro";
string Text2_window = "Aviso";
string Text1_Zero = "Retornando";
string Text1_DataError = "Aviso: Por favor, selecione o tipo de dados.";
string Text2_Zero = "Sucesso ao retornar para zero";
string Text3_Zero = "Erro ao retornar para zero";
string Text1_EN = "Habilitado";
string Text2_EN = "Desaabilitado";
string Text1_Stall = "Travado";
string Text2_Stall = "Destravado";
string Text1_Block = "Sucesso";
string Text2_Block = "Falha";
string Text1_Move = "Movimento completo";
string Text2_Move = "Movimento sucesso";
string Text3_Move = "Movimento falhou";
string Text4_Move = "Em movimento";
string Text1_COM = "Erro de dados";
string Text1_Dir = "Para frente";
string Text2_Dir = "Para trás";
string Text3_Dir = "Parado";
string Text1_Stop = "Parado completo";
string Text2_Stop = "Parado sucesso";
string Text3_Stop = "Parado falhou";
string Text4_Stop = "Parando";
string Text1_Cal = "Calibrando...";
string Text2_Cal = "Calibragem completa";
string Text3_Cal = "Falha ao calibrar";
string Text1_RX = "Sucesso ao configurar";
string Text2_RX = "Erro ao configurar";
string Text_HardVer = "Versão do hardware";
string Text_FirmVer = "Versão da firmware";
string Text_CurrentError = "Erro: A corrente deve estar entre 0 e 5200";
readonly string[] I_Ma = { "0", "400", "800", "1200", "1600", "2000", "2400", "2800", "3200", "3600", "4000", "4400", "4800", "5200" };
readonly string[] MStepValues = { "1", "2", "4", "8", "16", "32", "64", "128", "256" };
readonly string EN_H = "H";
readonly string EN_L = "L";
readonly string EN_Hold = "Hold";
readonly string Dir_CW = "CW";
readonly string Dir_CCW = "CCW";
readonly string Disable = "Disable";
readonly string Enable = "Enable";
readonly string[] UartBaud = { "9600", "19200", "25000", "38400", "57600", "115200", "256000" };
readonly string[] UartAddr = { "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0a", "0x0b", "0x0c", "0x0d", "0x0e", "0x0f", "0x10" };
readonly string[] HardVersion = { "未知电机", "MKS SERVO42D_485", "MKS SERVO42D_CAN", "MKS SERVO57D_485", "MKS SERVO57D_CAN", "MKS SERVO28D_485", "MKS SERVO28D_CAN", "MKS SERVO35D_485", "MKS SERVO35D_CAN" };
readonly string[] CurrentText_42D = { "100", "1000", "2000", "3000" };
readonly string[] CurrentText_57D = { "100", "1000", "2000", "3000", "4000", "5000", "5200" };
string[] ModosControle = { "CR_OPEN", "CR_CLOSE", "CR_vFOC", "SR_OPEN", "SR_CLOSE", "SR_vFOC" };
string[] VelocidadesPosicao = { "1", "10", "18", "600", "1200", "1800", "2400", "3000" };
string[] ModosControlePosicao = { "Pulses", "RelAxis", "AbsAxis" };
string[] Rampas = { "0", "8", "16", "32", "64", "128", "255" };
string[] LimiteModos = { "Disable", "DirMode", "NearMode" };
string[] LimiteZeros = { "Limpar", "Definir" };
string[] LimiteVelocidades = { "0", "1", "2", "3", "4" };
string[] LimiteDirecoes = { "Antihorário", "Horário" };
string[] LimiteRetornos = { "Desabilitado", "Habilitado" };
string[] EnderecosControlar = { "0x01", "0x02" };
string _EnderecoControlar = "";
public frmMKS()
{
InitializeComponent();
serialPort1.DataReceived += port_DataReceived;
}
private void frmMKS_Load(object sender, EventArgs e)
{
cmbBaud.Items.AddRange(UartBaud);
cmbEndereco.Items.AddRange(UartAddr);
cmbProtecao.Items.AddRange(LimiteRetornos);
cmbModoControle.Items.AddRange(ModosControle);
cmbCorrenteMaxima.Items.AddRange(I_Ma);
cmbMStep.Items.AddRange(MStepValues);
cmbModo.Items.AddRange(ModosControlePosicao);
cmbUartBaud.Items.AddRange(UartBaud);
cmbUartAddr.Items.AddRange(UartAddr);
cmbRampaInicio.Items.AddRange(Rampas);
cmbRampaParada.Items.AddRange(Rampas);
cmbModoLimite.Items.AddRange(LimiteModos);
cmbZeroLimite.Items.AddRange(LimiteZeros);
cmbVelocidadeLimite.Items.AddRange(LimiteVelocidades);
cmbDirecaoLimite.Items.AddRange(LimiteDirecoes);
cmbVelocidadePosicao.Items.AddRange(VelocidadesPosicao);
cmbLimiteRetorno.Items.AddRange(LimiteRetornos);
btnAtualizar_Click(sender, e);
}
private void btnAtualizar_Click(object sender, EventArgs e)
{
ComboBox cmb = cmbPorta;
cmb.Items.Clear();
string[] sAllPort = null;
try
{
sAllPort = SerialPort.GetPortNames();
}
catch
{
}
for (int i = 0; i < sAllPort.Length; i++)
{
cmb.Items.Add(sAllPort[i]);
}
}
private void btnConectar_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
try
{
serialPort1.Close();
cmbPorta.Enabled = true;
cmbBaud.Enabled = true;
}
catch
{
}
btnConectar.Text = "Conectar";
}
else
{
try
{
serialPort1.PortName = cmbPorta.Text;
serialPort1.BaudRate = Convert.ToInt32(cmbBaud.Text, 10);
serialPort1.Open();
cmbPorta.Enabled = false;
cmbBaud.Enabled = false;
btnConectar.Text = "Desconectar";
btnSobre_Click(btnSobre, e);
}
catch
{
}
}
}
#region Acoes Botoes
private void btnGoHome_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "32";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]).ConfigureAwait(false);
}
private void btnCalibrar_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "14";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]).ConfigureAwait(false);
}
private void btnRestaurar_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "36";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnGravarLimite_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "49";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnGravarRetorno_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "31";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnZero_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "33";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnIrParaZero_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "35";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnIniciarPosicao_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "13";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnIniciarTodos_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "13";
DataSended = Convert.ToByte(MyButton.Tag);
RealizarMultiplosEnvios(DataSended).ConfigureAwait(false);
}
private void btnPararTodos_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "38";
DataSended = Convert.ToByte(MyButton.Tag);
RealizarMultiplosEnvios(DataSended).ConfigureAwait(false);
}
private void btnPararPosicao_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "38";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnModoControle_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "16";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnCorrenteMaxima_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "17";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnMStep_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "12";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnProtecao_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "21";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnBaudRate_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "23";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnEndereco_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "24";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnRampaInicio_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "28";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnRampaParada_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "29";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnErroCarregado_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "0";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnErroAcumulado_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "39";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnRPM_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "40";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnNumeroPulsos_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "1";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnErroAngulo_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "2";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnDriverHabilitado_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "3";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnResetZero_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "4";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnBloqueado_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "5";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnDesbloquear_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "37";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void btnSobre_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "43";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
#endregion
private async Task RealizarMultiplosEnvios(byte data)
{
foreach (string addr in EnderecosControlar)
{
/*DataSended = data;
_EnderecoControlar = addr;
await SendRelevantData(QueryCommand[DataSended]);
await Task.Delay(100);*/
MKS057DService.AdicionarComandoNaFila(new Models.MKS057ComandoModel()
{
Comando = data,
Endereco = Convert.ToByte(addr, 16),
Angulo = int.Parse(txtValor.Text),
Velocidade = int.Parse(cmbVelocidadePosicao.Text),
});
}
}
private void WriteByteToSerialPort(byte[] data, byte start, byte length)
{
if (serialPort1.IsOpen)
{
try
{
SerialService.EnviarDadosPortaSerial(serialPort1, data, start, length);
txDisplay();
}
catch
{
Console.WriteLine("Erro ao enviar dados para a porta serial");
}
}
else
MessageBox.Show("Porta serial não está aberta");
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) // Evento de recebimento de dados da porta serial
{
SerialBuffer_RX = new byte[11] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // SerialBuffer_RX[0] Cabeçalho do quadro [1] Endereço do escravo [2] Número da instrução
Data_Number = serialPort1.BytesToRead; // Número de bytes recebidos
if (serialPort1.BytesToRead > 0 && serialPort1.BytesToRead <= SerialBuffer_RX.Length)
{
for (int a = 0; a <= Data_Number - 1; a++)
{
SerialBuffer_RX[a] = (byte)serialPort1.ReadByte(); // Lê um byte do buffer de entrada SerialPort
}
Text_display();
}
}
private async Task SendRelevantData(int data) // Verifica o tipo de dados e envia
{
ushort SpeedText;
ushort SpeedText2;
byte SpeedText3;
ushort SubdivisionText;
uint PulseText;
long RelAxisText;
long AbsAxisText;
byte UartAddrText;
ushort KpText;
ushort KiText;
ushort KdText;
ushort ACCText;
ushort MaxTText;
ushort Start_ACCText, Stop_ACCText;
ushort CurrentText;
byte HomeTrig = 0x00, HomeDir = 0x00, EndLimit = 0x00;
byte Mode_0 = 0x00, Set_0 = 0x00, Speed_0 = 0x00, Dir_0 = 0x00;
try
{
Addr = Convert.ToByte(_EnderecoControlar, 16);
}
catch
{
Console.WriteLine("Erro ao definir endereco");
}
if (Addr <= 0xff && Addr >= 0x00)
{
if (DataSended < 6 || DataSended == 37 || DataSended == 39 || DataSended == 40 || DataSended == 43 || DataSended == 46)
//(0 valor do codificador de posição 1 número acumulado de pulsos de entrada 2 erro de ângulo de posição 3 estado de habilitação da placa de acionamento em malha fechada 4 estado de retorno automático único ao ligar 5 bit de bloqueio 37 estado de desbloqueio 39 valor do codificador de contagem acumulada 40 velocidade atual do motor 43 informação de versão 46 estado do status do porto IO)
{
if (DataSended == 46)
{
//-------------------Determinação do tipo de motor--------------------
tCHK = 0xFA + Addr + 0x40;
Buffer = new byte[] { 0xFA, Addr, 0x40, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
await Task.Delay(50);
//---------------------------------------------------
}
tCHK = 0xFA + Addr + data;
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
}
if (DataSended > 5 && DataSended < 8) //(6 habilitar placa de acionamento 7 desabilitar placa de acionamento)
{
if (DataSended == 6)
{
tCHK = 0xFA + Addr + data + EN_ON;
Buffer = new byte[] { 0xFA, Addr, (byte)data, EN_ON, (byte)tCHK };
//GB4_button_使能驱动板.Enabled = false;
//GB4_button_关闭驱动板.Enabled = true;
}
else
{
tCHK = 0xFA + Addr + data + EN_OFF;
Buffer = new byte[] { 0xFA, Addr, (byte)data, EN_OFF, (byte)tCHK };
//GB4_button_关闭驱动板.Enabled = false;
//GB4_button_使能驱动板.Enabled = true;
}
WriteByteToSerialPort(Buffer, 0, 5);
}
/*if (DataSended == 8) //(8 modo de controle de velocidade do motor - iniciar)
{
try
{
SpeedText = Convert.ToUInt16(GB4_3_comboBox_速度档位.Text, 10);
Speed_1 = BitConverter.GetBytes(SpeedText);
if (SpeedText <= 3000 && SpeedText >= 1)
{
if (GB4_3_radioButton_反转.Checked)
{
//Speed = Convert.ToByte(SpeedText | RWD);
Speed_1[1] |= RWD;
//Console.WriteLine(Speed);
}
else if (GB4_3_radioButton_正转.Checked)
{
//Speed = Convert.ToByte(SpeedText | FWD);
Speed_1[1] |= FWD;
//Console.WriteLine(Speed);
}
tCHK = 0xFA + Addr + data + Speed_1[1] + Speed_1[0] + Start_ACC[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, Speed_1[1], Speed_1[0], Start_ACC[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 7);
}
else
MessageBox.Show(Text1_Speedgear, Text1_window);
}
catch
{
MessageBox.Show(Text1_General, Text2_window);
}
}*/
if (DataSended == 9) //(9 modo de controle de velocidade do motor - parar)
{
tCHK = 0xFA + Addr + data + 0x00 + 0x00 + Stop_ACC[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, 0x00, 0x00, Stop_ACC[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 7);
}
if (DataSended == 10) //(10 iniciar execução automática ao ligar)
{
tCHK = 0xFA + Addr + data + Save_Speed;
Buffer = new byte[] { 0xFA, Addr, (byte)data, Save_Speed, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
Console.WriteLine(value: Save_Speed);
}
if (DataSended == 11) //(11 parar execução automática ao ligar)
{
tCHK = 0xFA + Addr + data + Clear_Speed;
Buffer = new byte[] { 0xFA, Addr, (byte)data, Clear_Speed, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
if (DataSended == 12) //(12 configuração de subdivisão - confirmar)
{
try
{
SubdivisionText = Convert.ToUInt16(cmbMStep.Text, 10);
//Console.WriteLine(SubdivisionText); //saída no console
if (SubdivisionText < 256 && SubdivisionText >= 1)
{
Subdivision = Convert.ToByte(SubdivisionText);
tCHK = 0xFA + Addr + data + Subdivision;
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)Subdivision, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (SubdivisionText == 256)
{
tCHK = 0xFA + Addr + data + 0x00;
Buffer = new byte[] { 0xFA, Addr, (byte)data, 0x00, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else
MessageBox.Show("O valor de MStep deve estar entre 1 e 256");
}
catch
{
Console.WriteLine("Erro ao configurar MStep");
}
}
if (DataSended == 13) //(13 modo de controle de posição do motor - iniciar)
{
try
{
SpeedText2 = Convert.ToUInt16(cmbVelocidadePosicao.Text, 10);
Speed_2 = BitConverter.GetBytes(SpeedText2);
if (cmbModo.Text == ModosControlePosicao[0]) // Se o controle for através de pulsos
{
try
{
PulseText = Convert.ToUInt32(lblAngulo.Text, 10);
Pulse = BitConverter.GetBytes(PulseText);
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
{
if (PulseText <= 4294967295 && PulseText >= 1)
{
if (rdbAntihorarioPosicao.Checked)
{
//Speed2 = Convert.ToByte(SpeedText2 | RWD);
Speed_2[1] |= RWD;
//Pulse = Convert.ToByte(PulseText);
}
else if (rdbHorarioPosicao.Checked)
{
//Speed2 = Convert.ToByte(SpeedText2 | FWD);
Speed_2[1] |= FWD;
//Pulse = Convert.ToByte(PulseText);
}
else
{
MessageBox.Show("Sentido de giro não selecionado");
}
tCHK = 0xFA + Addr + data + Speed_2[1] + Speed_2[0] + Start_ACC[0] + Pulse[3] + Pulse[2] + Pulse[1] + Pulse[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, Speed_2[1], Speed_2[0], Start_ACC[0], Pulse[3], Pulse[2], Pulse[1], Pulse[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 11);
}
else
MessageBox.Show("O número de pulsos deve estar entre 1 e 4294967295");
}
else
MessageBox.Show("A velocidade deve estar entre 1 e 3000");
}
catch
{
Console.WriteLine("Erro ao definir controle Pulses");
}
}
else if (cmbModo.Text == ModosControlePosicao[1])
{
DataSended = 44;
data = 0xF4;
try
{
Text_BUF = lblAngulo.Text;
if (Text_BUF.Length > 1)
{
if (Text_BUF[0] == '0' && (Text_BUF[1] == 'x' || Text_BUF[1] == 'X'))
{
RelAxisText = Convert.ToInt32(lblAngulo.Text, 16);
RelAxis = BitConverter.GetBytes(RelAxisText);
}
else
{
RelAxisText = Convert.ToInt32(lblAngulo.Text, 10);
RelAxis = BitConverter.GetBytes(RelAxisText * 16384 / 360);
}
}
else
{
RelAxisText = Convert.ToInt32(lblAngulo.Text, 10);
RelAxis = BitConverter.GetBytes(RelAxisText * 16384 / 360);
}
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
{
if (RelAxisText <= 2147483647 && RelAxisText >= -2147483647)
{
tCHK = 0xFA + Addr + data + Speed_2[1] + Speed_2[0] + Start_ACC[0] + RelAxis[3] + RelAxis[2] + RelAxis[1] + RelAxis[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, Speed_2[1], Speed_2[0], Start_ACC[0], RelAxis[3], RelAxis[2], RelAxis[1], RelAxis[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 11);
}
}
else
MessageBox.Show("Valor para controle inválido");
}
catch
{
Console.WriteLine("Erro ao definir controle RelAxis");
}
}
else if (cmbModo.Text == ModosControlePosicao[2])
{
DataSended = 45;
data = 0xF5;
try
{
Text_BUF = lblAngulo.Text;
if (Text_BUF.Length > 1)
{
if (Text_BUF[0] == '0' && (Text_BUF[1] == 'x' || Text_BUF[1] == 'X'))
{
AbsAxisText = Convert.ToInt32(lblAngulo.Text, 16);
AbsAxis = BitConverter.GetBytes(AbsAxisText);
}
else
{
AbsAxisText = Convert.ToInt32(lblAngulo.Text, 10);
AbsAxis = BitConverter.GetBytes(AbsAxisText * 16384 / 360);
}
}
else
{
AbsAxisText = Convert.ToInt32(lblAngulo.Text, 10);
AbsAxis = BitConverter.GetBytes(AbsAxisText * 16384 / 360);
}
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
{
if (AbsAxisText <= 2147483647 && AbsAxisText >= -2147483647)
{
tCHK = 0xFA + Addr + data + Speed_2[1] + Speed_2[0] + Start_ACC[0] + AbsAxis[3] + AbsAxis[2] + AbsAxis[1] + AbsAxis[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, Speed_2[1], Speed_2[0], Start_ACC[0], AbsAxis[3], AbsAxis[2], AbsAxis[1], AbsAxis[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 11);
}
}
else
MessageBox.Show("Valor para controle inválido");
}
catch
{
Console.WriteLine("Erro ao definir controle AbsAxis");
}
}
}
catch
{
Console.WriteLine("Erro ao controlar motor de passo");
}
}
if (DataSended == 14) //(14 calibrar codificador)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
/*
if (DataSended == 15) //(15 tipo de motor - confirmar xx)
{
Text_BUF = comboBox6.Text;
if (Text_BUF == Mot_18)
{
tCHK = Addr + data + byte_data[1];
Buffer = new byte[] { Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
}
else if (Text_BUF == Mot_09)
{
tCHK = Addr + data + byte_data[0];
Buffer = new byte[] { Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
}
}
*/
if (DataSended == 16) //(16 modo de operação - confirmar)
{
Text_BUF = cmbModoControle.Text;
if (Text_BUF == ModosControle[0])
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == ModosControle[1])
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == ModosControle[2])
{
tCHK = 0xFA + Addr + data + byte_data[2];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[2], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == ModosControle[3])
{
tCHK = 0xFA + Addr + data + byte_data[3];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[3], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == ModosControle[4])
{
tCHK = 0xFA + Addr + data + byte_data[4];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[4], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == ModosControle[5])
{
tCHK = 0xFA + Addr + data + byte_data[5];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[5], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}
if (DataSended == 17) //(17 valor de corrente (mA) - confirmar)
{
//-------------------Determinação do tipo de motor--------------------
tCHK = 0xFA + Addr + 0x40;
Buffer = new byte[] { 0xFA, Addr, 0x40, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
await Task.Delay(50);
//---------------------------------------------------
try
{
CurrentText = Convert.ToUInt16(cmbCorrenteMaxima.Text, 10);
Current = BitConverter.GetBytes(CurrentText);
if (CurrentText <= Max_Current && CurrentText >= 0)
{
tCHK = 0xFA + Addr + data + Current[1] + Current[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, Current[1], Current[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 6);
}
else
MessageBox.Show("Corrente máxima deve estar entre 0 e " + Max_Current);
}
catch
{
Console.WriteLine("Erro ao salvar valor da corrente máxima");
}
}
/*if (DataSended == 18) //(18 configuração de habilitação - confirmar)
{
Text_BUF = GB3_comboBox_使能设置.Text;
if (Text_BUF == EN_H)
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == EN_L)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == EN_Hold)
{
tCHK = 0xFA + Addr + data + byte_data[2];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[2], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}
if (DataSended == 19) //(19 direção do motor - confirmar)
{
Text_BUF = GB3_comboBox_电机方向.Text;
if (Text_BUF == Dir_CW)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == Dir_CCW)
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}
if (DataSended == 20) //(20 desligamento automático da tela - confirmar)
{
Text_BUF = GB3_comboBox_自动熄屏.Text;
if (Text_BUF == Disable)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == Enable)
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}*/
if (DataSended == 21) //(21 proteção contra travamento - confirmar)
{
Text_BUF = cmbProtecao.Text;
if (Text_BUF == LimiteRetornos[0])
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == LimiteRetornos[1])
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}
if (DataSended == 22) //(22 interpolação de subdivisão - confirmar)
{
Text_BUF = Disable;
if (Text_BUF == Disable)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == Enable)
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}
if (DataSended == 23) //(23 taxa de baud da porta serial - confirmar)
{
Text_BUF = cmbUartBaud.Text;
if (Text_BUF == UartBaud[0]) //9600
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == UartBaud[1]) //19200
{
tCHK = 0xFA + Addr + data + byte_data[2];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[2], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == UartBaud[2]) //25000
{
tCHK = 0xFA + Addr + data + byte_data[3];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[3], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == UartBaud[3]) //38400
{
tCHK = 0xFA + Addr + data + byte_data[4];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[4], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == UartBaud[4]) //57600
{
tCHK = 0xFA + Addr + data + byte_data[5];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[5], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == UartBaud[5]) //115200
{
tCHK = 0xFA + Addr + data + byte_data[6];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[6], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == UartBaud[6]) //256000
{
tCHK = 0xFA + Addr + data + byte_data[7];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[7], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}
if (DataSended == 24) //(24 endereço de comunicação do motor - confirmar)
{
try
{
UartAddrText = Convert.ToByte(cmbUartAddr.Text, 16);
if (UartAddrText <= 0xff && UartAddrText >= 0x01)
{
tCHK = 0xFA + Addr + data + UartAddrText;
Buffer = new byte[] { 0xFA, Addr, (byte)data, UartAddrText, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else
MessageBox.Show("Endereço deve estar entre 0x01 e 0xff");
}
catch
{
Console.WriteLine("Erro ao definir endereço");
}
}
/*
if (DataSended == 25) //(25 Confirmar posição Kp)
{
KpText = Convert.ToUInt16(comboBox16.Text, 10);
Kp = BitConverter.GetBytes(KpText);
if (KpText < 65535 && KpText >= 0)
{
tCHK = Addr + data + Kp[1] + Kp[0];
Buffer = new byte[] { Addr, (byte)data, Kp[1], Kp[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else
{
MessageBox.Show(Text2_Geral, Text2_janela);
}
}
if (DataSended == 26) //(26 Confirmar posição Ki)
{
KiText = Convert.ToUInt16(comboBox17.Text, 10);
Ki = BitConverter.GetBytes(KiText);
if (KiText < 65535 && KiText >= 0)
{
tCHK = Addr + data + Ki[1] + Ki[0];
Buffer = new byte[] { Addr, (byte)data, Ki[1], Ki[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else
{
MessageBox.Show(Text2_Geral, Text2_janela);
}
}
if (DataSended == 27) //(27 Confirmar posição Kd)
{
KdText = Convert.ToUInt16(comboBox18.Text, 10);
Kd = BitConverter.GetBytes(KdText);
if (KdText < 65535 && KdText >= 0)
{
tCHK = Addr + data + Kd[1] + Kd[0];
Buffer = new byte[] { Addr, (byte)data, Kd[1], Kd[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else
{
MessageBox.Show(Text2_Geral, Text2_janela);
}
}*/
if (DataSended == 28) //(28 Confirmar aceleração inicial)
{
try
{
Start_ACCText = Convert.ToUInt16(cmbRampaInicio.Text, 10);
if (Start_ACCText <= 255 && Start_ACCText >= 0)
{
Start_ACC = BitConverter.GetBytes(Start_ACCText);
try
{
Temp1++;
}
catch
{
Temp1 = 0;
}
}
else
{
MessageBox.Show("O valor da rampa deve estar entre 0 e 255");
}
}
catch
{
MessageBox.Show("Erro ao definir rampa de início");
}
}
if (DataSended == 29) //(29 Confirmar aceleração de parada)
{
try
{
Stop_ACCText = Convert.ToUInt16(cmbRampaParada.Text, 10);
if (Stop_ACCText <= 255 && Stop_ACCText >= 0)
{
Stop_ACC = BitConverter.GetBytes(Stop_ACCText);
try
{
Temp1++;
}
catch
{
Temp1 = 0;
}
}
else
{
MessageBox.Show("O valor da rampa deve estar entre 0 e 255");
}
}
catch
{
MessageBox.Show("Erro ao definir rampa de parada");
}
}
/*
if (DataSended == 30) //(30 Ativar modo de retorno à origem)
{
if (radioButton7.Checked)
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (radioButton8.Checked)
{
tCHK = 0xFA + Addr + data + byte_data[2];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[2], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else
{
MessageBox.Show(Text2_Geral, Text2_janela);
}
}
*/
if (DataSended == 31) //(31 Parâmetros de limite)
{
//-------------------Verificar tipo de motor--------------------
tCHK = 0xFA + Addr + 0x40;
Buffer = new byte[] { 0xFA, Addr, 0x40, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
await Task.Delay(50);
//---------------------------------------------------
try
{
//Nível de gatilho
Text_BUF = "Baixo";
if (Text_BUF == "Baixo")
{
HomeTrig = 0x00;
}
else if (Text_BUF == "Alto")
{
HomeTrig = 0x01;
}
//Direção de retorno à origem
Text_BUF = cmbDirecaoLimite.Text;
if (Text_BUF == LimiteDirecoes[0])
{
HomeDir = 0x00;
}
else if (Text_BUF == LimiteDirecoes[1])
{
HomeDir = 0x01;
}
//Habilitar retorno à origem
Text_BUF = cmbLimiteRetorno.Text;
if (Text_BUF == LimiteRetornos[0])
{
EndLimit = 0x00;
}
else if (Text_BUF == LimiteRetornos[1])
{
EndLimit = 0x01;
}
//Velocidade de retorno à origem
SpeedText = Convert.ToUInt16(cmbVelocidadeLimite.Text, 10);
Speed_1 = BitConverter.GetBytes(SpeedText);
if (FV1[2] == 0x03)
{
if (SpeedText <= 3000 && SpeedText >= 1)
{
tCHK = 0xFA + Addr + data + HomeTrig + HomeDir + Speed_1[1] + Speed_1[0] + EndLimit;
Buffer = new byte[] { 0xFA, Addr, (byte)data, HomeTrig, HomeDir, Speed_1[1], Speed_1[0], EndLimit, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 9);
}
else
MessageBox.Show("Limite de velocidade de retorno deve estar entre 1 e 3000");
}
else
{
if (SpeedText <= 3000 && SpeedText >= 1)
{
tCHK = 0xFA + Addr + data + HomeTrig + HomeDir + Speed_1[1] + Speed_1[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, HomeTrig, HomeDir, Speed_1[1], Speed_1[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 8);
}
else
MessageBox.Show("Limite de velocidade de retorno deve estar entre 1 e 3000");
}
//----
}
catch
{
MessageBox.Show("Erro ao definir limite");
}
}
if (DataSended == 32) //(32 Limite de retorno à origem)
{
tCHK = 0xFA + Addr + data;
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
}
if (DataSended == 33) //(33 Retorno à origem direto)
{
tCHK = 0xFA + Addr + data;
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
}
/*
if (DataSended == 34) //(34 Confirmar direção de retorno à origem)
{
if (radioButton10.Checked)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (radioButton9.Checked)
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else
{
MessageBox.Show(Text2_Geral, Text2_janela);
}
}
*/
if (DataSended == 35) //(35 Voltar ao ponto zero)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
if (DataSended == 36) //(36 Restaurar configurações de fábrica)
{
tCHK = 0xFA + Addr + data;
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
}
if (DataSended == 38) //(38 Parar modo de controle de posição do motor)
{
if (cmbModo.Text == ModosControlePosicao[0])
{
}
else if (cmbModo.Text == ModosControlePosicao[1])
{
data = 0xF4;
}
else if (cmbModo.Text == ModosControlePosicao[2])
{
data = 0xF5;
}
tCHK = 0xFA + Addr + data + 0x00 + 0x00 + Stop_ACC[0] + 0x00 + 0x00 + 0x00 + 0x00;
Buffer = new byte[] { 0xFA, Addr, (byte)data, 0x00, 0x00, Stop_ACC[0], 0x00, 0x00, 0x00, 0x00, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 11);
}
/*if (DataSended == 41) //(41 Resposta do escravo)
{
Text_BUF = GB3_comboBox_从机应答.Text;
if (Text_BUF == Desativar)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == Ativar)
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}
if (DataSended == 42) //(42 Grupo de escravos)
{
try
{
UartAddrText = Convert.ToByte(GB3_comboBox_从机分组.Text, 16);
if (UartAddrText <= 0xff && UartAddrText >= 0x01)
{
tCHK = 0xFA + Addr + data + UartAddrText;
Buffer = new byte[] { 0xFA, Addr, (byte)data, UartAddrText, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else
MessageBox.Show(Text1_UartAddrError, Text1_janela);
}
catch
{
MessageBox.Show(Text1_Geral, Text2_janela);
}
}
if (DataSended == 47) //(47 MODBUS)
{
Text_BUF = GB3_comboBox_MODBUS.Text;
if (Text_BUF == Desativar)
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == Ativar)
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}
if (DataSended == 48) //(48 Bloqueio de teclas)
{
Text_BUF = GB3_comboBox_按键锁定.Text;
if (Text_BUF == "Desbloquear")
{
tCHK = 0xFA + Addr + data + byte_data[0];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
else if (Text_BUF == "Bloquear")
{
tCHK = 0xFA + Addr + data + byte_data[1];
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 5);
}
}*/
if (DataSended == 49) //(49 Retorno único)
{
try
{
//Modo de retorno à origem
Text_BUF = cmbModoLimite.Text;
if (Text_BUF == LimiteModos[0])
{
Mode_0 = 0x00;
}
else if (Text_BUF == LimiteModos[1])
{
Mode_0 = 0x01;
}
else if (Text_BUF == LimiteModos[2])
{
Mode_0 = 0x02;
}
//Configurar zero
Text_BUF = cmbZeroLimite.Text;
if (Text_BUF == LimiteZeros[0])
{
Set_0 = 0x00;
}
else if (Text_BUF == LimiteZeros[1])
{
Set_0 = 0x01;
}
//Direção de retorno à origem
Text_BUF = cmbDirecaoLimite.Text;
if (Text_BUF == LimiteDirecoes[0])
{
Dir_0 = 0x00;
}
else if (Text_BUF == LimiteDirecoes[1])
{
Dir_0 = 0x01;
}
//Velocidade de retorno à origem
Speed_0 = Convert.ToByte(cmbVelocidadeLimite.Text, 10);
tCHK = 0xFA + Addr + data + Mode_0 + Set_0 + Speed_0 + Dir_0;
Buffer = new byte[] { 0xFA, Addr, (byte)data, Mode_0, Set_0, Speed_0, Dir_0, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 8);
//----
}
catch
{
MessageBox.Show("Erro ao gravar parametros de limite");
}
}
if (DataSended == 91) //(91 Go Home)
{
tCHK = 0xFA + Addr + data;
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
WriteByteToSerialPort(Buffer, 0, 4);
}
}
else
MessageBox.Show("Endereço selecionado é inválido");
Console.WriteLine("Terminou o envio");
}
private void txtValor_TextChanged(object sender, EventArgs e)
{
double reducao = 20.0;
int.TryParse(txtValor.Text, out int valor);
double angulo = 0;
int val = 0;
if (cmbModo.Text == ModosControlePosicao[0])
{
int.TryParse(cmbMStep.Text, out int mstep);
if (cmbMStep.Text == "") mstep = 16;
double pulsos = mstep * 200;
double relacao = (pulsos * reducao) / 360.0;
angulo = valor / relacao;
val = Convert.ToInt32(valor * relacao);
}
else
{
angulo = valor / reducao;
val = Convert.ToInt32(valor * reducao);
}
lblAngulo.Text = val.ToString();
}
private void cmbEndereco_SelectedIndexChanged(object sender, EventArgs e)
{
_EnderecoControlar = cmbEndereco.Text;
}
private void btnEntradas_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "46";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void Text_display()
{
if (txtErroCarregado.InvokeRequired)
{
txtErroCarregado.Invoke(new Action(Text_display));
return;
}
rxDisplay(); //计算rCHK
if ((byte)rCHK == SerialBuffer_RX[Data_Number - 1])
{
switch (SerialBuffer_RX[2])
{
case 0x30: // 0 Encoder de valor em modo posicional FB + 01 + 30 + int32_t valor posicional + uint16_t valor do encoder + CRC
if (rdbHex.Checked) // Hexadecimal
{
txtErroCarregado.Clear();
txtErroCarregado.AppendText("0x");
for (int a = 3; a < 9; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
txtErroCarregado.AppendText(str.Length == 1 ? "0" + str : str);
}
}
else if (rdbDecimal.Checked) // Decimal
{
txtErroCarregado.Clear();
word32 = "0";
for (int a = 3; a < 7; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
word32 += str.Length == 1 ? "0" + str : str;
}
data32 = Convert.ToInt32(word32, 16);
word16 = "0";
for (int a = 7; a < 9; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
word16 += str.Length == 1 ? "0" + str : str;
}
data16 = Convert.ToInt16(word16, 16);
str = Convert.ToString(data32 * 360 + data16 * 360 / 16384, 10);
txtErroCarregado.AppendText(str);
}
else
{
MessageBox.Show("Erro ao ler dados de erro"); // Erro de dados
}
break;
case 0x33: // 1 Contagem acumulada de pulsos FB + 01 + 33 + int32_t contagem acumulada de pulsos + CRC
if (rdbHex.Checked) // Hexadecimal
{
txtNumeroPulsos.Clear();
txtNumeroPulsos.AppendText("0x");
for (int a = 3; a < 7; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
txtNumeroPulsos.AppendText(str.Length == 1 ? "0" + str : str);
}
}
else if (rdbDecimal.Checked) // Decimal
{
txtNumeroPulsos.Clear();
word32 = "0";
for (int a = 3; a < 7; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
word32 += str.Length == 1 ? "0" + str : str;
}
data32 = Convert.ToInt32(word32, 16);
str = Convert.ToString(data32, 10);
txtNumeroPulsos.AppendText(str);
txtAnguloAtual.Text = Math.Round(MKS057DService.PulsosParaAngulo(Convert.ToInt32(txtNumeroPulsos.Text)), 2).ToString();
}
else
{
MessageBox.Show("Erro ao ler dados de pulsos"); // Erro de dados
}
break;
case 0x39: // 2 Erro de ângulo de posição FB + 01 + 39 + int32_t erro de ângulo de posição + CRC
if (rdbHex.Checked) // Hexadecimal
{
txtErroAngulo.Clear();
txtErroAngulo.AppendText("0x");
for (int a = 3; a < 7; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
txtErroAngulo.AppendText(str.Length == 1 ? "0" + str : str);
}
}
else if (rdbDecimal.Checked) // Decimal
{
txtErroAngulo.Clear();
word32 = "0";
for (int a = 3; a < 7; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
word32 += str.Length == 1 ? "0" + str : str;
}
data32 = Convert.ToInt32(word32, 16);
str = Convert.ToString(data32, 10);
txtErroAngulo.AppendText(str);
}
else
{
MessageBox.Show("Erro ao ler dados de erro de angulo"); // Erro de dados
}
break;
case 0x3A: // 3 Estado de habilitação da placa de acionamento FB + 01 + 3A + uint8_t estado de habilitação do loop fechado da placa de acionamento + CRC
// Habilitado: 01
// Desabilitado: 00
if (SerialBuffer_RX[3] == EN_STATE_ON)
{
txtDriverHabilitado.Clear();
txtDriverHabilitado.AppendText(Text1_EN); // Texto1 de habilitação
}
else if (SerialBuffer_RX[3] == EN_STATE_OFF)
{
txtDriverHabilitado.Clear();
txtDriverHabilitado.AppendText(Text2_EN); // Texto2 de desabilitação
}
else
{
MessageBox.Show("Erro ao ler dados de driver habilitado"); // Erro de dados
}
break;
case 0x3B: // 4 Estado de retorno automático para a posição inicial após ligar FB + 01 + 3B + uint8_t valor de estado de retorno para a posição inicial + CRC
// Executando retorno para a posição inicial: 00
// Retorno para a posição inicial concluído: 01
// Falha ao retornar para a posição inicial: 02
if (SerialBuffer_RX[3] == 0x00)
{
txtResetZero.Clear();
txtResetZero.AppendText(Text1_Zero); // Texto1 de retorno para zero
}
else if (SerialBuffer_RX[3] == 0x01)
{
txtResetZero.Clear();
txtResetZero.AppendText(Text2_Zero); // Texto2 de retorno para zero
}
else if (SerialBuffer_RX[3] == 0x02)
{
txtResetZero.Clear();
txtResetZero.AppendText(Text3_Zero); // Texto3 de retorno para zero
}
break;
case 0x3E: // 5 Sinal de bloqueio do motor FB + 01 + 3E + uint8_t sinal de bloqueio + CRC
// Bloqueado: 01
// Não bloqueado: 00
if (SerialBuffer_RX[3] == 0x01)
{
txtBloqueado.Clear();
txtBloqueado.AppendText(Text1_Stall); // Texto1 de bloqueio
}
else if (SerialBuffer_RX[3] == 0x00)
{
txtBloqueado.Clear();
txtBloqueado.AppendText(Text2_Stall); // Texto2 de bloqueio
}
break;
case 0x3D: // 37 Status de desbloqueio
// Desbloqueio bem-sucedido: retorna FB 01 3D 01 3A
// Falha no desbloqueio: retorna FB 01 3D 00 39
if (SerialBuffer_RX[3] == 0x01)
{
MessageBox.Show(Text1_Block, Text1_Block); // Texto1 de bloqueio
}
else if (SerialBuffer_RX[3] == 0x00)
{
MessageBox.Show(Text2_Block, Text2_Block); // Texto2 de bloqueio
}
break;
case 0xF6: // 8 Início do controle de velocidade & 9 Parada do controle de velocidade
if (DataSended == 8)
{
txtStatus.Clear();
if (SerialBuffer_RX[3] == 0x01) // Sucesso
{
txtStatus.AppendText(Text1_Move); // Texto1 de movimento
}
else if (SerialBuffer_RX[3] == 0x00) // Falha
{
txtStatus.AppendText(Text3_Move); // Texto3 de movimento
break;
}
else
{
txtStatus.AppendText(Text1_COM); // Texto1 de erro de comunicação
break;
}
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
if (rdbHorarioPosicao.Checked) // Direção positiva
{
txtDirecao.AppendText(Text1_Dir); // Texto1 de direção
}
else if (rdbAntihorarioPosicao.Checked) // Direção negativa
{
txtDirecao.AppendText(Text2_Dir); // Texto2 de direção
}
txtVelocidade.AppendText(cmbVelocidadePosicao.Text); // Velocidade alvo
txtAceleracao.AppendText(Start_ACC[0].ToString()); // Aceleração alvo
}
else if (DataSended == 9)
{
txtStatus.Clear();
if (SerialBuffer_RX[3] == 0x02) // Concluído
{
txtStatus.AppendText(Text2_Stop); // Texto2 de parada
}
else if (SerialBuffer_RX[3] == 0x01) // Iniciado
{
txtStatus.AppendText(Text4_Stop); // Texto4 de parada
}
else if (SerialBuffer_RX[3] == 0x00) // Falha
{
txtStatus.AppendText(Text3_Stop); // Texto3 de parada
break;
}
else
{
txtStatus.AppendText(Text1_COM); // Texto1 de erro de comunicação
break;
}
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
txtDirecao.AppendText(Text3_Dir); // Texto3 de direção
txtVelocidade.AppendText("0"); // Velocidade alvo zero
txtAceleracao.AppendText(Stop_ACC[0].ToString()); // Aceleração alvo de parada
}
break;
case 0xFD: // 13 Início do controle de posição & 38 Parada do controle de posição
txtStatus.Clear();
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
if (DataSended != 38)
{
if (SerialBuffer_RX[3] == 0x02) // Concluído
{
txtStatus.AppendText(Text2_Move); // Texto2 de movimento
break;
}
else if (SerialBuffer_RX[3] == 0x01) // Iniciado
{
txtStatus.AppendText(Text4_Move); // Texto4 de movimento
}
else if (SerialBuffer_RX[3] == 0x00) // Falha
{
txtStatus.AppendText(Text3_Move); // Texto3 de movimento
break;
}
else
{
txtStatus.AppendText(Text1_COM); // Texto1 de erro de comunicação
break;
}
if (rdbHorarioPosicao.Checked) // Direção positiva
{
txtDirecao.AppendText(Text1_Dir); // Texto1 de direção
}
else if (rdbAntihorarioPosicao.Checked) // Direção negativa
{
txtDirecao.AppendText(Text2_Dir); // Texto2 de direção
}
txtVelocidade.AppendText(cmbVelocidadePosicao.Text); // Velocidade alvo
txtAceleracao.AppendText(Start_ACC[0].ToString()); // Aceleração alvo
}
else if (DataSended == 38)
{
if (SerialBuffer_RX[3] == 0x02) // Concluído
{
txtStatus.AppendText(Text2_Stop); // Texto2 de parada
break;
}
else if (SerialBuffer_RX[3] == 0x01) // Iniciado
{
txtStatus.AppendText(Text4_Stop); // Texto4 de parada
}
else if (SerialBuffer_RX[3] == 0x00) // Falha
{
txtStatus.AppendText(Text3_Stop); // Texto3 de parada
break;
}
else
{
txtStatus.AppendText(Text1_COM); // Texto1 de erro de comunicação
break;
}
txtDirecao.AppendText(Text3_Dir); // Texto3 de direção
txtVelocidade.AppendText("0"); // Velocidade alvo zero
txtAceleracao.AppendText(Stop_ACC[0].ToString()); // Aceleração alvo de parada
}
break;
case 0xF4: // 44 Coordenadas Relativas & 38 Controle de Parada de Posição
txtStatus.Clear();
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
if (DataSended != 38)
{
if (SerialBuffer_RX[3] == 0x02) // Completo
{
txtStatus.AppendText(Text2_Move);
break;
}
else if (SerialBuffer_RX[3] == 0x01) // Iniciar
{
txtStatus.AppendText(Text4_Move);
}
else if (SerialBuffer_RX[3] == 0x00) // Falha
{
txtStatus.AppendText(Text3_Move);
break;
}
else
{
txtStatus.AppendText(Text1_COM);
break;
}
txtVelocidade.AppendText(cmbVelocidadePosicao.Text);
txtAceleracao.AppendText(Start_ACC[0].ToString());
}
else if (DataSended == 38)
{
if (SerialBuffer_RX[3] == 0x02) // Completo
{
txtStatus.AppendText(Text2_Stop);
break;
}
else if (SerialBuffer_RX[3] == 0x01) // Iniciar
{
txtStatus.AppendText(Text4_Stop);
}
else if (SerialBuffer_RX[3] == 0x00) // Falha
{
txtStatus.AppendText(Text3_Stop);
break;
}
else
{
txtStatus.AppendText(Text1_COM);
break;
}
txtDirecao.AppendText(Text3_Dir);
txtVelocidade.AppendText("0");
txtAceleracao.AppendText(Stop_ACC[0].ToString());
}
break;
case 0xF5: // 45 Coordenadas Absolutas & 38 Controle de Parada de Posição
txtStatus.Clear();
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
if (DataSended != 38)
{
if (SerialBuffer_RX[3] == 0x02) // Completo
{
txtStatus.AppendText(Text2_Move);
break;
}
else if (SerialBuffer_RX[3] == 0x01) // Iniciar
{
txtStatus.AppendText(Text4_Move);
}
else if (SerialBuffer_RX[3] == 0x00) // Falha
{
txtStatus.AppendText(Text3_Move);
break;
}
else
{
txtStatus.AppendText(Text1_COM);
break;
}
txtVelocidade.AppendText(cmbVelocidadePosicao.Text);
txtAceleracao.AppendText(Start_ACC[0].ToString());
}
else if (DataSended == 38)
{
if (SerialBuffer_RX[3] == 0x02) // Completo
{
txtStatus.AppendText(Text2_Stop);
break;
}
else if (SerialBuffer_RX[3] == 0x01) // Iniciar
{
txtStatus.AppendText(Text4_Stop);
}
else if (SerialBuffer_RX[3] == 0x00) // Falha
{
txtStatus.AppendText(Text3_Stop);
break;
}
else
{
txtStatus.AppendText(Text1_COM);
break;
}
txtDirecao.AppendText(Text3_Dir);
txtVelocidade.AppendText("0");
txtAceleracao.AppendText(Stop_ACC[0].ToString());
}
break;
case 0x31:// 39 Valor do Codificador Incremental FB + 01 + 31 + Valor do Codificador uint48_t + CRC
if (rdbHex.Checked) // Hexadecimal
{
txtErroCarregado.Clear();
txtErroCarregado.AppendText("0x");
for (int a = 3; a < 9; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
txtErroCarregado.AppendText(str.Length == 1 ? "0" + str : str);
}
}
else if (rdbDecimal.Checked) // Decimal
{
txtErroCarregado.Clear();
word64 = "0";
for (int a = 3; a < 9; a++)
{
if (a == 3 && SerialBuffer_RX[3] >= 0x80)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
word64 = "FFFF" + str;
}
else
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
word64 += str.Length == 1 ? "0" + str : str;
}
}
data64 = Convert.ToInt64(word64, 16);
str = Convert.ToString(data64 * 360 / 16384, 10);
txtErroCarregado.AppendText(str);
}
else
{
MessageBox.Show(Text1_DataError, Text2_window);
}
break;
case 0x32:// 40 Velocidade Atual do Motor
if (rdbHex.Checked) // Hexadecimal
{
txtRPM.Clear();
txtRPM.AppendText("0x");
for (int a = 3; a < 5; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
txtRPM.AppendText(str.Length == 1 ? "0" + str : str);
}
}
else if (rdbDecimal.Checked) // Decimal
{
txtRPM.Clear();
word16 = "0";
for (int a = 3; a < 5; a++)
{
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
word16 += str.Length == 1 ? "0" + str : str;
}
data16 = Convert.ToInt16(word16, 16);
str = Convert.ToString(data16, 10);
txtRPM.AppendText(str);
}
else
{
MessageBox.Show(Text1_DataError, Text2_window);
}
break;
case 0x80:// 14 Calibrar Codificador
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
txtStatus.Clear();
if (SerialBuffer_RX[3] == 0x00)
{
txtStatus.AppendText(Text1_Cal);
}
else if (SerialBuffer_RX[3] == 0x01)
{
txtStatus.AppendText(Text2_Cal);
}
else if (SerialBuffer_RX[3] == 0x02)
{
txtStatus.AppendText(Text3_Cal);
}
break;
case 0x3F:// 36 Restaurar Configurações de Fábrica
case 0x82:// 16 Modo de Trabalho
case 0x83:// 17 Valor de Corrente
case 0x84:// 12 Configuração de Subdivisão
case 0x85:// 18 Configuração de Habilitação
case 0x86:// 19 Direção do Motor
case 0x87:// 20 Desligamento Automático da Tela
case 0x88:// 21 Proteção de Bloqueio
case 0x89:// 22 Interpolação de Subdivisão
case 0x8A:// 23 Taxa de Baud da Porta Serial
case 0x8B:// 24 Endereço de Comunicação do Motor
case 0x8C:// 41 Resposta do Dispositivo Escravo
case 0x8D:// 42 Grupo do Dispositivo Escravo
case 0x90:// 31 Parâmetros de Limite
case 0xF3:// 6 Habilitar Placa de Acionamento & 7 Desligar Placa de Acionamento
case 0xFF:// 10 Iniciar Execução Automática na Inicialização & 11 Parar Execução Automática na Inicialização
case 0x8E:// 47 Confirmação MODBUS
case 0x8F:// 48 Bloqueio de Teclas - Confirmação
case 0x9A:// 49 Retorno de uma Volta
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
txtStatus.Clear();
try
{
Temp1++;
if (SerialBuffer_RX[3] == 0x00)
{
txtStatus.AppendText(Text2_RX + "(" + Temp1 + ")");
}
else if (SerialBuffer_RX[3] == 0x01)
{
txtStatus.AppendText(Text1_RX + "(" + Temp1 + ")");
}
}
catch
{
Temp1 = 0;
}
break;
case 0x91:// 32 Reiniciar Limites
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
txtStatus.Clear();
if (SerialBuffer_RX[3] == 0x00)
{
txtStatus.AppendText(Text3_Zero);
}
else if (SerialBuffer_RX[3] == 0x01)
{
txtStatus.AppendText(Text1_Zero);
}
else if (SerialBuffer_RX[3] == 0x02)
{
txtStatus.AppendText(Text2_Zero);
}
break;
case 0x92:// 33 Reinicialização Direta
txtDirecao.Clear();
txtVelocidade.Clear();
txtAceleracao.Clear();
txtStatus.Clear();
if (SerialBuffer_RX[3] == 0x00)
{
txtStatus.AppendText(Text3_Zero);
}
else if (SerialBuffer_RX[3] == 0x01)
{
txtStatus.AppendText(Text2_Zero);
}
break;
case 0x40:// 43 Informação de Versão
try
{
int idx = SerialBuffer_RX[3] < 9 ? SerialBuffer_RX[3] : 22 - SerialBuffer_RX[3];
HV = HardVersion[idx];
FV = "V" + SerialBuffer_RX[4] + "." + SerialBuffer_RX[5] + "." + SerialBuffer_RX[6];
for (int a = 0; a < 3; a++)
{
FV1[a] = SerialBuffer_RX[a + 4];
}
if (DataSended == 43)
{
MessageBox.Show(Text_HardVer + ": " + HV + "\n" + Text_FirmVer + ": " + FV, "Versão");
DataSended = 0;
}
if (SerialBuffer_RX[3] == 1 || SerialBuffer_RX[3] == 2)
{
Max_Current = 3000;
//Text_CurrentError = Text_CurrentError42D;
cmbCorrenteMaxima.Items.Clear();
cmbCorrenteMaxima.Items.AddRange(CurrentText_42D);
}
else if (SerialBuffer_RX[3] == 3 || SerialBuffer_RX[3] == 4)
{
Max_Current = 5200;
//Text_CurrentError = Text_CurrentError57D;
cmbCorrenteMaxima.Items.Clear();
cmbCorrenteMaxima.Items.AddRange(CurrentText_57D);
}
else
{
Max_Current = 3000;
//Text_CurrentError = Text_CurrentError42D;
cmbCorrenteMaxima.Items.Clear();
cmbCorrenteMaxima.Items.AddRange(CurrentText_42D);
}
}
catch
{
MessageBox.Show(Text1_window, Text2_window);
}
break;
case 0x34:// 46 Estado do Portão IO
//GB5_textBox_IN1.Clear();
//GB5_textBox_IN2.Clear();
//GB5_textBox_OUT1.Clear();
//GB5_textBox_OUT2.Clear();
byte[] IO = new byte[1];
IO[0] = SerialBuffer_RX[3];
BitArray LimitIO = new BitArray(IO);
if (HV == HardVersion[3] || HV == HardVersion[4])
{
chbIN1.Checked = LimitIO.Get(0);
txtSensor.Text = LimitIO.Get(0) ? "HIGH" : "LOW";
chbIN2.Checked = LimitIO.Get(1);
//GB5_textBox_OUT1.AppendText(LimitIO.Get(2) ? "H" : "L");
//GB5_textBox_OUT2.AppendText(LimitIO.Get(3) ? "H" : "L");
}
else if (HV == HardVersion[1] || HV == HardVersion[2])
{
chbIN1.Checked = LimitIO.Get(0);
txtSensor.Text = LimitIO.Get(0) ? "HIGH" : "LOW";
//GB5_textBox_IN2.AppendText("NC");
//GB5_textBox_OUT1.AppendText("NC");
//GB5_textBox_OUT2.AppendText("NC");
}
break;
default:
MessageBox.Show(Text1_window, Text2_window);
break;
}
}
}
private void rxDisplay()
{
rCHK = 0x00;
Console.Write("RX: ");
for (int a = 0; a < Data_Number - 1; a++)
{
rCHK += SerialBuffer_RX[a];
Console.Write("{0:X2} ", SerialBuffer_RX[a]);
}
Console.WriteLine("{0:X2} rCHK: {1:X2} Length: {2}", SerialBuffer_RX[Data_Number - 1], (byte)rCHK, Data_Number);
}
private async void btnIniciarRef_Click(object sender, EventArgs e)
{
await ReferenciaMotor();
}
private void txDisplay()
{
Console.Write("TX: ");
for (int a = 0; a < Buffer.Length; a++)
{
Console.Write("{0:X2} ", Buffer[a]);
}
Console.WriteLine("Length: {0}", Buffer.Length);
}
private async Task ReferenciaMotor()
{
byte Addr = Convert.ToByte(cmbEndereco.Text, 16);
btnEntradas_Click(btnEntradas, new EventArgs());
await Task.Delay(1000);
btnZero_Click(btnZero, new EventArgs());
await Task.Delay(1000);
btnNumeroPulsos_Click(btnNumeroPulsos, new EventArgs());
await Task.Delay(1000);
bool Sucesso = ReferenciaEstaEmZero(Addr);
double Angulo = Convert.ToDouble(txtAnguloAtual.Text);
double _anguloAnterior = Angulo;
int _angulo = 45;
int _offset = 0;
Sentido _sentido = Sentido.Horario;
int tentativas = 0;
const int MaxTentativas = 10;
if (!Sucesso)
{
while (!Sucesso && tentativas < MaxTentativas)
{
cmbVelocidadePosicao.SelectedIndex = 2;
cmbModo.SelectedIndex = 2;
txtValor.Text = _angulo.ToString();
btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
DateTime Inicio = DateTime.Now;
bool passou = false;
while (!Sucesso && !passou && Inicio.AddSeconds(40) > DateTime.Now)
{
Sucesso = ReferenciaEstaEmZero(Addr);
passou = ((Angulo >= (_angulo - 1) && _sentido == Sentido.Horario) || (Angulo <= (_angulo + 1) && _sentido == Sentido.Antihorario));
Console.WriteLine($"Ref {Addr}: Angulo SP = {_angulo}, Angulo Atual = {Angulo}, Sentido SP = {_sentido.ToString()}, Passou = {passou}, Sucesso = {Sucesso}");
if (Sucesso)
{
btnPararPosicao_Click(btnPararPosicao, new EventArgs());
await Task.Delay(500);
btnZero_Click(btnZero, new EventArgs());
await Task.Delay(500);
_angulo = 0;
cmbVelocidadePosicao.SelectedIndex = 1;
txtValor.Text = _angulo.ToString();
//btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
//await Task.Delay(500);
int _anguloRetorno = _sentido == Sentido.Horario ? -8 : 8;
txtValor.Text = _anguloRetorno.ToString();
btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
await Task.Delay(1000);
btnZero_Click(btnZero, new EventArgs());
await Task.Delay(500);
_angulo = 0;
txtValor.Text = _angulo.ToString();
//btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
//await Task.Delay(500);
break;
}
btnEntradas_Click(btnEntradas, new EventArgs());
await Task.Delay(500);
btnNumeroPulsos_Click(btnNumeroPulsos, new EventArgs());
await Task.Delay(500);
Angulo = Convert.ToDouble(txtAnguloAtual.Text);
await Task.Delay(100); // Verificações rápidas.
if (_anguloAnterior == Angulo)
{
btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
}
_anguloAnterior = Angulo;
}
// Alterna sentido ou ajusta o ângulo se falhar.
if (!Sucesso && passou)
{
_sentido = _sentido == Sentido.Horario ? Sentido.Antihorario : Sentido.Horario;
_offset += 25;
_angulo += _offset;
_angulo = _angulo * (_sentido == Sentido.Horario ? 1 : -1);
tentativas++;
txtValor.Text = _angulo.ToString();
txtAnguloSP.Text = txtValor.Text;
}
}
}
if (!Sucesso)
{
btnPararPosicao_Click(btnPararPosicao, new EventArgs());
}
}
private bool ReferenciaEstaEmZero(byte Addr)
{
return chbIN1.Checked;
}
}
}