Category Archives: Programming Example

What Everybody Ought to Know About IP Addressing

Communication using Ethernet usually evolves around the Open Systems Interconnection model (OSI model). This model was made for computing systems to communicate without regard for the underlying internal structure and technology.

Think of it like sending a letter:
You write the message on paper – This is like the protocol that the system will be using. The protocol is like the language that the two devices will be communicating.

Sign it at the bottom of the paper – This signature is like a MAC address for the system. It will uniquely identify you.

Put it into an envelope and address it (Also return address) – This address is like the IP address for the system. It lets everyone know the location that the letter is going and returning.

Stamp, and put it in the mail – This is like the physical cable that we will be using. The schedule pickup, sorting, routing etc. to get you letter to the sender is now out of your hands.
This is similar to the OSI model. The layers within the model will communicate with each other to ensure that the information will get to the designation without error.

IP Address:
An IP (Internet Protocol) Address is a user defined numeric label assigned to a device on an Ethernet network that identifies the network and node. An IP address is a 32 bit address that is normally grouped into 4 bytes for ease of communication and understanding. Example: 192.168.1.1
You can look up your current address by going to the following url:
http://whatismyipaddress.com/

MAC Address:
The MAC (Media Access Control) Address is also called the physical address. This is part of the unique identification on an Ethernet network. The MAC address is a 48 bit address that is normally grouped into 6 bytes for ease of communication and understanding. Example: 00:02:A1:BC:72:33
Here is a URL link to find your MAC address on your computer:
http://www.wikihow.com/Find-the-MAC-Address-of-Your-Computer
Devices use their hardware addresses to communicate with each other within the OSI model.

Ethernet networks support many different types of protocols, including TCP/IP. In the industrial environment you will often here of EtherNet/IP , Modbus TCP, Profinet etc. are all part of TCP/IP.

There are a defined number of IP addresses that have been defined as private IP addresses. These addresses are not allocated to any specific organization and anyone can use these without approval. Choose the one with the range that will fit your application.

Class Private IP Addresses
A 10.0.0.0 – 10.255.255.255
B 172.16.0.0 – 172.31.255.255
C 192.168.0.0 – 192.168.255.255

Subnet Mask:
A subnet mask is an address that enables distinction between networks. It is used to divide the network into smaller units called Subnets. This is beneficial when the office communications are separate from the plant floor communications. It adds level of security and enhances maintenance and upgrade options.
A subnet mask is a 32 bit address that is normally grouped into 4 bytes. This is the same as the IP address, because we compare the IP addresses with the subnet mask to determine if they can communicate directly with one another. If not then the communication must happen through a router to get to the destination. The subnet mask must match for communications to happen.

Example:
Compare the following Modbus TCP addresses and see if they are on the same subnet:
Modbus TCP Address 1: 192.168.1.3
Modbus TCP Address 2: 192.168.0.10
Subnet Mask: 255.255.255.0

Convert these decimal values to their binary equivalent:
(You can do this by using your windows calculator in programmer mode. View | Programmer or Alt + 3)

Modbus TCP Address 1:
11000000.10101000.00000001.00000011
Modbus TCP Address 2:
11000000.10101000.00000000.00001010
Subnet Mask:
11111111.11111111.11111111.00000000
Same Subnet Compare:
11111111.11111111.1111111x.00000000
If the subnet mask has a ‘1’ then compare the two addresses and see if they are similar. In our example there is a difference, so the two devices will not communicate. You must change the subnet mask on the entire system or IP address.

Let’s now change the IP address on Address 2.
Modbus TCP Address 1: 192.168.1.3
Modbus TCP Address 2: 192.168.1.10
Subnet Mask: 255.255.255.0

Convert these decimal values to their binary equivalent:
Modbus TCP Address 1:
11000000.10101000.00000001.00000011
Modbus TCP Address 2:
11000000.10101000.00000001.00001010
Subnet Mask:
11111111.11111111.11111111.00000000
Same Subnet Compare:
11111111.11111111.11111111.00000000
We can now communicate successfully.

Troubleshooting your Ethernet network is easy by using a free product called Wireshark. https://www.wireshark.org/
This software will monitor and display your Ethernet traffic. Highlighting different communication protocols, you can quickly see your communication in action. Introduction to Wireshark Video gives a good overview of what is possible and shows what to look for on your network.

IP Address selection on your network must be unique. You cannot have two addresses the same. As a general rule only those addresses within the same subnet will communicate to each other without the need for a router.

