Introduction: Programming Raspberry Pi With CODESYS

Hello,

This instructable is essentially a tutorial to get you going using the CODESYS environment to program a Raspberry Pi.

This instructable is aimed not so much to hobbyists, but rather to budding control/automation engineers. Although CODESYS is also a nice alternative to using python to control the GPIO, I2C and the camera of the Pi.

For those who don't know, CODESYS is a PLC programming environment and is utilised by many industrial automation companies such as Bosch, Beckhoff, Festo, Eaton, Wago and many more. You can program using the traditional Ladder Logic to the more modern Structured text and Continuous Flow Chart (IEC 61131-3 standards).

Although usually very expensive and aimed at industrial environments, CODESYS released a target which essentially turns a RPi into a £25 PLC.

In this instructable I will be showing you how to control the GPIO of the Pi. I will also cover how to control relatively cheap Beckhoff I/O and a small Technosoft Servomotor over the EtherCat communication protocol, as well as creating a web visualisation to control the IO through your smartphone. It will cover quite a bit however I have structured it so hopefully you can pick and choose what you wish to do.

This instructable will not cover in depth how to actually program using the IEC standard languages, beyond some essentials of getting it moving, it focuses more on the hardware setup. If you want to learn more about this, I suggest visiting YouTube where you will find some good videos there.

If you get any problems with the sample programs I have uploaded, please give me a shout in the comments and I may be able to help.

I would like to thank Kurt Braun however of whose video I watched provided me the inspiration to try it out myself.

Step 1: Things You Will Need:

- Raspberry Pi (B, B+, 2 or 3)

- SD Card with latest Raspbian Jessie

- CODESYS Installed on your laptop/PC (Windows only)

- CODESYS Raspberry Pi target

- Ethernet cable

With the above you can play around with the system and control the GPIO. However if you wish to do anything over the industrial side of things using EtherCat, you will need on top of the above:

- Ethernet to USB adapter

- Another Ethernet cable

- 24V DC Power Supply (minimum 2A)

- Industrial EtherCat IO (with EtherCat XML file)

I used Beckhoff IO as this is what I am familiar with but it will work with others as long as they are compatible. You can find some cheap Beckhoff gear on ebay. You will need a a Bus coupler, EK1100, and then any number of IO (digital, analog, encoder cards, stepper motor driver etc.). I have 1x 8 digital In (EL1008) and 1x 8 digital out (EL2008). For information see http://www.beckhoff.co.uk/.

If you wish to control an industrial servomotor you will need an industrial servomotor and EtherCat servomotor driver, these can be very expensive but you can find them on ebay. I managed to borrow one from work, which is fortunate otherwise I wouldn't have the opportunity to learn to control it using the Pi.

Step 2: Installing CODESYS

3S Smart Systems don't make it as simple to get CODESYS for the Raspberry Pi downloaded and up and running as simple as you would hope. However if you stick with it you will be rewarded with a simple to use programming environment.

To download CoDeSys (COntroller DEvelopment SYStem) please go to the following link:

https://www.codesys.com/download

Scroll down and click on "Download Center as a Codesys user".

Before actually downloading the program you must first get some some login credentials. Click on the "Registration" link (in red) and then you will have to select a country and fill in a form. You will then receive an email with some login credentials.

If you return back to the download center (where you clicked on the red registration link), you can now download the exe file for the latest CODESYS V3 after entering the username and password.

Once the file has been downloaded, open the exe file and if windows attempts to block it select "run anyway". Follow the install wizard through. I have noticed occasionally when downloading this you get an error and the install wizard won't start, if this happens, try re downloading the exe file.

If you are struggling for space, you only need to install the following features:

- CODESYS V3

- CODESYS Gateway

- CODESYS OPC Sever

Once you have installed CODESYS you now need to add the Raspberry Pi Package to it. In order to do this you first have to visit the CODESYS store and download the package. The store states a price of 35 euros, however this is only if you wish to run your program on the Pi for over 2 hours. Otherwise its completely free and you just need to re download the program to the Pi every 2 hours, after all CODESYS is targeted at industry...

http://store.codesys.com/codesys-control-for-raspb...

