Tag Archives: plc programming ladder logic

Click PLC System Hardware

Many people ask me what I do when looking at a new PLC model or system. My approach is very straight forward and we will view this in action with this Click PLC series. This series will go from examining the hardware to programming and communicating to the PLC in several ways. If you have questions along the way, please let me know. Keep on Reading!

Deploying an AdvancedHMI Project

Deploying an AdvancedHMI project on the industrial floor sounds like an easy task, but there are a few things that you should consider. The HMI (Human Machine Interface) user interface will run on a computer. The industrial environment is one in which temperature, dust, electrical noise, etc. are always present. This can also be combined with workers wanting to play with the new computer. We will look briefly at the hardware and software items that will make your install more reliable and user friendly in the field.
cloud-37011_640-min

Hardware
The hardware that you deploy in the field should match the environment that you expect it to work in. Computers come in many shapes, sizes and price points. Here are a few items that you may want to consider.
thermometer-934646_640-min

  • Fanless Computer – This will keep the dust out but temperature may be a problem.
  • Monitor – Location and type – Do you need touch screen?
    Keyboard and mouse – Washable?
  • Enclosures – If you are in a wash down environment then an enclosure is a necessity. Sometimes these enclosures are worth more than the contents in them.
  • UPS – The uninterruptable power supply will usually serve two purposes. It will act when power is removed so the computer will be able to shutdown correctly. The UPS will usually also act as a power conditioner. Most power has surges on the line and this can be amplified when in the industrial environment. The surge suppressors in the UPS will protect the computer.
  • Program backup – Have multiple copies of the software saved in different places. You never know when the unexpected will happen. (Fire / Thief etc.) This includes the backup disks for your operating system as well as the programs (versions) that you are running on the computer. (AdvancedHMI, Visual Studio)
  • Documentation of the backup (Hardware / Software) – Ensure that you have documentation of the hardware and software versions that you are using. I would also include where everything was purchased. This way if records are missing we can track this down through the supplier.

Software
The software that we have on the production floor should be robust. This means that we should know what happens if thing go wrong. Backups as mentioned above should happen on a regular basis. Memory is inexpensive so backup your files regularly. We usually use a networked computer to automatically back up the production files each day. The following is a list of items that you should pay attention to when deploying a computer on the production environment.

  • Turn off windows update – Windows is great at keeping itself up to date. However this can cause programs to stop working. When dealing with an AdvancedHMI deployment we set windows to ‘Download updates but let me choose whether to install them’. It can take several minutes for windows to update. You want to be sure that the machine being controlled will not be affected.
    AdvancedHMI Deployment 010-min
  • Security – Set permissions – When setting up your windows computer for the factory floor, do not give the account that boots up and logs on automatically Administrator Privileges. It should be set up as a Standard User. This will prevent unauthorized software being loaded onto the system.
    Internet Explorer comes standard on any new computer with windows 8.1 or older. No other browser is present out of the box. It is good to set a supervisor password on the internet connection. This will allow you to restrict the internet use.
    http://www.thewindowsclub.com/password-protect-the-use-of-internet-explorer
    On the run prompt type: RunDll32.exe msrating.dll,RatingSetupUI
    Goto the General tab to select a supervisor password
    AdvancedHMI Deployment 020-min AdvancedHMI Deployment 025-min
  • AdvancedHMI – There are a few thing that we can do in the AdvancedHMI project. We will look at the AdvancedHMI project that we did for Creating a HMI Login Screen on AdvancedHMI.
    AdvancedHMI Deployment 060-min
    o ControlBox – Remove the ControlBox on the main screen form. This will ensure that the user cannot minimize, maximize or close the application.
    AdvancedHMI Deployment 030-min
    o Maximize for screen size – Make the main screen form maximized so it will fill the entire screen.
    AdvancedHMI Deployment 040-min
    o Form.TopMost = True – This command will ensure that your application will be on top of all other windows forms.
    AdvancedHMI Deployment 050-min
    In this example the calculator has focus, but the our windows form will always be on top.
    AdvancedHMI Deployment 055-min
    If you have only one form then you can use the Properties settings for the form you always want on top. Multiple pages will have to include some additional programming to ensure that they are on top and visible.
    Here is the code for the returning to the main form of the program.
Private Sub ReturnToMainButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
    Me.TopMost = False
   MainForm.Show()
    MainForm.TopMost = True
    Me.Hide()
End Sub
  • Shortcut on the desktop – Place a shortcut to the AdvancedHMI application on the desktop. This will allow someone to quickly start the application if the application unexpectedly closes.

Following the above recommendations will ensure that your computer will perform and last as expected on the factory floor. Your AdvancedHMI project will work reliable and efficiently.

If you would like a copy of the PLC and AdvancedHMI programs, please contact me and I would be happy to send them to you.

Watch on YouTube : Deploying an AdvancedHMI Project
If you have any questions or need further information please contact me.
Thank you,
Garry

Archie Jacobs from Manufacturing Automation, LLC  has another tip for disabling the windows error recovery on startup.
On the PC that will run AdvancedHMI, click the start button and type CMD to find the Command Prompt. Right Click on the command prompt and select Run As Administrator
Once the Command Prompt opens, type the following:
bcdedit /set {current} bootstatuspolicy ignoreallfailures
This will prevent problematic startup when the PC is not shut down properly as often happens in the industrial environment.




If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLC’s are not difficult to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimal, Hexadecimal, ASCII and Floating Point.

To get this free article, subscribe to my free email newsletter.


Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.




Modbus TCP Data Logging to Database

Using Visual Basic 2015 we will log three holding registers from the PLC along with time and date into a Microsoft Access Database. We will log every minute into the database with the information that we collect from the PLC via Modbus TCP (Ethernet). All code will be done and shown so you can implement this in your application with different parameters. The information collected in the database can then be distributed or analyzed in the future.ModbusTCP MSAccess 010-min

Visual Basic 2015 will be used with the EasyModbusTCP client/server library for .net. We will communicate to an Automation Direct – Do-More PLC. Using the free simulation software of the PLC Designer Software, we will retrieve three values of the Modbus Holding Registers using Modbus TCP. Once we have this information out of the programmable logic controller it will be placed in a Microsoft Access (2010) Database. This will be done by using a SQL command to insert the data.

Automation Direct has a powerful simulator with their Do-More PLC. The PLC software is available from Automation Direct as a free download.
http://support.automationdirect.com/products/domore.html

ModbusTCP MSAccess 040-min

We will start with the PLC program. The first  three holding registers will be used. That will be MHR1, MHR2 and MHR3 in the Do-More PLC. This will correspond to register numbers 40001, 40002 and 40003. The following is a table with all of the references for Modbus communications to the Do-More.

Coil/Register Numbers Data Addresses Type Do-More PLC Table Name
00001-09999 0000 to 270E Read-Write MC1 to MC1023 Discrete Output Coils
10001-19999 0000 to 270E Read-Only MI1 to MI1023 Discrete Input Contacts
30001-39999 0000 to 270E Read-Only MIR1 to MIR2047 Analog Input Registers
40001-49999 0000 to 270E Read-Write MHR1 to MHR2047 Analog Output Holding Registers

Note: The Do More PLC uses the Modbus area to communicate. This is because having direct access to the digital I/O can be dangerous when connected via Ethernet to the internet. Data must move in and out of this area via the PLC program.

Here is the PLC program that sets the three registers.
ModbusTCP MSAccess 050-min

The next thing to do is set up our Microsoft Access 2010 Database. Our database will be named ACC_Database and it will be located at the following location: “C:\AccLog”. We will have one table called ACC_Log. In the table we will have five fields; LogDate, LogTime, Register1, Register2, Register3.

ModbusTCP MSAccess 090-min
ModbusTCP MSAccess 100-min

Visual Basic 2015 is free and is part of Visual Studio 2015. It can be downloaded at the following location:
https://www.visualstudio.com/en-us/products/visual-studio-community-vs

ModbusTCP MSAccess 020-min

EasyModbusTCP is free software. It will be referenced in our visual basic program.  It can be downloaded from the following location:
https://sourceforge.net/projects/easymodbustcp/
After downloading you must extract the files.

ModbusTCP MSAccess 030-min

EasyModbusTCP is a Modbus TCP, Modbus UDP client/server library for .NET and Client library for JAVA. .NET (.dll) Client/Server also supports Modbus RTU. It supports the following function codes: – Read Coils (FC1)
– Read Discrete Inputs (FC2)
– Read Holding Registers (FC3)
– Read Input Registers (FC4)
– Write Single Coil (FC5)
– Write Single Register (FC6)
– Write Multiple Coils (FC15)
– Write Multiple Registers (FC16)
– Read/Write Multiple Registers (FC23)

Now we will call up visual studio and create our project. The first thing that we must do is reference our EasyModbus.dll file.
ModbusTCP MSAccess 110-min
ModbusTCP MSAccess 120-min

Our program will log the three registers based upon a timer function. When the time expires we will set the interval to 1 minute and call a subroutine (Button1). This subroutine will communicate to the PLC via Modbus TCP and get our three registers. It will then insert the data from the registers along with the time and date into an access database.

Here is what our visual basic form will look like:
ModbusTCP MSAccess 060-min

Here is the visual basic code for our project. We use the Imports command for the EasyModbusTCP namespacing.

Imports EasyModbus 'Import the EasyModbus 

Here is the part of the subroutine that will communicate to the PLC via the EasyModbusTCP, You will notice that we have used the ‘Try’ command on the ModbusClient.Connect() statement. This way we can track if we are communicating or not to the PLC.

Public Class Form1
  Private Sub Button1_Click() Handles Button1.Click
 'This subroutine will communicate using the EasyModbusTCP to the PLC
 'This will execute when the user clicks the button or at specific intervals from the Timer1
 Dim ComError = 0 'Set communication error flag to 0
 'Specify the IP Address and Port Number that we are connecting
 Dim ModbusClient As EasyModbus.ModbusClient = New EasyModbus.ModbusClient(TextBox1.Text, 502)
 Try
 ModbusClient.Connect() 'Connect to the PLC
 Catch ex As Exception 'What to do when an error occurs
 Label10.ForeColor = Color.Red
 Label10.Text = "Communication Error!"
 ComError = 1 'Set communication error flag to 1
 End Try
 If ComError = 0 Then 'Do the following when communication is OK
 Label10.ForeColor = Color.Black
 Label10.Text = "Logging..."
 Dim Registers As Integer() 'Where to store the information
 Registers = ModbusClient.ReadHoldingRegisters(0, 3) 'Read three registers starting at the first one
 Label1.Text = Registers(0) 'Value of MHR1
 Label2.Text = Registers(1) 'Value of MHR2
 Label3.Text = Registers(2) 'Value of MHR3
 ModbusClient.Disconnect() 'Disconnect from the PLC

Here is the code to open the database connection and insert the data into our ACC_Database file. We use the ‘Try’ command to ensure that if errors occur it will not stop our program. The connection string ( Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\AccLog\ACC_Database.accdb) may be different then yours. In order to get your connection string, please review the following from a previous post and search for connection string.

'Log values into an Access Database
 'We will use a SQL instruction to insert a record into the table
 Try
 Dim SQL As String 'SQL Command String
 Dim objCmd As New OleDb.OleDbCommand 'Command
 'Connection String to the Access Database
 Dim Con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\AccLog\ACC_Database.accdb")
 'SQL Statement - All values must be set for the table
 SQL = "INSERT INTO ACC_Log VALUES ('" & Now.ToString("yyyy/MM/dd") & "', '" & Now.ToString("hh:mm:ss") & "', '" & Registers(0) & "', '" & Registers(1) & "', '" & Registers(2) & "')"
 Con.Open() 'Open the database connection
 objCmd = New OleDb.OleDbCommand(SQL, Con) 'Set the command
 objCmd.ExecuteNonQuery() 'Execute the SQL command
 Con.Close() 'Close the database connection
 Catch ex As Exception 'What to do when an error occurs
 Label10.ForeColor = Color.Red
 Label10.Text = "Database Error!"
 End Try
 End If
 End Sub

This timer is originally set for 100ms. When the program starts, it will log the first time and then set the timer interval to 1 minute. (60000ms)

 Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
   Label9.Text = Now 'Display time and date
 Timer1.Interval = 60000 'Set interval for 1 minute
 Timer1.Enabled = True
 Call Sub() Button1_Click() 'Call the routine to get the PLC information and store in a database
 End Sub

This will handle the LinkLabel on the form.

 Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
   ' Specify that the link was visited.
 Me.LinkLabel1.LinkVisited = True
 ' Navigate to a URL.
 System.Diagnostics.Process.Start("https://www.accautomation.ca")
 End Sub
 End Class

ModbusTCP MSAccess 070-min

Running the program:
The status will show ‘Initializing..’ so that the imports can be loading in the program. This will happen each time the software starts.
ModbusTCP MSAccess 083-min

Logging will be displayed in the status to indicate that everything is working correctly.
ModbusTCP MSAccess 080-min

Error messages will show in the status when an error has occurred. We have programmed two errors:
Communication Error! – Information is not being received from the PLC. This could be due to the wrong IP address or communications links have been broken.
Database Error! – Information cannot be written into the database, the database is not present, etc.
ModbusTCP MSAccess 085-min

Here is what our database looks like after collecting a few samples.
ModbusTCP MSAccess 105-min

As you can see, collecting information from the PLC via ModbusTCP and inserting it into an Access database can be easily done. The next steps would be to ensure that the data is always collected. What happens when the communication to the PLC is cut? Robust logging is required. This is when we create a buffer in the PLC of the logged values. Please refer to our EBook ‘Robust Data Logging for Free’ .

Download the sample database, visual basic and PLC code for this project here.

Watch on YouTube : Modbus TCP Data Logging to Database
If you have any questions or need further information please contact me.
Thank you,
Garry



If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLC’s are not difficult to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimal, Hexadecimal, ASCII and Floating Point.

To get this free article, subscribe to my free email newsletter.


Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.




AdvancedHMI to Solo Process Temperature Controller

Modbus RTU will be the serial (RS485) method in which we will communicate between the AdvancedHMI Screen and the Automation Direct Solo Process Temperature Controller.
We can address up to 247 (Solo 1 to 247) devices on this master – slave protocol. A maximum of 32 devices (Nodes) on the network can communicate to the master. A review of the Modbus RTU protocol can be seen at the following URL.
http://www.rtaautomation.com/technologies/modbus-rtu/

AdvancedHMI is a free HMI programming package the runs on Microsoft Visual Studio. It can be downloaded at the following URL.
https://sourceforge.net/projects/advancedhmi/

Connections:
We will be running the AdvancedHMI software on the computer. One of the USB ports will have an USB to RS485 adapter and communicate RS485 to the Solo process temperature controller.
Solo Process Temp Controller 010 Communication Diagram-min
See the following post to install the USB to RS485 adapter.
https://accautomation.ca/usb-to-rs485-pc-adapter-installation/

Solo Controller Settings:
In the Initial Setting Mode we will change the on line configuration to on and make the changes to the Modbus settings as follows: 9600 Baud, Even, 7 Data Bits, 1 Stop Bit, Modbus ASCII Format. We will leave the default unit number as 1. See the following post to set the controller:
https://accautomation.ca/solo-process-temperature-controller/

Modbus RTU (Addresses)
The following address will be used in our project:
AdvancedHMI to Solo 050-min

AdvancedHMI to Solo 055-min
AdvancedHMI will use the Modbus Decimal value in the PLCAddressValue to determine the information that you want to get. For a list of all Modbus addresses that can be used in your project, refer to the Solo Manual located a the following URL:
https://www.automationdirect.com/adc/Manuals/Catalog/Process_Control_-a-_Measurement/Temperature_-z-_Process_Controllers

Screen Display: (AdvancedHMI)
Here is what our screen will look like:
AdvancedHMI to Solo 010-min
We have mimicked the look of the solo process temperature controller. Our PV and SV values are DigitalPanelMeters from the AdvancedHMI toolbar.  The eight output indicators are just labels.

Our ModbusRTUCom1 settings are as follows:
AdvancedHMI to Solo 030-min
Settings: 9600, 8, Even, One StopBit and Station 1 should all match the settings in the Solo process temperature controller that we did previously.
PollRateOverride will allow us to determine how often the communication will take place to the controller. (250msec)
The PortName will be the same port number that the computer will communicate out of. This will be set when you install the USB to RS485 adapter. It may change if a different USB port is used.

The DataSubsciber1 will be used to determine the status of the controller.
AdvancedHMI to Solo 040-min
PLCAddressValue = 44139

We read the value of the eight status bits and convert this into a string so we can determine the status of each of the individual bits. Here is the code that is used to do this. It is the only code required for this application.

Private Sub DataSubscriber1_DataChanged(sender As Object, e AsDrivers.Common.PlcComEventArgs) Handles DataSubscriber1.DataChanged
        Dim i As Integer = DataSubscriber1.Value
        Dim Status As String
        Status = Convert.ToString(i, 2).PadLeft(8, "0") '8 bits
        'There are 8 bits that we need to check and account for on our screen. 
        'Modbus Decimal - 44139
        'Bit 0 - ALM3 - Alarm 3
        'Bit 1 - ALM2 - Alarm 2
        'Bit 2 - C degrees
        'Bit 3 - F degrees
        'Bit 4 - ALM1 - Alarm 1
        'Bit 5 - OUT 2 
        'Bit 6 - OUT 1
        'Bit 7 - AT - Auto Tuning

The complete AdvancedHMI code for this application can be downloaded at the end of the post.

The PV and SV indicators are DigitalPanelMeters as mentioned above.
AdvancedHMI to Solo 060-min

AdvancedHMI to Solo 065-min
They both have four digits with a decimal position of 1. This will give us a value between 000.0 and 999.9.
The SV includes a keypad to change the set value. KeypadScaleFactor is set to 0.1 to allow for the decimal place.

Included in our display is a BasicTrendChart from the AdvancedHMI toolbar.
AdvancedHMI to Solo 075-min

AdvancedHMI to Solo 070-min
You want to make sure that the YMaximum and YMinimum settings are set so the values will not go past these settings. If they do then the graph line will disappear from the chart at that point and time.
This will show a running trend for the last 5 minutes.
Polling rate is 250msec x 1200 points in the chart = 300 000msec
300 000msec / 1000 = 300 seconds
300 seconds / 60 (seconds in minute) = 5 minutes

Notes: Displaying Extended ASCII Symbols in Visual Studio (VB.NET)
You can display any symbol in the visual studio environment by holding the ‘Alt’ key down and typing the decimal number of the symbol that you want. In our example the degrees symbol is Alt 248.
Here are the extended ASCII symbols:
AdvancedHMI to Solo 020-min
http://www.asciitable.com/

Running the Application:
AdvancedHMI to Solo 085-min

You will notice that the response rate is very quick. (250msec) As the PV, SV or indication values change, the screen will get updated.AdvancedHMI to Solo 090-min

The trend chart will show the last 5 minutes of the PV value. AdvancedHMI to Solo 095-min

As you can see, programming the AdvancedHMI to communicate to the Solo process temperature controller is very easily done.

Download the AdvancedHMI code for this project here.

Watch on YouTube : AdvancedHMI to Solo Process Temperature Controller
If you have any questions or need further information please contact me.
Thank you,
Garry



If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLC’s are not difficult to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimal, Hexadecimal, ASCII and Floating Point.

To get this free article, subscribe to my free email newsletter.


Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.




PLC Bits Numbers and Position

People often ask “What is a PLC?” and “PLC Meaning”. A programmable logic controller (PLC) is a piece of hardware that isolates inputs from outputs. Programs are written to look at the inputs solve logic and set the outputs to perform work. Today we are going to look at the basic fundamental way we program. Every PLC company will do this…

Everything in the programmable logic controller actually boils down to bits in the memory.
Memory Bits-min
It is these bits that we manipulate in order to accomplish the work that we need done by the PLC. The instruction set is the method we use to do this. In general, there are several ways to view the bits. Discrete input and output, Numbers and Position of bits will be covered. Understanding the different ways in which we can view these bits will help in developing programs.
Bits are part of the memory of all PLC systems. The memory can be retentive or non-memory retentive. Memory retentive means that if power is lost to the PLC, the status of the bit remains the same when power is restored. If the bit is non-memory retentive, and power is lost the bit returns to the off state. Addressing refers to how the controller understands what memory location to look at. When we address memory in the PLC we can do this in two different ways:
Direct Addressing: Specify a location of the memory location
Indirect Addressing: Specify a location that contains a value to point to the memory location required.
Indirect Addressing Animation

Refer to the manual of the specific PLC that you are using for the way in which memory is addressed and if it is memory retentive or not.

Discrete bits are the basic building blocks in the PLC. When we talk of digital I/O this is referring to the individual bits that you can wire switches, pushbuttons, proximity sensors, or any other device that is either on or off. (1 or 0) They can be usually wired to the PLC as a normally open or normally closed contact. The ladder logic is written in a way that you examine the bit as either on or off.
HOW PLC INPUTS WORK
PLC Input

HOW PLC OUTPUTS WORKPLC Outputs
We also must look at the frequency (rate of change from off to on) of the input bits or output in some cases. The maximum frequency that we can read an input to the PLC will be determined by the scan of the PLC.
Example:
A 2 ms Scan (0.002 second) means that we can read the inputs and solve the logic in 2 ms. In order to ensure that the input is read in both states (on / off) we have to ensure that the input is off or on for at least 2 ms. The maximum frequency (Switching / Second) that the input could switch would be 2 ms = 1/.002 times per second = 500hz

Numbers in the PLC are all based on binary. Analog inputs and outputs are based upon the number of bits put together in order to display the range for the input. (12 bit or 16 bit) The values from the analog 12bit input will go from 000 to FFF base 16 (Hex). Hexadecimal is used to display the binary bits in the word or register. Some of the more common numbering systems in the PLC are binary, hexadecimal, BCD (binary coded decimal) and octal (based on 8 bits)
funny_counter
Additional Information on understanding numbering systems in the PLC:
What Everybody Ought to Know about PLC (Programmable Logic Controller) Numbering Systems

Position of the bits within the word, stack or accumulator can be very useful. Usually we can use this to track items. The typical example of this is to track items on a conveyor belt. The belt movement is usually a pulse input from an encoder. A sensor indicates the item on the conveyor.
PLC PROGRAMMING EXAMPLE – SHIFT REGISTER (CONVEYOR REJECT)
Conveyor Reject

Bits are the basic building blocks that we use to program programmable logic controllers. The three ways to view bits (Discrete, Number and Position) will help use to understand the different ways to program.
Here are some additional links that you may find helpful:
Five Steps to PLC Program Development
PLC Programming Example – Process Mixer
PLC Programming Example – Shift Register (Conveyor Reject)
PLC Programming Example – Paint Spraying

The Secret of Using Counters
The Secret of Using Timers

Watch on YouTube : PLC Bits Numbers and Position
If you have any questions or need further information please contact me.
Thank you,
Garry



If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLC’s are not difficult to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimal, Hexadecimal, ASCII and Floating Point.

To get this free article, subscribe to my free email newsletter.


Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.




Excel Conditional Movement of Data

I have been recently asked how you can move data conditionally on an excel spreadsheet once the information has been obtained from the PLC? Monthly data was being collected from the PLC and put on an excel spreadsheet using Omron CX-Server DDE. They wanted at the beginning of each month to move the data to the appropriate month so they can track the changes.

The following three blogs were posted on how to get data into the Microsoft Excel Spreadsheet from the programmable logic controller. (PLC)

HOW TO IMPLEMENT MODBUS TCP PROTOCOL USING VBA WITH EXCEL

IMPLEMENTING THE OMRON CX SERVER DDE AND EXCEL

HOW TO IMPLEMENT THE OMRON HOST LINK PROTOCOL PART 2 – VBA

The method to move the data around the spreadsheet once the data has been obtained will be done by Visual Basic for Applications. (VBA)

Make a spreadsheet in excel as follows:
Excel Conditional Movement of Data 0100-min

Operation:
When the current data in A2 or B2 changes, it will trigger a macro to execute. This macro will use the Worksheet_Change to trigger the code. The date in A2 is then compared to all of the dates located from A5 to A30. If a match is found then the value in B2 is placed beside the matching date found column. Example: A2 = A7 then B7 = B2
Here is a look at the VBA editor and code:
Excel Conditional Movement of Data 0110-min

Here is the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = “$A$2” Or Target.Address = “$B$2” Then
For x = 5 To 30
If Sheets(“Sheet1”).Range(“A2”) = Sheets(“Sheet1”).Range(“A” & x) Then
Sheets(“Sheet1”).Range(“B” & x) = Sheets(“Sheet1”).Range(“B2”)
End If
Next ‘x
End If
End Sub

Download the example excel file.

Watch on YouTube : Excel Conditional Movement of Data
If you have any questions or need further information please contact me.
Thank you,
Garry



If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLC’s are not difficult to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimal, Hexadecimal, ASCII and Floating Point.

To get this free article, subscribe to my free email newsletter.


Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.




Building a PLC Program That You Can Be Proud Of – Part 5

The Game of Simon
Learning all about bit manipulation and sequencers

Simon is a memory game introduced in 1978. It has four coloured buttons, each producing a particular tone when it is pressed or activated by the device. A round in the game consists of the device lighting up one or more buttons in a random order, after which the player must reproduce that order by pressing the buttons. As the game progresses, the number of buttons to be pressed increases. If the wrong button is hit the current game is over. Our game will have a high level score and a current level score.

We will be using AdvancedHMI to communicate Modbus TCP to the Automation Direct Do-More Designer Software Simulator.

Watch on YouTube : The Game of Simon Play (PLC / HMI)
Here is the end result of our program.

Note: The programs are provided free of charge and are an excellent way to learn PLC / HMI programming.

Here is a quick review of the programming series so far. If you are new to the site, we recommend reviewing the other parts in the series first. In part 1 we looked at writing PLC programs to control a traffic light using discrete bits and then using timed sequencing using indirect addressing. Part 2 used indirect addressing for inputs as well as output to control the sequence of pneumatic (air) cylinders in the program. Part 3 and 4 we returned to the traffic light application and expand our program significantly. We looked at the sequence of operation using Input, output and mask tables.

Simon Game HMI 130-min

The first thing that we will do is look at the HMI programming. Please refer to the following post for information on setting up and using AdvancedHMI software.
Create a PLC with HMI Training and Learning Environment Free

The following table is the Modbus TCP memory map to the Do-More PLC:

Coil/Register Numbers Data Addresses Type Do-More PLC Table Name
00001-09999 0000 to 270E Read-Write MC1 to MC1023 Discrete Output Coils
10001-19999 0000 to 270E Read-Only MI1 to MI1023 Discrete Input Contacts
30001-39999 0000 to 270E Read-Only MIR1 to MIR2047 Analog Input Registers
40001-49999 0000 to 270E Read-Write MHR1 to MHR2047 Analog Output Holding Registers

Simon Game HMI 100-min
Add the ModbusTCPCom control and set the IP Address. Also set the PollRateOverride to 50 so the response to our PLC is quicker.

The following map will apply to our game:
(Communication between the HMI and PLC)

40002 – MHR2 – Register – Game Sounds
40001 – MHR1 – Register – Current Game Level
40003 – MHR3 – Register – Highest Game Level
00005 – MC5 – Bit – Start/Reset Game
00001 – MC1 – Bit – Green Button Input
10001 – MI1 – Bit – Green Button Set
00002 – MC1 – Bit – Red Button Input
10002 – MI1 – Bit – Red Button Set
00003 – MC1 – Bit – Yellow Button Input
10003 – MI1 – Bit – Yellow Button Set
00004 – MC1 – Bit – Blue Button Input
10004 – MI1 – Bit – Blue Button Set

Simon Game HMI 110-min
The DataSubsciber is used to read information from the PLC and manipulate the data in the visual basic code.  We will use this to determine what sounds to play.

The following is the code for the button when hit to play the sound and the DataSubscriber1 to play the sound when the playback from the PLC is required. (Console.Beep (Frequncy (Hz), Duration (msec)))

Private Sub PilotLight1_Click(sender As Object, e As EventArgs) Handles PilotLight1.Click ‘ Green Light
     Console.Beep(415, 420)
End Sub

Private Sub PilotLight2_Click(sender As Object, e As EventArgs) Handles PilotLight2.Click ‘ Red Light
     Console.Beep(310, 420)
End Sub

Private Sub PilotLight3_Click(sender As Object, e As EventArgs) Handles PilotLight3.Click ‘ Yellow Light
     Console.Beep(252, 420)
End Sub

Private Sub PilotLight4_Click(sender As Object, e As EventArgs) Handles PilotLight4.Click ‘ Blue Light
     Console.Beep(209, 420)
End Sub

Private Sub DataSubscriber1_DataChanged(sender As Object, e As Drivers.Common.PlcComEventArgs) Handles DataSubscriber1.DataChanged
If DataSubscriber1.Value = “1” Then
     Console.Beep(415, 420) ‘ Green
ElseIf DataSubscriber1.Value = “2” Then
     Console.Beep(310, 420) ‘ Red
ElseIf DataSubscriber1.Value = “4” Then
     Console.Beep(252, 420) ‘ Yellow
ElseIf DataSubscriber1.Value = “8” Then
     Console.Beep(209, 420) ‘ Blue
ElseIf DataSubscriber1.Value = “10” Then
     Console.Beep(120, 1500) ‘ Losing Sound
ElseIf DataSubscriber1.Value = “20” Then
     For x = 1 To 8
          Console.Beep(600, 90) ‘ Winning Sound
          Threading.Thread.Sleep(20)
     Next ‘x
End If
End Sub

Simon Game HMI 120-min

We now have our HMI interface complete and can move onto the PLC programming.

Random sequence generator – MHR4
The first four bits of MHR4 will be used to generate the random sequence for each step of the pattern.
The first scan is to set (1) a bit in MHR0. This will also ensure that the rest of the bits in the word are reset (0).
The second rung will shift the bits left in the output word MHR0. This will happen once per scan of the PLC. When bit 04 turns on then bit 00 will then be turned on again. This way we will always have one of the first four bits turned on in the output word. (00, 01, 02 or 03) MHR0 is logically AND with Hex value 000F and the result is placed in MHR4.

Simon Game PLC 100-min

Start the Game
The game will be started n the leading edge of the reset button. (MC5)
All of the registers and pointers are reset to start the game.
1     is moved into the current level – MHR1
100 is moved into the Play Sequence Pointer – V1
100 is moved into the Input Sequence Pointer – V2
100 is moved into the Current Level Pointer – V0
The random sequence MHR5 is moved indirectly into the Current Level Pointer V0 and this pointer is then incremented by 1.
An initialization bit is then set.

Simon Game PLC 110-min

The initialization bit starts a timer for 600msec in order to give time for the HMI to respond. Once the time expires the Initialization bit is reset and the game start bit is set. (Y0)
Y0 – Game Started is used to determine if play is to continue.

Simon Game PLC 120-min

Play the Sequence

Simon Game PLC 130-min

Set the outputs to play the sequence.
This will also set the sound to play for each of the colours selected. (MHR2)

Simon Game PLC 140-min

Reset the sound during the playing of the sequence.

Simon Game PLC 150-min

Read the inputs from the HMI. (MC1 – MC4)
Set the bits in V501 so we can compare the word.

Simon Game PLC 160-min

If the wrong button is hit, then play a sound and stop the game.

