Skip to content

ReadStruct returns no values for 4-Bool structure, direct Read works correctly #559

@GimmyZ98

Description

@GimmyZ98

I'm testing a program and trying to read a structure of 4 bools, and although I'm connected to the PLC and no errors are being thrown, the values of the tags are not actually being read. I tried adding a Read right after the ReadStruct, using the same tag, and with this second method I was able to read the tag’s value correctly. I can't "see" any errors within my program. I'm also sharing the code and two screenshots: one showing the contents of the DB in the PLC and one showing the form with the printout of the read values.

`

using S7.Net;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        static Plc plc = new Plc(CpuType.S71500, "192.168.100.170", 0, 1);

        public struct Test
        {
            public bool a { get; set; }
            public bool b { get; set; }
            public bool c { get; set; }
            public bool d { get; set; }
        }

        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
            this.FormClosed += Form1_FormClosed;
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                plc.Open();

                if (!plc.IsConnected)
                {
                    MessageBox.Show("Connessione al PLC fallita.");
                    return;
                }

                await StartReadingLoop();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Errore: " + ex.Message);
            }
        }

        private async Task StartReadingLoop()
        {
            while (plc.IsConnected)
            {
                try
                {
                    Test testData = new Test();

                    testData = (Test)plc.ReadStruct(typeof(Test), 193, 0);

                    _A1_Test.Text = $"A: {testData.a}";
                    _A2_Test.Text = $"A: {plc.Read("DB193.DBX0.0").ToString()}";                    
                }
                catch (Exception ex)
                {
                    MissioneAbortita.Text = ex.Message;
                    Console.WriteLine(ex.Message);
                }

                await Task.Delay(100);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (plc != null && plc.IsConnected)
            {
                plc.Close();
            }
        }
    }
}

`

Image Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions