public static tcFunctionResult tcWriteData(int index, object data) { if (!tcClient.IsConnected) { LogMessage(string.Format("Error\t: {0}", "Attempted to write to PLC when not connected")); return(tcFunctionResult.TC_NOT_CONNECTED); } if (index > tcVarList.Count || index < 0) { LogMessage(string.Format("Error\t: {0}", "Attempted to access a value outside the list")); return(tcFunctionResult.TC_VARLIST_OUTOFBOUND); } AdsStream _DataStrem = new AdsStream(tcVarList[index].DataSize); AdsBinaryWriter tcStreamWriter = new AdsBinaryWriter(_DataStrem); try { switch (tcVarList[index].VariableType.ToLower()) { case "bool": tcStreamWriter.Write((bool)data); tcClient.Write(tcVarList[index].Handle, _DataStrem); break; case "arbool": break; case "int": break; case "arint": break; case "string": break; case "real": break; case "lreal": break; } tcStreamWriter.Close(); } catch (Exception ex) { LogMessage(string.Format("Error at writing data {0}\t: {1}", index.ToString(), ex.Message)); return(tcFunctionResult.TC_FAIL_TO_WRITE_DATA); } finally { tcStreamWriter.Close(); } return(tcFunctionResult.TC_SUCCESS); }
private void buttonFalse_Click(object sender, RoutedEventArgs e) { using (var client = new TwinCAT.Ads.TcAdsClient()) { try { client.Connect(851); // creates a stream with a length of 4 byte AdsStream ds = new AdsStream(4); BinaryWriter bw = new BinaryWriter(ds); ds.Position = 0; bw.Write(Convert.ToInt32(textBox.Text)); // writes a DINT to PLC client.Write(0x4020, 0x0001, ds); //client.WriteSymbol("MyGVL.MyBoolVar", false, reloadSymbolInfo: true); client.WriteSymbol("P_Motion2.ati_xStart", false, reloadSymbolInfo: true); client.Dispose(); } catch (TwinCAT.Ads.AdsErrorException ex) { MessageBox.Show("PLC Control Error: \r\n\r\n" + ex.Message); } catch (System.FormatException ex) { textBoxPLCSetPosition.Text = "0"; MessageBox.Show("Invalid float value for Position. ErrMsg: \r\n\r\n" + ex.Message); } } }