Simon Game PLC 170-min

If the correct color is selected, increment to the next random colour in the sequence.

Simon Game PLC 180-min

If the correct colour sequence has been entered, then the level has been completed.
Start a delay to ensure that the HMI has finished playing all of the sounds.

Simon Game PLC 190-min

When the level is entered correctly and the time delay has expired, we will reset the play and input pointers. The level increases by 1 and  another random number is added to the sequence and the current level pointer is incremented by 1.
MHR1 – Level – Increases
V1 – 100
V2 – 100
V0 – New random number gets indirecly addressed and the pointer is incremented by 1

Simon Game PLC 200-min

Setting the Highest Level achieved
If the current level is greater than the highest level, the current level is moved into the highest level.

Simon Game PLC 210-min

If no key is hit for 45 seconds after the sequence is played a sound will be played and the game start bit will be reset.

Simon Game PLC 220-min

If the game start bit is off for more than 500ms, the sound will be reset.

Simon Game PLC 230-min

Download the PLC program and the Bin directory for the AdvancedHMI screen.

Watch on YouTube : Building a PLC Program that You can be Proud Of – Part 5 – Game of Simon

Part 6 will look at a sequencer controlling seven cylinders that can be taught. The cylinders can be operator programmed from the AdvancedHMI screen.

If you have any questions or need further information please contact me.
Thank you,
Garry



If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLC’s are not difficult to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimal, Hexadecimal, ASCII and Floating Point.

To get this free article, subscribe to my free email newsletter.


Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.




Create a PLC with HMI Training and Learning Environment Free

Learn PLC programming and use a powerful HMI (Human Machine Interface) easily and free. We will use the Automation Direct Do-More programming software tied into the Advanced HMI package via Modbus TCP.
PLC HMI Training Learning 0080-min

Our application will show a HMI screen with a panel meter and a reset button. The panel meter value may be changed by clicking it. This will bring up a input screen to put in a number. When the reset button is selected the input value entered will show on the panel meter.
PLC HMI Training Learning 0310-min

Since we will be communicating via Modbus TCP, the following table shows the Coil/Register Numbers and the associated Do-More PLC Addresses.

Coil/Register Numbers Data Addresses Type Do-More PLC Table Name
00001-09999 0000 to 270E Read-Write MC1 to MC1023 Discrete Output Coils
10001-19999 0000 to 270E Read-Only MI1 to MI1023 Discrete Input Contacts
30001-39999 0000 to 270E Read-Only MIR1 to MIR2047 Analog Input Registers
40001-49999 0000 to 270E Read-Write MHR1 to MHR2047 Analog Output Holding Registers

Note: The Do More PLC uses the Modbus area to communicate. This is because having direct access to the digital I/O can be dangerous when connected via Ethernet to the internet. Data must move in and out of this area via the PLC program.

We will first start with the PLC.
Automation Direct has a powerful simulator with their Do-More PLC. It is the Do-More Designer Software. This software simulator includes the entire instruction set (Not Just Bit Logic) as well as communication protocols. It can be downloaded and installed for free from the above link.
Our PLC program will have the following addresses:
Digital Panel Meter Present Value (PV) – MHR1 – Modbus 40001
Digital Panel Meter Set Value (SV) – MHR2 – Modbus 40002
Reset Button – MC1 – Modbus 00001

The first rung of the ladder will use the 1 second pulse bit and increment the PV value of our digital panel meter. This will also compare the current value to 4000 and if greater or equal, move the value of zero into the PV value.

The second rung of the ladder will move WX0 analog value from our simulator into the PV value of our digital panel meter.

The last rung of ladder will move the SV value into the PV value of our Digital Panel Meter. This happens when the reset is hit.

PLC HMI Training Learning 0200-min

The simulator is showing X0 on and we can then use the WX0 slider to change the PV value of the Panel Meter.
PLC HMI Training Learning 0210-min

Advanced HMI is a powerful HMI/SCADA (Supervisory Control and Data Acquisition) development package that takes advantage of Visual Studio. There is no coding required and you can simply drag and drop items onto the page. The best thing is that the software is free.

Communications drivers include the following and are accessible via VB or C# code:

  • Allen Bradley DF1 RS232 Driver
  • Allen Bradley Ethernet/IP Driver for SLC,MicroLogix, ControlLogix, and CompactLogix
  • Beckhof TwinCAT Driver
  • ModbusTCP Driver
  • ModbusRTU Driver
  • Omron Ethernet FINS Driver – Ethernet for newer controllers such as CP1H with Ethernet module
  • Omron Serial FINS Driver – Serial (RS232 / RS485) for newer controller such as CP1H
  • Omron Serial HostLink Driver – Serial (RS232 / RS485) for controllers such as CQM1, C200H, K-Series (C28K), C200, etc

The power of Advanced HMI is that it works within Visual Studio. This is a program integrated development environment (IDE) that you can take advantage of to modify or create new features including data logging applications.

Advanced HMI runs on Visual Studio 2008 or higher and will need to be installed on your PC. Visual Studio Community Edition 2015 is the latest version of the software. If you do not have it installed, please download and install from the following link.

https://www.visualstudio.com/en-us/products/visual-studio-community-vsPLC HMI Training Learning 0090-min

We will now need the Advanced HMI project. Here is the link to download the zip file.

http://sourceforge.net/projects/advancedhmi/PLC HMI Training Learning 0095-min

After downloading ‘AdvancedHMIBetaV399a.zip’ extract the files from the zip file. (Right Click.. Select Extract All)
Note: Your version might be different than the one above.

Open the solution file (AdvancedHMIv35.sln) from the extracted files in the root directory.
PLC HMI Training Learning 0097-min

PLC HMI Training Learning 0100-min

Our initial screen looks like the following. The project will now need to be compiled in order to add the components to the Toolbox.
Select Build | Build Solution from the menu
The next thing to do is add the communication to the form. On the left hand side of the screen you will see the ‘Toolbox’. Click on it and under AdvancedHMIDrivers Components we will select ModbusTCPCom. To actually add a component to our form you need to drag it. Select the component and as you hold the mouse button down move to the form.PLC HMI Training Learning 0120-min

After adding the ModbusTCPCom component, it will appear at the bottom, beneath our form.
Click on the ModbusTCPCom1 at the bottom of our form. On the right hand side you will notice the properties for this communication driver. Under Communication Settings | IP Address, enter the value  of the IP Address for the PLC. (192.168.1.3) Ensure that the port number is 502. This is the default port number for Modbus TCP.PLC HMI Training Learning 0130-min