Watch on YouTube : What Everybody Ought to Know About IP Addressing
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.

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.

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.

  • 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.
  • 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 – 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.

    o ControlBox – Remove the ControlBox on the main screen form. This will ensure that the user cannot minimize, maximize or close the application.

    o Maximize for screen size – Make the main screen form maximized so it will fill the entire screen.

    o Form.TopMost = True – This command will ensure that your application will be on top of all other windows forms.

    In this example the calculator has focus, but the our windows form will always be on top.

    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.

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

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.

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.


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

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.

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.

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:

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("http://www.accautomation.ca")
 End Sub
 End Class

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.

Logging will be displayed in the status to indicate that everything is working correctly.

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.

Here is what our database looks like after collecting a few samples.

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.

See the following post to install the USB to RS485 adapter.
http://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:
http://accautomation.ca/solo-process-temperature-controller/

Modbus RTU (Addresses)
The following address will be used in our project:


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:

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:

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.

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.


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.


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:

http://www.asciitable.com/

Running the Application:

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

The trend chart will show the last 5 minutes of the PV value. 

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.

Creating a HMI Login Screen on AdvancedHMI

We will be creating a HMI (human machine interface) login screen for the cylinder program that we developed previously.
BUILDING A PLC PROGRAM THAT YOU CAN BE PROUD OF – PART 6
Our program had a Run, Jog and Teach mode for the cylinders. Our user will login with a user name and password. Based upon the user level that is set we will control what modes each user will be able to operate. We will also write this user level mode into the PLC.

The following is the sequence of operation:
Watch on YouTube : Creating a HMI Login Screen on AdvancedHMI Sequence of Operation
Note: All of the programs used are provided free of charge and are an excellent way to learn PLC / HMI programming.

AdvancedHMI is a free HMI software package that communicates to a number of different PLC manufacturers. This package uses visual studio and vb.net to program, however you do not need to be an expert on visual basic to implement this software. We will be using an access database (Access 2010) to store our user information. When the operator logs into the system, they will enter a user name and password. The program will compare this to the information in the database and set the appropriate modes on the HMI.

The first thing that we need to do is to create a database to store the user information. We will create a table called ‘tbl_user’. The fields in the database will be as follows:
First_Name – Text Field – 50 characters
Last_Name – Text Field – 50 characters
User_Level – Number – Integer
User_Name – Text Field – 50 characters
Password – Text Field – 50 characters

The user level will be as follows:
0 – Stop and reset the machine only (Not logged in)
1 – Run, stop and reset the machine only
2 – Run, stop, reset and jog the machine
3 – Run, stop, reset, jog and teach the machine

Here is a list of addresses that we will be using for our login screen between the HMI and PLC.

Device Data Addresses Type Do-More PLC Description
Run/ Jog Selector 00008 Input MC8  MC8 on is jog mode
Jog / Teach Selector 00070 Input MC70  MC70 on is teach mode
User Level 40005 Output MHR5  Current user level

We will add a Login / Logout button on the main page of our control. This will allow the operator to sign in or out of the machine. To ensure that the operator knows that he is logged into the system we will display a message in a label also on the main screen. Here is what our main page now looks like:

The next thing we need to do is to design the form for our login information. This will contain two text boxes for the password and user name. We will also need two buttons; Login and Cancel. Our new form will be called Page2. Here is what it will look like:

When the HMI first powers up and no user has logged in we will ensure that the Jog and Teach functions are reset by writing values directly to the PLC. We will also set the user level to 0.
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles Me.Load
ModbusTCPCom1.Write(“00008”, 0) ‘Reset Run / Jog Selector PLC
ModbusTCPCom1.Write(“00070”, 0) ‘Reset Jog / Teach Selector PLC
ModbusTCPCom1.Write(“40005”, 0) ‘Set user level to 0
End Sub

Now let’s look at the logic for the button on the main page. If a person is logged into the machine then this button will log them out. This will also change the user level to 0 and write this to the PLC. In our case, MHR5 (400005) will contain the user level code. If no one is logged in then this button will call up our login form (Page2) so information can be entered.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
     If Button1.Text = “Login” Then
Page2.txtUsername.Text = “”
Page2.txtPassword.Text = “”
Page2.Show()
Else
SelectorSwitch1.Value = False
SelectorSwitch2.Value = False
          MomentaryButton1.Enabled = False ‘Start
          SelectorSwitch1.Enabled = False ‘Run / Jog Selector
          SelectorSwitch2.Enabled = False ‘Jog / Teach Selector
          Button1.Text = “Login”
          Label6.Text = “Please Login To Operate the Machine”
          ModbusTCPCom1.Write(“40005”, 0) ‘Reset user level in PLC
     End If