Unfortunately to download this you will need another username and password, so you will have to register for the CODESYS Store. If you click on the download button it will prompt you to login, if you follow this link you can register for the store. After signing up return back to the download page and click on download. Download this somewhere memorable, you will need it in the next step.

Once the package has been downloaded you will need to open up CODESYS and install it. I will explain how to do this in the next step.

Step 3: Connecting to the Pi

Now we have everything we need downloaded. It's time to open up to explore CODESYS and connect it to the Pi.

Open up CODESYS from your start menu or desktop shortcut, you will want to open up the one that says "CODESYS V3.5 SP8 Patch 2" (it was SP8 Patch 2 at the time of starting to write this Instructable). You should be presented with something that looks like the picture, with a start page showing latest CODESYS news etc.

Installing the Raspberry Pi Package we downloaded in Step 2.

- On the toolbar, select Tools > Package Manager...

- Click "Install.." at the top right of new window.

- Find and select the package you downloaded earlier.

- Follow the install wizard through, selecting complete install.

Now we are finally ready to start a project.

- From the toolbar, select File > New Project...

- Select Standard project, give it a name, choose a location to save it to and click OK.

- In the new window, under device, select "CODESYS Control for Rasperrby Pi" and under PLC_PRG, select "Structured Text (ST)".

You will have noticed at the left of the screen, a device tree has appeared (see picture). CODESYS has automatically created you a main program (PLC_PRG) and one task (MainTask) from which the PLC_PRG is called from. PLC's are real time devices which run tasks at different cycle times. Task management can be complicated so I will not go into this now however it is covered in Youtube tutorials on CODESYS. All you need to know is that the PLC_PRG will be cycled through every time the task is run (every 20ms by default), reading the inputs and setting the new outputs, essentially a massive continuous loop. We will write our first program to control the GPIO of the Pi in the next step. But first how to connect to the Pi.

- Boot up the Pi and plug into your router (or ethernet port of your PC, the important thing here is that the Pi is on the same network as the PC) with an Ethernet cable. You must use an Ethernet cable for the Pi, it doesn't work over Wifi (or it least it doesn't with me).

- Either using a monitor or by using a tool such as Advanced IP Scanner, take note of the IP address given to the Pi.

- Under the toolbar in CODESYS > Tools, click "Update RaspberryPI"

- If this does not appear you will have to cluck "Customize", expand the tools and click "Add Command..." Find Raspberry Pi and add the "Update RaspberryPI" to the toolbar menu.

- Enter your login information and the IP Address of the Pi.

- Once the Pi has been updated (you should get notified by the flashing orange message tab in the bottom left of the screen in CODESYS with the message saying "Update Finished").

- Double click on device in the device tree.

- From the new page which has been brought up, you should see your device name in a text entry field (see picture)

- Enter the IP address of the Pi here and press enter.

- You should now be connected to the Pi.

Note: You will have to do this every time you create a new project before you can run the program.

Step 4: GPIO Control

Now time for our first program, I have to apologise in advance here, due to the way I have written this Instructable, some of this information may be repeated in the next step, nonetheless , it's important stuff.

We are going to create a simple blinking routine to blink a LED connected to the GPIO of the PI. I shall leave it up to you to connect the LED, many other Instructables can be found which can offer advice on this. Alternatively you can not worry about the hardware element and just see the results on screen, (or use a multimeter on the pins).

- Start a new project in CODESYS and connect to the Pi the same way as shown in Step 3.

- Double Click on "PLC_PRG (PRG)" in the device tree.

- Now copy the text from my screenshot ( I have attached .txt document to make it easier) into the correct windows, noting the top window is to declare variables and the bottom is for the code. This is essentially a blinking routine based on two timers to blink the pin 4 on the GPIO. We now need to link our Variable "Output1" to our GPIO, to do this:

- Double click on "GPIOs_A_B(GPIOs A/B)" on the device tree. - Go to the "GPIOs Parameters" tab.

- On the row GPIO4, define the GPIO as an output by changing the value box to output by double clicking on it and selecting "Output" (see picture).