We can now add the digital panel meter. From the toolbox select and drag the DigitalPanelMeter to our form.PLC HMI Training Learning 0140-min

Resize the panel meter on the form by dragging a corner of the component.
While the panel meter is clicked, set the Properties | PLC Properties of the component:
PLCAddressValue – 40001 – MHR1 – Value to display on the meter.
PLCAddressKeypad – 40002 – MHR2 – This is the location of the stored number when the operator selects the meter and enters a number in the keypad.PLC HMI Training Learning 0150-min

Add a MomentaryButton to our form by selecting and dragging it from the toolbox.PLC HMI Training Learning 0160-min

After re-sizing the component, we can change the colour to blue under Properties | Misc. Also change the text on the button to ‘RESET’
Set the PLCAddressClick value to 00001. This is address MC1 in the Do-More PLC.PLC HMI Training Learning 0170-min

Run the application by selecting the ‘Start’ form the top menu. This also can be started by hitting ‘F5’. The form will then show in a separate window and the panel meter will be incrementing the value. Hitting the reset button will reset the value to the one entered when you click the panel meter.PLC HMI Training Learning 0310-min

When you hit the panel meter on the display a keypad will then pop up on your screen. Enter the new value and then select ‘Enter’. The new value will appear in MHR2 in the Do-More PLC.
PLC HMI Training Learning 0320-min

Watch on YouTube : Create a PLC with HMI Training and Learning Environment Free
If you have any questions or need further information please contact me.
Thank you,
Garry



If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLC’s are not difficult to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimal, Hexadecimal, ASCII and Floating Point.

To get this free article, subscribe to my free email newsletter.


Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.




How to Implement Modbus TCP Protocol using VBA with Excel

We will use Visual Basic for Applications (VBA) to communicate to a PLC using Modbus TCP protocol. Reading ten registers in the PLC and displaying a bar graph in Excel. Previously we have used VB6 to communicate Modbus TCP.
The following steps will be done:

  1. Explain Modbus TCP protocol
  2. Install OstroSoft Winsock Component
    – Winsock API Calls for communication on network
  3. Develop the Excel and VBA application
    (Microsoft Excel 2010)
  4. Communicate to the PLC and sample code
    (Do-More Simulator)

 

The Modbus TCP/IP or Modbus TCP is a Protocol  that is used for communications over TCP/IP networks. This is done on port 502. Modbus TCP does not require a checksum calculation as lower layers already provide checksum protection. You can think of this as a letter being sent and Ethernet TCP/IP acts like an envelope for the Modbus Commands. I will not go into the details of the communication protocol but here are some links to references:
Introduction to Modbus TCP/IP
Simply Modbus – Modbus TCP

 

OstroSoft Winsock Component
OSWINSCK.dll serves as a wrapper for the Winsock API and helps programmers to abstract from the complexity of API calls and focus on application functionality. Works with programming and scripting languages supporting COM.
You will need to download and install the OstroSoft Winsock Component on your computer.
For use with .NET, Visual Basic 4 or 5, Visual C++, ASP, VBA, VBScript, JavaScript or any other language, supporting COM:
1. Download oswinsck.exe
Modbus TCP using VBA Excel 001-min

2. Run downloaded file from Windows Explorer or command-line
Modbus TCP using VBA Excel 002-min
Hit OK
Modbus TCP using VBA Excel 003-min
I use the default directories where the program will be installed. Click the button to install.
Modbus TCP using VBA Excel 004-min
Leave the program group to the default so I know what the program is after installation. Click continue.
Modbus TCP using VBA Excel 005-min
Click OK
The OstroSoft Winsock Component is now installed.

Start Microsoft Excel.

Modbus TCP using VBA Excel 010-min
Select ‘Developer’ along the top tabs.
Modbus TCP using VBA Excel 020-min

If the Developer tab is not present then we must turn on the developer tab.
Select File | Options Modbus TCP using VBA Excel 021-minSelect ‘Customize Ribbon’Modbus TCP using VBA Excel 022-minCheck the ‘Developer’ under Main Tabs. Modbus TCP using VBA Excel 023-min

Under the Developer menu. Select ‘Visual Basic’
Modbus TCP using VBA Excel 030-minThe Visual Basic Editor window will now be displayed. Modbus TCP using VBA Excel 040-min
From the menu – Tools | References
We can now add the OstroSoft Winsock Component to our application.
Select OK
Modbus TCP using VBA Excel 050-minSelect Sheet1(Sheet1). Modbus TCP using VBA Excel 060-min

Now put the visual basic code in the Sheet1(Sheet1)
Here is the code:

‘This example uses OstroSoft Winsock Component
‘http://www.ostrosoft.com/oswinsck.asp

Option Explicit

Dim bytesTotal As Long
Dim sPage As String
Dim MbusQuery
Dim returnInfo
Dim wsTCPgdb
Dim WithEvents wsTCP As OSWINSCK.Winsock
Dim SetObject
Dim RetrieveData

Private Sub CommandButton1_Click() ‘ Retrieve Data
On Error GoTo ErrHandler
  Dim sServer As String
  Dim nPort As Long
  Dim StartTime
 
  DoEvents
  nPort = 502 ‘ See configuration in Do-More Designer
  ‘ Set the IP address of the PLC
  sServer = Sheets(“Sheet1”).Range(“B4″) ‘”192.168.1.3”
  RetrieveData = 1
  CommandButton1.BackColor = “&H0000FF00” ‘ Set colour to Green

‘Check to see if the object has been created. If not set wsTCP.
If SetObject = “” Then
Set wsTCP = CreateObject(“OSWINSCK.Winsock”)
wsTCP.Protocol = sckTCPProtocol
SetObject = 1
  End If

‘ Check the state of the TCP connection
‘0 sckClosed connection closed
‘1 sckOpen open
‘2 sckListening listening for incoming connections
‘3 sckConnectionPending connection pending
‘4 sckResolvingHost resolving remote host name
‘5 sckHostResolved remote host name successfully resolved
‘6 sckConnecting connecting to remote host
‘7 sckConnected connected to remote host
‘8 sckClosing Connection Is closing
‘9 sckError error occured

