Implementing Tree View in PSLab Android App

When a task expands over sub tasks, it can be easily represented by a stem and leaf diagram. In the context of android it can be implemented using an expandable list view. But in a scenario where the subtasks has mini tasks appended to it, it is hard to implement it using the general two level expandable list views. PSLab android application supports many experiments to perform using the PSLab device. These experiments are divided into major sections and each experiments are listed under them. The best way to implement this functionality in the android application is using a multi layer treeview implementation. In this context three layers are enough as follows; This was implemented with the help from a library called AndroidTreeView. This blog will outline how to modify and implement it in PSLab android application. Basic Idea Tree view implementation simply follows the data structure “Tree” used in algorithms. Every tree has a root where it starts and from the root there will be branches which are connected using edges. Every edge will have a parent and child. To reach a child, one has to traverse through only one route. Setting Up Dependencies Implementing tree view begins with setting up dependencies in the gradle file in the project. compile 'com.github.bmelnychuk:atv:1.2.+' Creating UI for tree view The speciality about this implementation is that it can be loaded into any kind of a layout such as a linearlayout, relativelayout, framelayout etc. final TreeNode Root = TreeNode.root(); Root.addChildren( // Add child nodes here ); // Set up the tree view AndroidTreeView experimentsListTree = new AndroidTreeView(getActivity(), Root); experimentsListTree.setDefaultAnimation(true); [LinearLayout/RelativeLayout].addView(experimentsListTree.getView()); Creating a node holder Trees are made of a collection of tree nodes. A holder for a tree node can be created using an object which extends the BaseNodeViewHolder class provided by the library. BaseNodeViewHolder requires a holder class which is generally static so that it can be accessed without creating an instance which nests textviews, imageviews and buttons. Once the holder extends the BaseNodeViewHolder, it should override two methods as follows; @Override public View createNodeView(final TreeNode node, ClassContainingNodeData header) { } @Override public void toggle(boolean active) { } createNodeView() which inflate the view and toggle() method which can be used to toggle clicks on the tree node in the UI. The following code snippet shows how to create an object which extends the above mentioned class with the overridden methods. public class ExperimentHeaderHolder extends TreeNode.BaseNodeViewHolder<ExperimentHeaderHolder.ExperimentHeader> { private ImageView arrow; public ExperimentHeaderHolder(Context context) { super(context); } @Override public View createNodeView(final TreeNode node, ExperimentHeader header) { final LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(R.layout.header_holder, null, false); TextView title = (TextView) view.findViewById(R.id.title); title.setText(header.title); arrow = (ImageView) view.findViewById(R.id.experiment_arrow); return view; } @Override public void toggle(boolean active) { arrow.setImageResource(active ? arrow_drop_up : arrow_drop_down); } public static class ExperimentHeader { public String title; public ExperimentHeader(String title) { this.title = title; } } } Creating a TreeNode Once the holder is complete, we can move on to creating an actual tree node. TreeNode class requires an object…

Continue ReadingImplementing Tree View in PSLab Android App

Developing Control Panel for Sensor Activity in PSLab Android

Once we are able to capture data from the sensor using the PSLab device and stimulate it on PSLab Android App, we now require to provide the user various control options. These control options help the user to customize the data captures from the sensors. These options are available for all the sensors. Number of samples: This allows the user to enter the number of samples he/she wants to capture. Indefinite mode: This allows the user to capture indefinite samples from the sensors. Play/Pause: This allows the user to start or pause the capture anytime. Time-gap: User can set the time-gap between each sample capture. Let’s discuss how to implement these control options in PSLab Android. Creating layout for Control Panel Initially, a control panel is created. A separate layout is created for the same in the sensor activity. Inside the layout, we added An Image-Button which works as a play and pause button An Edit-Text in which the user can enter the number of samples to be captured. A Check-Box which enables indefinite sample capture. A Seek-Bar which sets the time-gap between each sample capture. Adding functionality to widgets. Image-Button on-click listener has two roles to play. One role is to change the play image to pause image or vice versa and another is to set boolean variable true or false. This variable is used to stop or start the thread which is involved in fetching data from the sensor. playPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (play) { playPauseButton.setImageResource(R.drawable.play); play = false; } else { playPauseButton.setImageResource(R.drawable.pause); play = true; } } }); The play variable can be accessed by the different fragment to pause or resume the capture of the data from the sensors. if (scienceLab.isConnected() && ((SensorActivity) getActivity()).play) { //rest of the code } The number entered in the Edit-Box work as the maximum limit of samples to be captured. For this, a simple counter function is implemented. If the count value reaches the value in Edit-Box the thread is AsyncTask for fetching sensor data is not called any further. Enabling the Check-Box, disables the Edit-Box and hence eliminate the role of counter function resulting in AsyncTask (for fetching sensor data) being called indefinitely. Time gap Seek-Bar sets the delay between each time AsyncTask for fetching sensor data is called. The thread sleeps for  the time selected in the Seek-Bar before AsyncTask is called again. Here is the code snippet for it. try { Thread.sleep(((SensorActivity) getActivity()).timegap); } catch (InterruptedException e) { e.printStackTrace(); } This implements control panel for sensor activity in PSLab Android. To follow the entire code, click here. Resources Stack Overflow solution on how to change Imagebutton’s image onClick.

Continue ReadingDeveloping Control Panel for Sensor Activity in PSLab Android

I2C Communication in PSLab

PSLab supports communication using the I2C protocol and both the Desktop App and the Android App have the framework set-up to use the I2C protocol. I2C protocol is mainly used by sensors which can be connected to PSLab. For supporting I2C communication, PSLab board has a separate block for I2C communication and has pins named 3.3V, GND, SCL and SDA. A brief overview of how I2C communication works and its advantages & limitations compared to SPI communication can be found here. The PSLab Python and Java communication libraries have a class dedicated for I2C communication with numerous methods defined in them. The methods required for a particular I2C sensor may differ, however, in general most sensors utilise a certain common set of methods. The set of methods that are commonly used are listed below with their functions. For utilising the methods, the I2C bus is first notified using the HEADER byte (it is common to all the methods) and then a byte to uniquely determine the method in use. The send method is used to send the data over the I2C bus. First the I2C bus is initialised and set to the correct slave address using I2C.start(address) followed by this method. The method takes the data to be sent as the argument. def send(self, data): try: self.H.__sendByte__(CP.I2C_HEADER) self.H.__sendByte__(CP.I2C_SEND) self.H.__sendByte__(data) # data byte return self.H.__get_ack__() >> 4 except Exception as ex: self.raiseException(ex, "Communication Error , Function : " + inspect.currentframe().f_code.co_name)   The read method reads a fixed number of bytes from the I2C slave. One can also use I2C.simpleRead(address,  numbytes) instead to read from the I2C slave. This method takes the length of the data to be read as argument.  It fetches length-1 bytes with acknowledge bits for each. def read(self, length): data = [] try: for a in range(length - 1): self.H.__sendByte__(CP.I2C_HEADER) self.H.__sendByte__(CP.I2C_READ_MORE) data.append(self.H.__getByte__()) self.H.__get_ack__() self.H.__sendByte__(CP.I2C_HEADER) self.H.__sendByte__(CP.I2C_READ_END) data.append(self.H.__getByte__()) self.H.__get_ack__() except Exception as ex: self.raiseException(ex, "Communication Error , Function : " + inspect.currentframe().f_code.co_name) return data   The readBulk method reads the data from the I2C slave. This takes the I2C slave device address, the address of the device from which the data is to be read and the length of the data to be read as argument and the returns the bytes read in the form of a list. def readBulk(self, device_address, register_address, bytes_to_read): try: self.H.__sendByte__(CP.I2C_HEADER) self.H.__sendByte__(CP.I2C_READ_BULK) self.H.__sendByte__(device_address) self.H.__sendByte__(register_address) self.H.__sendByte__(bytes_to_read) data = self.H.fd.read(bytes_to_read) self.H.__get_ack__() try: return [ord(a) for a in data] except: print('Transaction failed') return False except Exception as ex: self.raiseException(ex, "Communication Error , Function : " + inspect.currentframe().f_code.co_name)   The writeBulk method writes the data to the I2C slave. It takes address of the particular I2C slave for which the data is to be written and the data to be written as arguments. def writeBulk(self, device_address, bytestream): try: self.H.__sendByte__(CP.I2C_HEADER) self.H.__sendByte__(CP.I2C_WRITE_BULK) self.H.__sendByte__(device_address) self.H.__sendByte__(len(bytestream)) for a in bytestream: self.H.__sendByte__(a) self.H.__get_ack__() except Exception as ex: self.raiseException(ex, "Communication Error , Function : " + inspect.currentframe().f_code.co_name)   The scan method scans the I2C port for connected devices which utilise I2C as a communication mode. It takes…

Continue ReadingI2C Communication in PSLab

High School Physics Practicals using PSLab Device

High school physics syllabus includes rather advanced concepts in the world of Physics; namely practicals related to sound, heat, light and electric. Almost all of these practicals are done in physics labs using conventional bulky equipments. Especially the practicals related to electrical and electronics. They use bulky oscilloscopes with complex controls and multimeter with so many controls. PSLab being a sophisticated device which integrates a whole science lab into a 2” by 2” small circuit, these practicals made easy and interesting. There are several practicals required to be completed by a student before sitting for GCE (Advanced Level) examination. This blog post points out how to perform those experiments using PSLab device and several other tools required without having to use bulky instruments. Calculating internal resistance and EMF of a dry cell This experiment includes the above mentioned circuitry. Once the basic setup is completed using; Dry cell 10K variable resistor 1K resistor Switch/Jumper Connect the CH1 pin and GND pin of PSLab across the dry cell and CH2 pin and GND across the Ammeter instead of the Ammeter. Once the pin connection is complete, plug the PSLab device to the computer and using the desktop application voltmeter, measure the voltage from CH1 and current from voltage value read from CH2 and the known resistance value of R. Record these data against step changes in the resistance of the variable resistor starting from a high value to a low value. Once there are sufficient data as much as 10 data set, using a graph paper draw the relation between current and voltage measured according to the equation given below. E = V + Ir V = -rI + E This will produce a graph with a constant negative gradient. Gradient of the graph will produce the internal resistance of the dry cell. I-V graphs for a semiconductor This experiment will require; Diode 100 Ohms resistor Conduct the experiment as follows once the circuit is set up. Increase the voltage provided by the PV1 pin of the PSLab by 100 mV per step and measure the voltage across diode using CH3 pin of PSLab device. Using that voltage and the supply voltage, calculate the current flowing through the resistor. Note down the readings as voltage to current pairs and plot them on a graph paper. The graph will produce the following results which is identical to common IV characteristics of a semiconductor. Start A at zero and increase by 0.1V steps while measuring voltage and current across diode. (Image from Wikipedia) Apart from this conventional experiment, PSLab provides an inbuilt experiment students and teachers can use. In the Electronics Experiments section, Diode IV characteristics experiment is configured in such a way that this experiment can be conducted very easily. The circuit configuration is the same and R value should be 1K. Once the step size is set to an appropriate resolution, START button will begin the experiment and provide with the final graph. Transfer characteristics of a transistor Set up the…

Continue ReadingHigh School Physics Practicals using PSLab Device

Using the Audio Jack to make an Oscilloscope in the PSLab Android App

The PSLab Android App allows users to access functionality provided by the PSLab hardware device, but in the interest of appealing to a larger audience that may not have immediate access to the device, we’re working on implementing some additional functionalities to perform experiments using only the hardware and sensors that are available in most android phones. The mentors suggested that the audio jack (Microphone input) of phones can be hacked to make it function as an Oscilloscope. Similarly, the audio output can also be used as a 2-channel arbitrary waveform generator. So I did a little research and found some articles which described how it can be done. In this post, I will dive a bit into the following aspects - AudioJack specifications for android devices Android APIs that provide access to audio hardware of device Integrating both to achieve scope functionality Audio Jack specification for android devices In a general audio jack interface, the configuration CTIA(LRGM - Left, Right, Ground, Mic) is present as shown in the image below. Some interfaces also have OMTP(LRMG - Left, Right, Mic, Ground) configuration in which the common and mic inputs are interchanged. In the image, Common refers to ground. If we simply cut open the wire of a cheap pair of earphones (stolen from an airplane? ;) ) , we  will gain access to all terminals (Left, Right, Common, Mic Input) illustrated in the image below Android APIs that provide access to audio hardware of device AudioRecord and AudioTrack are two classes in android that manage recording and playback respectively. We require only AudioRecord to implement scope functionality. We shall first create an object of the AudioRecord class, and use that object to read the audio buffer as and when required. Creating an AudioRecord object: we need the following parameters to initialise an AudioRecord object. SAMPLING_RATE: Almost all mobile devices support sampling rate of 44100 Hz. In this context, the definition is number of audio samples taken per second. RECORDER_AUDIO_ENCODING: Audio encoding describes bit representation of audio data. Here we used PCM_16BIT encoding this means stream of bits generated from PCM are segregated in a set of 16 bits. getMinimumBufferSize() returns minimum buffer size in byte units required to create an AudioRecord object successfully. private static final int SAMPLING_RATE = 44100; private static final int RECORDING_CHANNEL = AudioFormat.CHANNEL_IN_MONO; private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; private AudioRecord audioRecord = null; private int minRecorderBufferSize; minRecorderBufferSize = AudioRecord.getMinBufferSize(SAMPLING_RATE, RECORDING_CHANNEL, RECORDER_AUDIO_ENCODING); audioRecord = new AudioRecord(       MediaRecorder.AudioSource.MIC,       SAMPLING_RATE,       RECORDING_CHANNEL,       RECORDER_AUDIO_ENCODING,       minRecorderBufferSize); audioRecord object can be used to read audio buffer from audio hardware using read() method. minRecorderBuffer size is in byte units and 2 bytes constitute a short in JAVA. Thus size of short buffer needed is half the total number of bytes. short[] audioBuffer = new short[minRecorderBufferSize / 2]; audioRecord.read(audioBuffer, 0, audioBuffer.length); Now audioBuffer has the audio data as a signed 16 bit values. We need to process the buffer data and plot the processed data points on chart to completely implement scope functionality.…