- Now select the tab "GPIOs I/O Mapping", expand th eouput selection and double click on the variable box of "Bit4" (For the Pin4 on the GPIO). (see picture) - Click on the "..." which has now appeared in the box. (see picture)

- Now we need to select the variable Output1, to find this follow Application > PLC_PRG then double click on "Output1". That output is now mapped to that variable.

- To run the program:

- Press "F11" on your keyboard, this builds/compiles the code. Also found under "Build" on the toolbar.

- Once the code has compiled, press "Alt + F8" on your keyboard to login to the Pi (or the PLC to now give it it's correct name). Also found under "Online" on the toolbar.

- Click "Yes" on the pop up to download the program.

- Once the program had downloaded, press "F5" to run the program. Also found under "Debug" on the toolbar.

- You should now see a live stream on your screen of what is happening, the variables on the code should flash from True to False as the program dictates. You should also see your LED blink if you chose to wire it up.

- To stop the code press " Shift + F8" on your keyboard. Also found under "Debug" on the toolbar.

At this point, if you do not have any 'industrial' IO or motors, feel free to take a look at the Visualisation step, but try applying it to this project, not the Industrial IO.

Step 5: Industrial IO Control

Now for this step we will need the additional parts as detailed in Step 1.

Wiring the system:

- Slide the industrial IO modules together. (see picture)

- Connect the industrial IO module to your 24V power supply. (see picture) ( All the wires I am holding out the way are just looping the digital outputs to the digital inputs for testing)

- Power the IO on.

We will also need to connect the Pi up slightly differently. You will need to connect the Pi to your network connection through your USB to Ethernet adapter. Bare in mind this will probably give us a different IP address to earlier and will appear next to device "eth1" on the Pi when using the command "ifconfig".

- Connect the Pi to your network through the adapter using one Ethernet cable.

- Connect the IO (using the top port) to the Pi's Ethernet port using the other Ethernet cable.

- Power on the Pi.

Before we can connect the IO, we will now need to make sure you have the device description XML files from the industrial IO manufacturer and these are added to CODESYS.

- If you are using Beckhoff the XML files can be found here:

http://www.beckhoff.co.uk/english.asp?download/elc...

- Download and unzip the zip file somewhere safe.

- Open CODESYS, from the toolbar select Tools > Device Repository...

- Click "Install..."

- Navigate to the folder you just unzipped and select the XML file "EKxxxx" and click open, CODESYS will automatically install the device.

- Repeat the above 2 steps for all other devices you brought, in my case for EL1008 and EL2008 I install "EL1xxx" and "EL2xxx".

Now to connect to the industrial IO using CODESYS:

- Start a new project in CODESYS and connect to the Pi the same way as shown in Step 3.

- Right click on "Device" on your device tree and select "Add Device...".

- From the new window (see picture) select "EtherCAT Master" and click "Add Device".

- Close the window.

- Right click on "EtherCat_Master" on your device tree and select "Add Device...".

- Select "EK1100" from EtherCat > Slave > Beckhoff Automation System Couplers and click "Add Device...".

- Close the window.

- Right click on "EK1100" on your device tree and select "Add Device...".

- Select the first of your IO modules, in my case the "EL1008" from EtherCat > Slave > Beckhoff Automation Digital Input Terminals and click "Add Device...".

- Repeat the above step for all additional IO in order of how they are connected to the system coupler.

There is a scan feature you can use to automatically add all IO but I will not cover that in this instructable as it is good to understand how CODESYS builds up the IO.

We will now need to find out the hardware (MAC) address of the Pi's Ethernet port to tell CODESYS where to look for the IO, to do this either plug the pi into a monitor or SSH and use the command "ifconfig" in the terminal. You are looking for the code next to HWaddr from the port eth0 (see picture).

Once you have the address we need to add it to CODESYS:

- From the device tree, double click on "EtherCAT_Master".

- Enter the hardware address from earlier into the text entry field "Source Address (MAC)".

All the hardware is now setup and we are now ready to create our first program to control the industrial IO.

- Double Click on "PLC_PRG (PRG)" in the device tree.

- Now copy the text from my screenshot ( I have attached .txt document to make it easier) into the correct windows, noting the top window is to declare variables and the bottom is for the code. This is essentially a blinking routine based on two timers to blink the output 1 LED from The Beckhoff IO.

We now need to link our Variable "Output1" to our Beckhoff IO, to do this:

- Double click on "EL2008" on the device tree.

- Go to the "EtherCAT I/O Mapping" tab.

- Double click on the first variable box. (see picture)

- Click on the "..." which has now appeared in the box. (see picture)

- Now we need to select the variable Output1, to find this follow Application > PLC_PRG then double click on "Output1". That output is now mapped to that variable.

To run the program:

- Press "F11" on your keyboard, this builds/compiles the code. Also found under "Build" on the toolbar.

- Once the code has compiled, press "Alt + F8" on your keyboard to login to the Pi (or the PLC to now give it it's correct name). Also found under "Online" on the toolbar.

- Click "Yes" on the pop up to download the program.

- Once the program had downloaded, press "F5" to run the program. Also found under "Debug" on the toolbar.

You should now see the output 1 LED on the Beckhoff Terminal blink at a 1 second interval. To see the code working, double click on "PLC_PRG" from the device tree and you should see a live feed of the status' of the variables.

To stop the code press " Shift + F8" on your keyboard. Also found under "Debug" on the toolbar.

Linking Inputs from EL1008 works in the same way. Try wiring the output 1 into input 1 and adding a variable to see the variable also switch between false and true.

You can now control Industrial grade IO using a raspberry Pi, think of the possibilities.

Some examples could include using Analog Inputs to monitor different sensors, PWM outputs to control motors etc.

If you encounter any issues, I have added my Codesys program file to the Instructable for comparison.

Step 6: Creating a Web Visualisation

In this chapter we are going to add a web visualisation allowing you to control the PLC and any IO connected to it from a remote browser, in this case Google Chrome on my android phone.

-In your existing project from the previous step, create another two BOOL variables in your "PLC_PRG" called "OutputVIS" and "Output2". And add the following line of code to the bottom your program:

Output2 := OutputVIS;

- Assign the "Output2" to the second output on the Beckhoff IO unit or Raspberry Pi GPIO as described in the previous step.

-Now, in the device tree (left hand side), right click on "Application", go to "Add Object..." - "Visualization".

- Check the "Active" box and click "Add" on the pop up (see picture).

- A new screen will appear (see picture). This is the page where we design our visualisation using the tools on the right hand side.

- From the toolbox, add a "Rocker Switch", by dragging and dropping the image onto your workspace. The rocker switch can be found under the "Lamps/Switch/Bitmaps" tab in the toolbox.

- Re size the switch to make it slightly bigger.

- Now, click on your rocker switch and a the toolbox screen should have changed to a properties screen, on this screen double click on the box next to "Variable" (see picture). Then click on the "..." that appears.

- Assign the variable "OutputVis" in the same way as assigning a variable to an IO device.

- This is our visualisation complete in the most basic way, if you wish, you can add more switches, buttons, lamps etc and a nice background, but for the purposes of showing you the functionality, we shall leave it there.

- Now when you log in and run the program in the same way as showed in the last step. Your visualisation should also load. You will notice when you toggle the rocker switch, the output on the IO turns on and off.

- Now, lets do this from your phone.

- Make sure your phone is on the same network as the Raspberry Pi.

- Go to your browser and type the following into the address bar:

"Your IP":8080/webvisu.htm

Replacing "Your IP" with the IP of the Raspberry Pi.

- You should now see the vis we created and be able to toggle the button and therefore the output from your phone - how cool is that!

If you encounter any issues please see the Codesys project file attached for comparison.

Try making a Vis of your own to control the GPIO in the project created in Step 4.

Step 7: Servomotor Control

If you are lucky enough to have access to a industrial grade servo (or stepper) and drive then this step will show you how to control that using the Raspberry Pi PLC.

I have managed to get my hands on a Technosoft EtherCat starter kit from work which contains one motor and the drive (see picture).

Details can be found here: http://www.technosoftmotion.com/en/starter-kits-an...

With this tutorial you could use any EtherCat drive and motor combination as long as you have the device description file(XML) from the manufacturer to import into Codesys. (You can also use the raspberry pi with other communication protocols to control different motors and IO but the configurations and steps to do this will be slightly different to everything I have described in this instructable). You may need to use some proprietary software to set up the drives.

SAFETY NOTE:

**When using motors please be careful as moving parts can be dangerous. Please also be careful to follow instructions from motor manufacturer and check all wiring is correct, especially with high voltage drives.**

- First step is to wire up your motor and drive according to the manufacturers instructions, in my case this was simple, all I had to do was add 24V to the logic and power in ports (see red and blue thicker cables in the picture), the rest came all wired up. Next, you have to link an ethernet cable between the EtherCat In port of your motor drive and the ethernet port of the Raspberry Pi. This is the same process as linking the Pi to the Industrial IO in Step 5.

If you want to use both the IO and the motor, leave the IO as it was and connect the ethernet cable from the EtherCat In port of the motor drive to the EtherCat out port of the Industrial IO. If you do this though, you have to make sure both devices are added to your device tree in Codesys. EtherCat is a brilliant fieldbus communication protocol allowing you to 'daisy chain' comms across loads of devices using only simple ethernet cables.

For this Instructable however we will just be using the motor on its own.

- When wiring is complete, we can move to programming.

- Following the same process as Step 5 open up a new project in Codesys and add a EtherCat Master and device, this time however choose the XML file that corresponds to that of the motor drive for the device (see picture of my device tree after adding this)

- We now need to add an axis to this device. This essentially means we are going to tell Codesys that this EtherCat device is controlling a motor. And within that what the parameters of the motor are.

- Right click on the device you have just added and click on "Add SoftMotionLight CiA402 Axis".

This is where The Raspberry Pi PLC idea falls down the smallest, smallest amount. As the Pi does not have a real time kernel and therefore no real time capabilities (although these can be added if you dare play with the Pi's kernel) it cannot handle the full capabilities of communication to a drive therefore we have to use the 'Light' version. In real speak, this means that the synchronicity of the motor to your program will not be as good as if it was a proper >£500 device. But who cares about that when it does everything else so well!

- Now Right Click on the new item of the device tree, go to " Refactoring" then "Rename". Rename the Axis "Axis1". Codesys will then bring up a new screen asking you to check if its found the right folder, click "OK".

- Double click on "Axis1" in the device tree and this will open up a new tab in the main window. This is where you need to calibrate the axis in your system, by choosing how many revolutions means what, so for example the motor I have has an encoder with 2000 increments per turn of the motor. I have no gearbox and I want to work in turns, not mm (if you had a linear axis on the motor). So my screen looks like the attached picture.

- Codesys takes care of most things for you with EtherCat so to now make the motor move all we have to do is write a program and utilise some built in Codesys functions.

- To make this easy, I have uploaded a sample program to this instructable written in CFC ( a language of Codesys), you can easily copy and paste the POUs (found under "Application" in the device tree") to your program. I have used some simple built in functions which are part of the "MC_Open" Codesys library which take care of moving the motor, I just have to tell them functions what motor I want to move, how far and how fast.

- When you have downloaded the program and entered run mode as described in Step 5. To move the motor, you need to open the "Motor_Control" POU, now you need to click on the variables "Distance", "Velocity" and "Accel" (see picture) in turn and enter numbers, e.g. 60, 60, 100. Do 60 turns and 60revs/min with an acceleration of 100revs/s/s. Now click on the variable "Power_Enable" until "True" shows next to the variable in blue, you now need to write this value to the PLC by clicking "Ctrl + F7". This will also write the values to the other variables we have changed.

- The motor should now be enabled, meaning it is powered on and holding position.

- To move the motor using "MC_MoveRelative_SML" (a relative move of the motors position as opposed to an absolute) you need to set the variable "Move_Motor_Pos" to "True" (in the same way as above). You may have to do this step twice to see the motor move, this is a bug which I do not quite understand. The motor should rotate, yay!

Now you have control over motors, try writing a program that rotates the motor back and forth. You can use the MC_Open functions in ST language too.

Step 8: Use Your Imagination

If you have managed to make it this far through all that text without falling asleep, I applaud you. However you should now be rewarded with the knowledge of using CODESYS, or a least be familiar enough and hooked enough by the idea to use it yourself. If the environment caught your fancy, I suggest checking out what else you can do using it, both within the hobbyist element and the industrial one.

See below for some good links below in case you need any other help:

Depending on the success of this instructable, I shall aim to get some more out there, perhaps focusing on some other RPi peripherals, as well as maybe some more industrial applications and maybe some on programming.

Happy Making!

http://forum.codesys.com/viewforum.php?f=21&sid=68...

https://www.youtube.com/user/WagoKurt

https://www.youtube.com/user/TheReimber

https://blog.adafruit.com/2015/12/11/how-to-use-ra...

**Shameless Plug**

If you are in the UK, I run a 3D printing Hub on 3dhubs.com, I have 3 printers at my disposal up to max build size of 280x220x230mm in various materials. If you would like to know more, please visit:

https://www.3dhubs.com/peterborough/hubs/beardy

Comments

author
JuanO42 (author)2017-09-19

Hi, Does somebody knows if this CodeSys on RPi deployment would work with the CodeSys IO Link deployment? Anyone tried something similar with IO Link? Thanks.

author
chrisbeardy (author)JuanO422017-09-19

I'm not sure the raspberry pi can be used as an IO link master

https://store.codesys.com/codesys-control-for-raspberry-pi-sl.html

unless possibly used with the beckhoff slice

https://store.codesys.com/codesys-io-link-master.html

author
davidl777 (author)2017-06-08

Hello,

Have you test the homing function with the tehnosoft driver?

author
chrisbeardy (author)davidl7772017-06-11

Do you mean using the MC_Homing in Codesys or using the drive itself as an intelligent drive?

Withing Codesys using MC_Homing yes I have, you need an external calibration flag though to let the FB know it's hit the datum sensor.

author
SAADIN2 (author)2017-05-23

This is very useful, thank you !!

author
chrisbeardy (author)SAADIN22017-05-30

no worries, you're welcome

author
captainhammer27 (author)2017-04-04

I have been trying to create a cheap slave device using Raspberry Pi or Arduino to test an EtherCAT system due to high costs of conventional components. I stumbled across these guys who sell hats/shields to convert a Pi/Arduino into an EtherCAT slave device for only $50. They also provide lots of code for both platforms for both master/slave devices free of charge. I'll leave this here in case anyone is interested =)

http://www.bausano.net/en/hardware/ethercat-e-ardu...

Thanks chrisbeardy for the great instructable. Lots of good info here.

author

this is awesome

author
Pavan_Padubidri (author)2017-03-22

Would you please tell me how to interface this Raspberry PI - CodeSYS controller as a OPC UA server ?

author

Hello, codesys OPC server does not support the raspberry pi runtime, only on more powerful controllers. you may be able to create an opc server on the pi using another software and access that using codesys on the pi to write to it. sorry I couldn't be of more help.

author
robbjosh (author)2016-08-30

Hi there,

Great Instructable! I followed it and got good results. I wanted to know if it's possible to get the Raspberry Pi to start in "Run Mode" once it powers up, so that there is no need to use a laptop to connect to the RPi to get it to run. I want to use the RPi as a standalone PLC with a 5" touch screen connected as my HMI. Everytime I restart the RPi I have to connect my laptop and set it to "Run Mode" Please help.

author
chrisbeardy (author)robbjosh2016-09-06

I've never actually tried with the raspberry pi so not sure. however as the other commenter suggests you should be able to download the boot project to the PLC. let me know if you've had success!

author
KHSQZ (author)robbjosh2016-08-30

Hi Robbjosh, I have the version 2.3 of Codesys for devices of Eaton Automation.

In this version, the procedure is:

Go to "Online" -> "Login"

"Online" -> "Run".

After you must to go again in "Online" and Click On "Create Boot Project".

In sequence, click on "Source Code Download".

Best Regards

Kaio Queiroz

author
tomatoskins (author)2016-06-07

This is great! I love how simple you make this!