‘ If TCP is not connected, try to connect again.
If wsTCP.State <> 7 Then
    If (wsTCP.State <> sckClosed) Then
      wsTCP.CloseWinsock
    End If
    ‘ Open the connection
    wsTCP.Connect sServer, nPort
    StartTime = Timer ‘ Use the timer to determine if a connection cannot be made
    Do While ((Timer < StartTime + 2) And (wsTCP.State <> 7))
        DoEvents
    Loop
    If (wsTCP.State = 7) Then
    Else
       Exit Sub
    End If
End If

‘ If we are connected then request the information.
If (wsTCP.State = 7) Then
    MbusQuery = Chr(0) + Chr(0) + Chr(0) + Chr(0) + Chr(0) + Chr(6) + Chr(0) + Chr(3) + Chr(0) + Chr(0) + Chr(0) + Chr(20)
    wsTCP.SendData MbusQuery ‘Send out the Modbus Information
    ‘ Read the information
    ‘0000:    Transaction Identifier
    ‘0000:    Protocol Identifier
    ‘0006:    Message Length (6 bytes to follow)
    ’00:      The Unit Identifier
    ’03:      The Function Code (read MHR Read Holding Registers)
    ‘0000:    The Data Address of the first register
    ‘0002:    The number of registers to write
   
    ‘ Write the information
    ‘0000:    Transaction Identifier
    ‘0000:    Protocol Identifier
    ‘0009:    Message Length (6 bytes to follow)
    ’01:      The Unit Identifier
    ’16:      The Function Code (read Analog Output Holding Registers)
    ‘0000:    The Data Address of the first register
    ‘0001:    The number of registers to write
    ’02:      The number of data bytes to follow
    ‘0030     The number to put into the register
   
    ‘ Note: Addresses are offset by 1
    ‘   Example: MHR1 = Address 0000
    ‘   Example: MHR30 = Address 0029
   
End If
  Exit Sub

ErrHandler:
  MsgBox “Error ” & Err.Number & “: ” & Err.Description
End Sub
Private Sub CommandButton2_Click() ‘ Stop the communication
RetrieveData = 0
CommandButton1.BackColor = “&H8000000F” ‘ Set the default colour
End Sub

Private Sub wsTCP_OnDataArrival(ByVal bytesTotal As Long)
  Dim sBuffer
  Dim i
  Dim MbusByteArray(500)
  Dim h As Integer
  Dim txtSource
wsTCP.GetData sBuffer
  txtSource = txtSource & sBuffer
 
Dim j As Byte
returnInfo = “”
For i = 1 To bytesTotal
    wsTCP.GetData j, vbByte
    MbusByteArray(i) = Asc(Mid(sBuffer, i, 2))
    returnInfo = returnInfo & Asc(Mid(sBuffer, i, 2))
Next
 txtSource = returnInfo
 txtSource = Val(Str((MbusByteArray(10) * 256) + MbusByteArray(11)))
 Sheets(“Sheet1”).Range(“B10”) = Val(Str((MbusByteArray(10) * 256) + MbusByteArray(11)))
 Sheets(“Sheet1”).Range(“B11”) = Val(Str((MbusByteArray(12) * 256) + MbusByteArray(13)))
 Sheets(“Sheet1”).Range(“B12”) = Val(Str((MbusByteArray(14) * 256) + MbusByteArray(15)))
 Sheets(“Sheet1”).Range(“B13”) = Val(Str((MbusByteArray(16) * 256) + MbusByteArray(17)))
 Sheets(“Sheet1”).Range(“B14”) = Val(Str((MbusByteArray(18) * 256) + MbusByteArray(19)))
 Sheets(“Sheet1”).Range(“B15”) = Val(Str((MbusByteArray(20) * 256) + MbusByteArray(21)))
 Sheets(“Sheet1”).Range(“B16”) = Val(Str((MbusByteArray(22) * 256) + MbusByteArray(23)))
 Sheets(“Sheet1”).Range(“B17”) = Val(Str((MbusByteArray(24) * 256) + MbusByteArray(25)))
 Sheets(“Sheet1”).Range(“B18”) = Val(Str((MbusByteArray(26) * 256) + MbusByteArray(27)))
 Sheets(“Sheet1”).Range(“B19”) = Val(Str((MbusByteArray(28) * 256) + MbusByteArray(29)))

DoEvents
‘ Determine if we retrieve the data again.
If RetrieveData = 1 Then
    Call CommandButton1_Click
End If
End Sub

Private Sub wsTCP_OnError(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
  MsgBox Number & “: ” & Description
End Sub

Private Sub wsTCP_OnStatusChanged(ByVal Status As String)
  Debug.Print Status
End Sub

Note: The program utilizes the CHR and STR functions to convert the data from binary to ASCII and back.
The highest value of a byte of data is 256. This is why we have to multiply the highest significant byte with 256

Interface:
Go back to Sheet1 and we can now put on the worksheet what we would like to see.

Note the following:
IP Address = B4
MHR 1 to 10 values located at B10 to B19
‘Stop Data’ – CommandButton2
‘Retrieve Data’  – CommandButton1

Modbus TCP using VBA Excel 070-min

 

Communication to the PLC

Start the Do-More Designer software.
Under the Project Browser select ‘System Configuration’
Modbus TCP using VBA Excel 125-min
Make note of the IP address. If you are running the simulator then this is automatically filled in.
Modbus TCP using VBA Excel 126-min
Ensure that the Enable Modbus/TCP Server is checked. Also make sure that the TCP Port Number is 502.
Modbus TCP using VBA Excel 127-min

The sample PLC program will write values in the range from 0 to 4000. These values will be put in MHR 1 to MHR 10.

Here is the first couple of rungs of the PLC program. It will use clock bit flags to increment the MHR 1 channel. When it gets to the value above 4000, a move instruction will put a 0 back into MHR 1.
If input X0 turns on then the value in XW0 will be moved into MHR1 and the previous clock bit will not be in effect. Values will be between 0 and 4096. (12 bit resolution)
Modbus TCP using VBA Excel 150-min

This is repeated with different internal clock bit flags up to MHR10.

Running the program will produce the following:Modbus TCP using VBA Excel 120-min

As you can see the Modbus TCP protocol is easy to implement with visual basic for applications.
Download the PLC program and Excel file.

Additional Information:
Excel – Conditional Movement of Data

Watch on YouTube : How to Implement Modbus TCP Protocol using VBA with Excel
If you have any questions or need further information please contact me.
Thank you,
Garry



If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLC’s are not difficult to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimal, Hexadecimal, ASCII and Floating Point.

To get this free article, subscribe to my free email newsletter.


Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.