End Sub

Page2 is our login form. Here is the programming logic for the Login Button.
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If txtPassword.Text = “” Or txtUsername.Text = “” Then
MessageBox.Show(“Please complete the required fields…”, “Authentication Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
‘ Connect to DB
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source= F:\Users\Shortt\Downloads\Creating a HMI Login Screen in AdvancedHMI\HMI\AdvancedHMIBetaV399a\AccDatabase.accdb”
Try
Dim sql As String = “SELECT * FROM tbl_user WHERE User_Name='” & txtUsername.Text & “‘ AND Password = ‘” & txtPassword.Text & “‘”
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
‘Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then
Dim FirstName As String
Dim LastName As String
Dim UserLevel As Integer
FirstName = sqlRead(“First_Name”)
LastName = sqlRead(“Last_Name”)
UserLevel = sqlRead(“User_Level”)
MainForm.ModbusTCPCom1.Write(“40005”, UserLevel)
MainForm.Button1.Text = “Logout”
MainForm.Label6.Text = FirstName & ” “ & LastName & ” Level = “ & UserLevel
MainForm.MomentaryButton1.Enabled = True ‘Start
If UserLevel = 3 Then
MainForm.SelectorSwitch1.Enabled = True ‘Run / Jog Selector
MainForm.SelectorSwitch2.Enabled = True ‘Jog / Teach Selector
ElseIf UserLevel = 2 Then
MainForm.SelectorSwitch1.Enabled = True ‘Run / Jog Selector
MainForm.SelectorSwitch2.Enabled = False ‘Jog / Teach Selector
Else
MainForm.SelectorSwitch1.Enabled = False ‘Run / Jog Selector
MainForm.SelectorSwitch2.Enabled = False ‘Jog / Teach Selector
End If
MainForm.Show()
Me.Hide()
Else
‘ If user enter wrong username and password combination show error
MessageBox.Show(“Username and Password do not match..”, “Authentication Failure”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
‘Clear all fields
txtPassword.Text = “”
txtUsername.Text = “”
‘Focus on Username field
txtUsername.Focus()
End If
conn.Close()
          Catch ex As Exception
MessageBox.Show(“Failed to connect to Database.. System Error Message: “ & ex.Message, “Database Connection Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub

A further explanation of the code above can be found at the following address.
How to create login form in VB.NET

Connecting to our database
The ConnectionString will vary from machine to machine. To automatically determine the connection string to our database we can do the following:
1 – Click DataBindings in the Properties window. Click F4 if you cannot see the properties window or add it on View – Properties Window.

2 – Under DataBindings, click on Text – Add Project Data Source. This will call up the Data Source Configuration Wizard.

3- Choose Database as your Data Source Type and click Next.

4- Choose Dataset as your Database Model and click Next.

5 – Click on New Connection

6 – Click on Microsoft Access Database File as your Data Source and click Continue

7- The Add Connection window appears. Beside the ‘Database file name:’ click Browse. Locate the database file that we created above.
8 – Click the Test Connection. You should get the test connection succeeded message.

9 – Click OK to close the Add Connection wizard. Expand the “Connection string that you will save in the application”. Copy the connection string given and paste it on conn.ConnectionString.
Note: Copy – ctrl + C / Paste – ctrl + V

Here is the programming logic for the Cancel Button.
Private Sub ReturnToMainButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
MainForm.Show()
Me.Hide()
End Sub

In this program we are just writing a user level in PLC memory address MHR05. The control of the PLC can be limited if hardwired selector switches and pushbuttons were in the system. Implementing a login screen is very straight forward and can be part of your overall automation solution.

Download the access database and the Bin directory for the AdvancedHMI login screen.

The cylinder PLC program from Building a PLC Program That You Can Be Proud Of – Part 6 can be downloaded with the following link.
Download the PLC program and the Bin directory for the AdvanceHMI Screen.

Watch on YouTube : Creating a HMI Login Screen on AdvancedHMI – Explaining the Code
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 6

We will continue the series by looking at a sequencer controlling seven cylinders that can be taught. The cylinders can be operator programmed from the AdvancedHMI screen. You will be able to select what cylinders to activate at each step and program in 500 steps. Our PLC will be the Do-More from Automation Direct.

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.
In part 5 we used the AdvancedHMI software to create the game of Simon. 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.

We will be using AdvancedHMI to communicate Modbus TCP to the Automation Direct Do-More Designer Software Simulator. The following is the sequence of operation:
Watch on YouTube : Running the Cylinder Sequence (PLC / HMI)
Note: All of the  programs used are provided free of charge and are an excellent way to learn PLC / HMI programming.

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


Here are the inputs and outputs we will be using for our program:

Device Data Addresses Type Do-More PLC Description
Start Pushbutton 00011 Input MC11
Stop Pushbutton 00012 Input MC12
Jog Pushbutton 00013 Input MC13
Reset Pushbutton 00014 Input MC14
Run/ Jog Selector 00008 / 00015 Input/ Output MC8 / MC15  MC8 is the value and MC15 is the click
Light Stack 00010 / 00009 / 00008 Output MC10 / MC9 / MC8  Red / Green / Amber
Set Pushbutton 00071 Input MC71
Jog / Teach Selector 00070 Input MC70  MC70 on is teach mode
Sequence Step (Panel Meter) 40001 Output MHR1  Current step in the sequence
Inputs Actual 40002 Input MHR2  Show the actual inputs in binary format
Output Sequence 40003 Output MHR3  Show the actual outputs in a binary format
Input Sequence 40004 Input MHR4  Show the input sequence bits in a binary format
Cylinder 1 to 7 – value 00001 to 00007 Output MC1 to MC7  Determine if cylinder is on/off
Cylinder 1 to 7 – set (click) 00041 to 00047 Input MC41 to MC47  Set the cylinder button
Cylinder 1 to 7 – retract indicators 00021 to 00027 Input MC21 to MC27 Indicate cylinder has retracted
Cylinder 1 to 7 – extend indicators 00031 to 00037 Input MC31 to MC37 Indicate cylinder has extended
Cylinder 1 to 7 – extend / retract error indicators 00050 to 00063 Output MC50 to MC63 Indicate cylinder input error when jogging

The first thing we will do is design the HMI. We have three main areas on the screen. Basic Controls, Cylinder Visualization and the Sequence Step/Teach area. Please refer to the above reference chart for the inputs and outputs programmed on the screen.

Basic Controls:
This area will allow us to see what mode we are in via the stack light. Red – Stop
Yellow – Jog / Teach Mode – Troubleshooting
Green – Run

Cylinder Visualization:
Each cylinder will have indication lights to determine status of the cylinder. (Extended / Retracted)
The cylinder will also have red indication lights to reflect the differences between the current sequence and the next sequence step. This is visible when we are in jog mode.

Sequence Step/Teach:
When in jog or teach mode the sequence step is visible, which indicates the current step that we are on. The inputs and outputs are displayed as a binary value which represents the actual inputs and outputs. This is valuable when troubleshooting and finding errors in the system. The set button is visible when in teach mode. When pushed the outputs and inputs are set for that step and the sequence will then increment.

The following is the code for each of the words that the DataScribers are reading. This includes the code to change the word into a 16 bit binary value.

Private Sub DataSubscriber1_DataChanged(sender As Object, e As Drivers.Common.PlcComEventArgs) Handles DataSubscriber1.DataChanged
'Label1.Text = Hex(DataSubscriber1.Value)Dim i As Integer = DataSubscriber1.Value
Label1.Text = Convert.ToString(i, 2).PadLeft(16, "0") '16 bits
End Sub
Private Sub DataSubscriber2_DataChanged(sender As Object, e As Drivers.Common.PlcComEventArgs) Handles DataSubscriber2.DataChanged
'Label2.Text = Hex(DataSubscriber2.Value)
Dim i As Integer = DataSubscriber2.Value
Label2.Text = Convert.ToString(i, 2).PadLeft(16, "0") '16 bits
End Sub
Private Sub DataSubscriber3_DataChanged(sender As Object, e As Drivers.Common.PlcComEventArgs) Handles DataSubscriber3.DataChanged
Dim i As Integer = DataSubscriber3.Value
Label3.Text = Convert.ToString(i, 2).PadLeft(16, "0") '16 bits
End Sub
Private Sub DataSubscriber4_DataChanged(sender As Object, e As Drivers.Common.PlcComEventArgs) Handles DataSubscriber4.DataChanged
If DataSubscriber4.Value = True Then
     Label1.Visible = True
     Label2.Visible = True
     Label3.Visible = True
     Label4.Visible = True
     Label5.Visible = True
Else
     Label1.Visible = False
     Label2.Visible = False
     Label3.Visible = False
     Label4.Visible = False
     Label5.Visible = False
End If
End Sub

We will now look at the PLC ladder program. The program is broken down into several parts as follows:

ACC Automation
This is the main start / stop circuit of the program.
If we are in run mode the green light will be on. (MC9)
If we are not in jog mode (MC8) this circuit will be functional.

If we are not run mode (MC9) or in jog mode (MC8) then the stop mode is active.
This will turn on the red light. (MC10)

Run / Jog – Toggle Circuit
Flip Flop circuit to set the jog function

Move the outputs to the physical outputs when we go to run mode.

Indirect Addresses for the Program
V0 – Input pointer – 100 – 499
V1 – Output pointer – 500 – 999
V2 – Input pointer last step in sequence
V3 – Output pointer last step in sequence
V10 – Inputs to the sequencer
V20 – Outputs from the sequencer

Jog Mode – Jog Pushbutton

Reset the sequencer pointers. This will happen automatically in run mode or by hitting the reset button in jog or stop mode.

Teach Function
This first rung will activate the values so we can manually turn them off/on with the HMI screen.

This will reset the pointers when going into teach mode.

This will set the teach point and increment to the next step.

Show the current step of the sequence.
Note: 0 is the first step

Set the inputs for cylinders.
The actural physical input points would be inserted here.
HMI inputs from the cylinders have a 500ms delay to simulate the movement of the actual cylinder.

Set the actual inputs / sequencer inputs / sequencer outputs so we can monitor this on the HMI.

Set the outputs for cylinders.
This will set the physical output points Y1 to Y7.
This will also set the HMI cylinders MC1 to MC7 (00001 to 00007)

Diagnostic Bits for indicating the difference for the inputs to the PLC. This will show up as a red indication light on the cyclinder represented on the HMI.

This section of PLC logic will mimic the inputs from the cylinders.
Cylinder 1 – Retract MC21 (00021) – Extend MC31 (00031)
Cylinder 2 – Retract MC22 (00022) – Extend MC32 (00032)
Cylinder 3 – Retract MC23 (00023) – Extend MC33 (00033)
Cylinder 4 – Retract MC24 (00024) – Extend MC34 (00034)
Cylinder 5 – Retract MC25 (00025) – Extend MC35 (00035)
Cylinder 6 – Retract MC26 (00026) – Extend MC36 (00036)
Cylinder 7 – Retract MC27 (00027) – Extend MC37 (00037)

Between each funtion of the cylinder there is a time delay for the input to turn on and off of 500msec.

Cylinder 2 – Retract MC22 (00022) – Extend MC32 (00032)

Cylinder 3 – Retract MC23 (00023) – Extend MC33 (00033)

Cylinder 4 – Retract MC24 (00024) – Extend MC34 (00034)

Cylinder 5 – Retract MC25 (00025) – Extend MC35 (00035)

Cylinder 6 – Retract MC26 (00026) – Extend MC36 (00036)

Cylinder 7 – Retract MC27 (00027) – Extend MC37 (00037)

This is the end of the PLC program. You can see that the program is not very complicated once you break down the individual steps.

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 6b – Explaining the Program
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:

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:

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.

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


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


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

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.

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.

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.

Play the Sequence

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

Reset the sound during the playing of the sequence.

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

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

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

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.

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

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

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.

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

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.

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.

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.

The simulator is showing X0 on and we can then use the WX0 slider to change the PV value of the Panel Meter.

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-vs

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

http://sourceforge.net/projects/advancedhmi/

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.

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.

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.

We can now add the digital panel meter. From the toolbox select and drag the DigitalPanelMeter to our form.

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.

Add a MomentaryButton to our form by selecting and dragging it from the toolbox.

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.

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.

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.

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

2. Run downloaded file from Windows Explorer or command-line

Hit OK

I use the default directories where the program will be installed. Click the button to install.

Leave the program group to the default so I know what the program is after installation. Click continue.

Click OK
The OstroSoft Winsock Component is now installed.

Start Microsoft Excel.


Select ‘Developer’ along the top tabs.

If the Developer tab is not present then we must turn on the developer tab.
Select File | Options Select ‘Customize Ribbon’Check the ‘Developer’ under Main Tabs.

Under the Developer menu. Select ‘Visual Basic’
The Visual Basic Editor window will now be displayed.
From the menu – Tools | References
We can now add the OstroSoft Winsock Component to our application.
Select OK
Select Sheet1(Sheet1).

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

 

Communication to the PLC

Start the Do-More Designer software.
Under the Project Browser select ‘System Configuration’

Make note of the IP address. If you are running the simulator then this is automatically filled in.

Ensure that the Enable Modbus/TCP Server is checked. Also make sure that the TCP Port Number is 502.

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)

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

Running the program will produce the following:

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.