Continue ReadingUsing the Audio Jack to make an Oscilloscope in the PSLab Android App

Characteristization of Transistors Using PSLab

Transistors are one of the key building blocks of all electronics. They are fundamentally three-terminal semiconductor devices, with the terminals being labelled as the Emitter(E), Base(B), and Collector(C). These active components are found everywhere in electronics, and all of the complex processors that power everything from cellphones to aircraft employ millions of these devices in switching and amplification roles. In this blog post, we shall use the PSLab to explore some of the fundamental properties of transistors, and their various applications. Transistor as an amplifier In the schematic shown, we shall try to use an NPN transistor to amplify a small signal. A small amplitude oscillation generated by W1 with the amplitude knob turned down to a very low level is used as the input. Since transistors do not handle bipolar signals, we have mixed a constant DC voltage generated PV3 to shift this small signal into the positive domain. The fluctuating potential difference incident at the base of the transistor creates a corresponding current flow between the Base and Emitter. By the fundamental property of transistors, this influences the path resistance between the Collector(C) and the Emitter(E) , and the resultant amplified voltage output can be monitored at the junction between the 1K resistor and the collector. We have used CH1 to monitor the input voltage, and CH2 for the output In a more applied scenario, we can implement the second schematic in order to create an audio amplifier. Instead of using W1 as the input signal, a speaker is used as a microphone. When a sound signal is incident on the speaker, its membrane oscillates, and as a result , the coil attached to it also does the same. Since this coil is placed in a magnetic field , its oscillations result in a change in the magnetic flux passing through, and this change causes a voltage(EMF) induced at its output. We then use our transistor amplifier to amplify this small EMF Common Emitter Characteristics Any introductory course on transistors includes a diagram similar to the one shown , and a description about how for any base current, the collector current eventually saturates, and that this saturation level is proportional to the base current itself. With the PSLab’s transistor CE characterization app, we can set up this experiment, and verify this for ourselves using an NPN transistor. The results shown were gathered using a 2N2222 transistor In the schematic , the base current is determined by the voltage source PV2, and a high value series resistor of 200 KOhms . We use an analog input CH3 to monitor the voltage present at the Base of the transistor in order to calculate the total base current. Base current = V/R = (PV2 - CH3) / 200e3 Now that we have set a particular base current, PV1 is used to sequentially increase the voltage across the collector and emitter of the transistor. A current limiting resistor of 1K Ohm is used, and CH1 is used to monitor the voltage drop…

Continue ReadingCharacteristization of Transistors Using PSLab

Making Custom Change Listeners in PSLab Android

In this post we are going to learn how to make custom change listeners. There are many use cases for custom change listeners like if you want to initiate some action when some variable’s value is changed. In PSLab android app, this was required during initialisation of PSLab hardware device, it takes about 3-4 seconds to initialise the device which includes reading calibration data from device and process it. So before starting the initialisation process, app notifies user with the message, “Initialising Wait …” and after initialisation is done, user is notified with the message “Initialisation Completed”. There might be other ways to accomplish this but I found making a custom change listener for boolean and trigger notifying user action on change of boolean value to be most organised way to do it. Another way I can think of is to pass the fragment reference to the class  constructor for which the object is to be made. And Views need to be made public for access from that object to change status after some work is done. Let’s look at an example, we would change status in a fragment after some task in object instantiation is completed. Implementation Class with variable on which custom change listener is required: Create a class and declare a variable for which you want to listen the value change to trigger some action. In this example we have created a InitializationVariable class and defined a boolean variable named initialised. Define an interface inside the class and that’s where the trick lies. When you set/change the value of the variable through a function setVariable(boolean value) in this case, note that we are triggering the interface method too. public class InitializationVariable {   public boolean initialised = false;   private onValueChangeListener valueChangeListener;   public boolean isInitialised() {       return initialised;   }   public void setVariable(boolean value) {       initialised = value;       if (valueChangeListener != null) valueChangeListener.onChange();   }   public onValueChangeListener getValueChangeListener() {       return valueChangeListener;   }   public void setValueChangeListener(onValueChangeListener valueChangeListener) {       this.valueChangeListener = valueChangeListener;   }   public interface onValueChangeListener {       void onChange();   } } Create an object of above class in activity/fragment: Create an object to the class we just made and attach onValueChangeListener to it. This example shows how it's used in PSLab Android, you can use it anywhere but remember to access view elements from a valid context. public static InitializationVariable booleanVariable; public class HomeFragment extends Fragment {   @BindView(R.id.tv_initialisation_status)   TextView tvInitializationStatus;   public static InitializationVariable booleanVariable;// object whose value change is noted   public static HomeFragment newInstance() {       HomeFragment homeFragment = new HomeFragment();       return homeFragment;   }   @Nullable   @Override   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {       View view = inflater.inflate(R.layout.home_fragment, container, false);       unbinder = ButterKnife.bind(this, view);       return view;   }   @Override   public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {       super.onViewCreated(view, savedInstanceState);       booleanVariable.setValueChangeListener(new InitializationVariable.onValueChangeListener() {           @Override           public void onChange() {               if (booleanVariable.isInitialised())                   tvInitializationStatus.setText("Initialsation Completed");               else                   tvInitializationStatus.setText("Initialising Wait ...");           }       });  } } Now whenever booleanVariable.setVariable(value) is called, it triggers the onValueChangeListener where you can manage the action you wanted to do on value change. This…

Continue ReadingMaking Custom Change Listeners in PSLab Android

Opening Local HTML Files in PSLab Android App

The PSLab Android App allows users to perform experiments using the PSLab device. The experience to perform an experiment should resemble the generic way to perform the experiment. So we associated an Experiment Doc file which the user can refer to while performing experiment. Just like a regular lab manual, the experiment doc contains the AIM, THEORY & FORMULAS, SCHEMATIC, OUTPUT, etc. In the PSLab Desktop App, since there was already a provision for using HTML docs and so I  avoided reinventing the wheel and used those html files as it is.      The problem we faced was how to open a bunch of HTML files with their corresponding CSS, JS files in Android’s webView. There are two ways it can be done: Host the experiment docs on a server and make a request from the android app for the specific experiment doc like Diode I-V, Zener I-V, etc. Put the folder containing all html, CSS, js files in assets folder and request for the HTML doc files locally. The PSLab developer team went with the second option as the availability of  Internet  is necessary for the performing experiment if we follow the first option and so to avoid this dependence on the Internet, we went with the second option and stored HTML docs locally in assets folder. Implementation Put the folder containing all the HTML, CSS, JS files in the assets folder in your android project. In this case the folder is DOC_HTML. Define the WebView in xml and take the webView’s reference in your activity/fragment In xml <WebView   android:id="@+id/perform_experiment_wv"   android:layout_width="match_parent"   android:layout_height="match_parent" /> In activity/fragment webView = (WebView) view.findViewById(R.id.perform_experiment_wv); Load the url in webView in the format as shown below webView.loadUrl("file:///android_asset/DOC_HTML/apps/" + htmlFile); “file:///” acts as resource identifier, so "file:///android_asset/” actually points to “pslab-android/app/src/main/assets/”. From the assets directory, we can a provide route to any HTML file. Here I put all HTML files in apps folder and used the string variable “htmlFile” to point to the specific html file. Similarly html files stored in the external storage can also be accessed but there are some cases you need to handle. For example,if external storage is mounted, you can’t request the html file from external storage. To request html files from external storage, make sure that you have the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath(); Relative to baseDir you can specify the path from your html files, like baseDir + “DOC_HTML/apps” + htmlFile Conclusion Putting HTML files in the assets folder and requesting it by webView’s loadURL() method is the best but there are various drawbacks of using this method like the increase in size of the apk. In our case, the normal apk size was 3MB but after adding the html doc folder it increased to 7MB. It increased by almost an additional size of the html folder added in assets. As it's written, in the android’s project overview guide, the assets folder contains files that should be compiled into an .apk…

