In one of the first blog posts of the Pltouch series, we anticipated that the I/O library can be used in a way the PLC developers are familiar with (but it is not the only way of course).
PLC developers are accustomed to have a big infinite loop in which the code is executed sequentially. Conversely, in PC programs and in apps as well, this is not the case, there is no infinite loop and in mobile apps there are even many entry points.
Based on those assumptions, the learning curve of PLC developers that want to embrace the Android/Java world might be steep. In order to smooth the steepness of this learning curve, the Pltouch I/O library allows users to continue to use the PLC-style way of doing things even in the context of Android apps.
So, how to do that? Quite simple. Suppose that you already created an Android project, imported the I/O library and initialized it (eventually read our article in how to …). Let your activity implement the PltouchListener interface and place your PLC style code inside the onLogicExecution method, like for instance:
public class MainActivity extends Activity implements PlTouchListener{ private PltouchManager pManager; private TextView analog1; private TextView analog2;<span style="font-weight: 300;"> </span> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); analog1 = (TextView)findViewById(R.id.txtAnalog1); analog2 = (TextView)findViewById(R.id.txtAnalog2); pManager = new PltouchManager(this); pManager.setDebug(false); pManager.initialize(analog1, analog2); } @Override protected void onPause() { super.onPause(); pManager.teardown(); pManager = null; } @Override public void onLibraryTearedDown() { /* add clean up code */ Log.d("Pltouch", "library teared down"); } @Override public void onLogicExecution() { /* place here your PLC-style code */ Log.d("Pltouch", "on logic execution"); } }
The code inserted in the onLogicExecution callback will be executed sequentially and an infinite number of times. An important thing to know is that the statements contained in the onLogicExecution method will be executed in a different thread compared to the UI one. This means that if you need to update some graphical widgets from within that method, you have to call runOnUiThread, like in the example below:
@Override public void onLogicExecution() { Log.d("Pltouch", "on logic execution"); runOnUiThread(new Runnable() { @Override public void run() { try { if (pManager.digitalRead(1) == DigitalValues.HIGH){ analog1.setText("Digital Input 1 HIGH"); }else{ analog1.setText(""); } } catch (IndexOutOfBounds e) { e.printStackTrace(); } } }); }
where a TextView’s text is modified according to the value of the first digital input pin.