Continue ReadingOpening Local HTML Files in PSLab Android App

Custom SeekBar in PSLab Android

By default Seekbar in Android only return integer values greater than zero. But there can be some situation where we need the SeekBar to return a float and negative values. To implement trigger functionality in the Oscilloscope activity of PSLab Android app, we require a SeekBar that sets a voltage level that should trigger the capture sequence. Since this voltage value ranges between -16.5 V to 16.5 V, default Seekbar don't serve the purpose. The solution is to create a custom SeekBar that returns float values. Let’s understand how to implement it. Create a FloatSeekBar class which extends AppCompatSeekBar. Create a constructor for the class with Context, AttributeSet and defStyle as parameters. AttributeSet is the set of properties specified in an XML resource file whereas defStyle is default style to apply to this view. public class FloatSeekBar extends android.support.v7.widget.AppCompatSeekBar { private double max = 0.0; private double min = 0.0; public FloatSeekBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); applyAttrs(attrs); }   Then define setters method which set the max and min values of the SeekBar. This method basically sets the range of the SeekBar. public void setters(double a, double b) { min = a; max = b; }   getValue is a method that manipulates current progress of the SeekBar and returns the value. Here the equation used to determine the value is (max - min) * (getProgress() / getMax()) + min. public double getValue() { DecimalFormat df = new DecimalFormat("#.##"); Double value = (max - min) * ((float) getProgress() / (float) getMax()) + min; value = Double.valueOf(df.format(value)); return value; }   setValue method takes the double value, and accordingly set the progress of the SeekBar. public void setValue(double value) { setProgress((int) ((value - min) / (max - min) * getMax())); } This creates a custom SeekBar, it can be used just like a normal SeekBar. Now, set the range of custom SeekBar between -16.5 and 16.5. seekBarTrigger = (FloatSeekBar) v.findViewById(R.id.seekBar_trigger); seekBarTrigger.setters(-16.5, 16.5);   In order to get value of the custom SeekBar call getValue method. seekBarTrigger.getValue(); In order to follow the entire code for custom SeekBar implementation in PSLab refer FloatSeekBar.java, Attr.xml and TimebaseTrigger.java. A glimpse of custom SeekBar in PSLab Android. Resources Android.com reference for AttributeSet Android.com reference for Custom Attributes Niusounds: Custom SeekBar for Android  

Continue ReadingCustom SeekBar in PSLab Android

Comparing Different Graph View Libraries and Integrating Them in PSLab Android Application

There is a significant role of graphs in PSLab, they're used for the following purpose: To plot voltage signals from analog inputs in Oscilloscope Activity. To plot digital signals in Logical Analyzer Activity. To plot data points from various sensors. For this, we need to implement real time graphs that stimulate real time data from the PSLab device efficiently. It is necessary to analyze each and every Graph View Library, compare them and integrate the best one in PSLab Android app. Available Graph Libraries The available Graph View libraries of Android are: MPAndroidChart Graph-View SciChart Which one is the best with respect to the PSLab project? MPAndroidChart Line Graph plotted using MPAndroidChart (image source) It is an open source graph view library by Philipp Jahoda. The following are the features of MPAndroidChart There are 8 different chart types Scaling on both axes. Scaling can be done using pinch zoom gesture. Dual Axes, we can have 2 Y-axis. Real time support Customizable axis ie we can define different labels to the axis Save chart to SD-Card Predefined color templates Legends which are used to define which line depicts what. Animations Fully customizable, from background color to color of the lines and grids. On trying MPAndroidChart, I found it to be a slightly difficult to implement. Graph-View Line Graph plotted using GraphView Library (image source) It is also an open source graph view library by Jonas Gehring. The following are features of the Graph-View Supports Line Chart, Bar Chart and Points. Scrolling vertical and horizontal Scaling on both axes. Realtime Graph support Draw multiple series of data. Let the diagram show more that one series in a graph. You can set a color and a description for every series. Legends (as discussed in MPAndroidChart) Custom labels Manual Y axis limits can be set. SciChart It is rich APIs for Axis Ranging, Label Formatting, Chart Modifiers (interaction) and Renderable Series. It is packed with features but unfortunately, it is not open sourced. The Verdict Both MPAndroidChart and Graph-View are good libraries, packed with a lot of features. GraphView is easier to implement as compared to MPAndroidChat (not that difficult either). Both of them have the features like pinch zoom. MPAndroidChart had the feature of scale adjustment even when the graph is being plotted. The rate of plotting was comparable in both but it was slightly faster in MPAndroidChart. So, finally GraphView is easier to implement but MPAndroidChart has slightly better performance. So, we integrated MPAndroidChart in PSLab Android application. Integrating MPAndroidChart in PSLab Android App In order to integrate MPAndroidChart in the Android project add the following code in the build.gradle of your project.   compile 'com.github.PhilJay:MPAndroidChart:v3.0.1' Creating Oscilloscope like graph If we observe an Oscilloscope, it has a black/blue screen with grid lines. An oscilloscope is a voltage vs time graph hence the x axis represents the time elapsed and y axis the voltage of the signal at the instant of time. There are left and right y axis for different channels.…

Continue ReadingComparing Different Graph View Libraries and Integrating Them in PSLab Android Application