## Performing the Experiments Using the PSLab Android App

General laboratory experiments can be performed using core functionalities offered by the PSLab hardware device like Programmable Voltage Sources, Programmable Current Source, Analog to Digital Converter, Frequency Counter, Function Generators, etc. In this post we will  have a brief look on a general laboratory experiment and how we can perform it using the  PSLab Android App and the PSLab hardware device.

We are going to take Zener I-V Characteristics Curve experiment as an example to understand how we can perform a general experiment using the PSLab device. First, we will  look at the general laboratory experiment and it’s format. Then we will see how that experiment can be performed using the PSLab Android App and the PSLab Hardware Device.

#### Experiment Format of General Experiment in Laboratory

AIM: In this experiment, our aim is to observe the relation between the voltage and the corresponding current that was generated. We will then plot it to get the dependence.

Apparatus:

• A Zener Diode
• A DC Voltage Supplier
• 100 ohm resistor
• 2 multimeter for measuring current and voltages
• Connecting wires

Theory: A Zener Diode is constructed for operation in the reverse breakdown region.The relation between I-V is almost linear in this case, Vz = Vz0 + Iz * Rz , where Rz is the dynamic resistance of the zener at the operating point and Vz0 is the voltage at which the straight-line approximation of the I-V characteristic intersects the horizontal axis. After reaching a certain voltage, called the breakdown voltage, the current increases drastically even for a small change in voltage. However, there is no appreciable change in voltage accompanying this current change. So, when we plot the graph, we get a curve which is very near to the x-axis and nearly parallel to it until a particular potential value, called the Zener potential, is reached. After the Zener potential Vz value, there will be a sudden change and the graph becomes exponential.

Procedure: Construct the circuit as shown in figure below

Now, start increasing the voltage until a reading in the multimeter for current can be obtained. Note that reading. Now, start increasing the input voltage and take the corresponding current readings. Using the set of readings observed,  construct a V vs I graph. This graph gives us the I-V characteristics. The slope of the curve at any point gives the dynamic resistance at that voltage.

Result: The Characteristic curve has been verified after plotting V-I data points on the graph.

#### Experiment format in PSLab Android App

We have a ViewPager that renders two fragments:

1. Experiment Doc– It consists of information like the Aim of experiment, Schematic, Output screenshot that we will get after the experiment has been performed.
2. Experiment Setup– It consists of the setup to configure the PSLab device. This fragment is analogous to the experiment apparatus of the laboratory.

Below is a gif showing the experiment doc of the Zener I-V experiment which is to be performed using the PSLab device. It consists of a schematic and a screenshot of the output that we get after performing the experiment.

Make the circuit connections on a breadboard as shown in the schematic. After the circuit is complete we need to configure experiment.

To configure the experiment, we give the initial voltage, the final voltage and the step size. After clicking on START EXPERIMENT, the voltage is varied on the PV1 channel from the initial voltage to final voltage by increasing the voltage in step size. At each variation of voltage, the current is calculated by dividing the voltage difference between resistor by its resistance value i.e

`I = ( VPV1 - VCH1 ) / R`

As soon as the initial voltage reaches the final voltage, the experiment stops and data points are plotted on the graph. From the graph we can see the change in the current through a zener diode when the voltage varies across it’s terminals.

The output that was obtained after the experiment is I-V characteristic curve for Zener Diode as shown in the image below.

It can be clearly seen that after the breakdown voltage (~0.7V) the  current increases drastically with respect to the  increase in the voltage. After this point, the voltage can be considered  nearly constant unlike the current which varies exponentially.

In the PSLab Android App, there are read-back errors while reading bytes serially from the PSLab Hardware Device. As a result, the data points are not read accurately and an inaccurate plot is generated on the graph as shown in the image below.

#### Resources

Continue Reading Performing the Experiments Using the PSLab Android App

## SPI Communication in PSLab

PSLab supports communication using the Serial Peripheral Interface (SPI) protocol. The Desktop App as well as the Android App have the framework set-up to use this feature. SPI protocol is mainly used by a few sensors which can be connected to PSLab. For supporting SPI communication, the PSLab Communication library has a dedicated class defined for SPI. A brief overview of how SPI communication works and its advantages & limitations can be found here.

The class dedicated for SPI communication with numerous methods defined in them. The methods required for a particular SPI sensor may differ slightly, 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.

In the setParameters method, the SPI parameters like Clock Polarity (CKP/CPOL), Clock Edge (CKE/CPHA), SPI modes (SMP) and other parameters like primary and secondary prescalar which are specific to the device used.

Primary Prescaler (0,1,2,3) for 64MHz clock->(64:1,16:1,4:1,1:1)

Secondary prescaler (0,1,..7)->(8:1,7:1,..1:1)

The values of CKP/CPOL and CKE/CPHA needs to set using the following convention and according to our requirements.

• At CPOL=0 the base value of the clock is zero, i.e. the idle state is 0 and active state is 1.
• For CPHA=0, data is captured on the clock’s rising edge (low→high transition) and data is changed at the falling edge (high→low transition).
• For CPHA=1, data is captured on the clock’s falling edge (high→low transition) and data is changed at the rising edge (low→high transition).
• At CPOL=1 the base value of the clock is one (inversion of CPOL=0), i.e. the idle state is 1 and active state is 0.
• For CPHA=0, data is captured on the clock’s falling edge (high→low transition) and data is changed at the rising edge (low→high transition).
• For CPHA=1, data is captured on the clock’s rising edge (low→high transition) and data is changed at the falling edge (high→low transition).

```public void setParameters(int primaryPreScalar, int secondaryPreScalar, Integer CKE, Integer CKP, Integer SMP) throws IOException {
if (CKE != null) this.CKE = CKE;
if (CKP != null) this.CKP = CKP;
if (SMP != null) this.SMP = SMP;

packetHandler.sendByte(commandsProto.SET_SPI_PARAMETERS);
packetHandler.sendByte(secondaryPreScalar | (primaryPreScalar << 3) | (this.CKE << 5) | (this.CKP << 6) | (this.SMP << 7));
packetHandler.getAcknowledgement();
}
```

The start method is responsible for sending the instruction to initiate the SPI communication and it takes the channel which will be used for communication as input.

```public void start(int channel) throws IOException {
packetHandler.sendByte(commandsProto.START_SPI);
packetHandler.sendByte(channel);
}
```

The setCS method is responsible for selecting the slave with which the SPI communication has to be done. This feature of SPI communication is known as Chip Select (CS) or Slave Select (SS). A master can use multiple Chip/Slave Select pins for communication whereas a slave utilises just one pin as SPI is based on single master multiple slaves principle. The capacity of PSLab is limited to two slave devices at a time.

```public void setCS(String channel, int state) throws IOException {
String[] chipSelect = new String[]{"CS1", "CS2"};
channel = channel.toUpperCase();
if (Arrays.asList(chipSelect).contains(channel)) {
int csNum = Arrays.asList(chipSelect).indexOf(channel) + 9;
if (state == 1)
packetHandler.sendByte(commandsProto.STOP_SPI);
else
packetHandler.sendByte(commandsProto.START_SPI);
packetHandler.sendByte(csNum);
} else {
Log.d(TAG, "Channel does not exist");
}
}
```

The stop method is responsible for sending the instruction to the stop the communication with the slave.

```public void stop(int channel) throws IOException {
packetHandler.sendByte(commandsProto.STOP_SPI);
packetHandler.sendByte(channel);
}
```

PSLab SPI class has methods defined for sending either 8-bit or 16-bit data over SPI which are further classified on whether they request the acknowledgement byte (it helps to know whether the communication was successful or unsuccessful) or not.

The methods are so named send8, send16, send8_burst and send16_burst . The burst methods do not request any acknowledgement value and as a result work faster than the normal methods.

```public int send16(int value) throws IOException {
packetHandler.sendByte(commandsProto.SEND_SPI16);
packetHandler.sendInt(value);
int retValue = packetHandler.getInt();
packetHandler.getAcknowledgement();
return retValue;
}
```

Resources:

Continue Reading SPI Communication in PSLab

## 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();
);
// Set up the tree view
AndroidTreeView experimentsListTree = new AndroidTreeView(getActivity(), Root);
experimentsListTree.setDefaultAnimation(true);
```

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;

super(context);
}

@Override

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);

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 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 which extends the BaseNodeViewHolder class as mentioned earlier. Also it requires a viewholder which it can use to inflate the view in the tree layout. The viewholder can be a different class. The importance of this different implementation can be explained as follows;

```TreeNode treeNode = new TreeNode(new ExperimentHeaderHolder.ExperimentHeader(“Title”))
```

In the Saved Experiments section of PSLab android application, all the three levels shouldn’t implement the toggle behavior as a user clicks on the experiment (last level item), he doesn’t expect the icon to change like the ones in headers where an arrow points up and down when he clicks on it. In this case we can reuse a holder which has the title attribute while creating only a holder which does not override the toggle function to ignore icon toggling at the last level of the tree view. This explanation can be illustrated using a code snippet as follows;

```new TreeNode(new ExperimentHeaderHolder.ExperimentHeader(“Title”))
.setViewHolder(new IndividualExperimentHolder(context));
```

Creating parent nodes and finally the Root node

The final part of the implementation is to create parent nodes to group up similar experiments together. The TreeNode object supports a method call addChild() and addChildren(). addChild() method allows adding one tree node to the specific tree node and addChildren() method allows adding many tree nodes at the same time. Following code snippet illustrates how to add many tree nodes to a node and make it a parent node.

```treeDiodeExperiments.addChildren(treeZener, treeDiode, treeDiodeClamp, treeDiodeClip, treeHalfRectifier, treeFullWave);
```

Setting a click listener

Click listener is a very important implementation. Each tree node can be attached with a click listener using the interface provided by the library as follows;

```treeNode.setClickListener(new TreeNode.TreeNodeClickListener() {
@Override
public void onClick(TreeNode node, Object value) {

}
});
```

The value object is the class attached to the holder and its attributes can be retireved by casting it to the specific class using casting methods;

```String title = ((ExperimentHeaderHolder.ExperimentHeader) value).title;
```

Resources:

Continue Reading Implementing 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.

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 {
} 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 Reading Developing Control Panel for Sensor Activity in PSLab Android

## 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
• 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

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];

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. I am still looking for relation between the signed 16-bit value of audio buffer and actual mic bias voltage. According to android headset specs, Mic bias voltage is between 1.8-2.9V.

### Using AudioRecord class to create a scope in PSLab Android

In PSLab Android App, there is already an Oscilloscope made to capture and plot the data received from PSLab device. To make a cheap oscilloscope, cut open the wire of a cheap headset and expose terminals as illustrated in the image above and provide input signal at microphone input terminal.

Note: Don’t provide a voltage more than 2V at mic input terminal, it can damage your android device. To be sure check peak voltage from external voltmeter of the signal that you want to apply on scope and if it’s greater than 2V, I suggest you to first make a voltage divider to lower the voltage and then you are good to go.

To integrate plotting of audio buffer, we simply need to create another thread that captures audio data and updates the UI with the processed buffer data.

```public class captureAudioBuffer extends AsyncTask<Void, Void, Void> {

private AudioJack audioJack;
private short[] buffer;
public captureAudioBuffer(AudioJack audioJack) {
this.audioJack = audioJack;
}

@Override
protected Void doInBackground(Void... params) {
Log.v("AudioBuffer", Arrays.toString(buffer));
audioJack.release();
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// UPDATE UI ACCORDING TO READ BUFFER DATA
Log.v("Execution Done", "Completed");
}
}```

For complete code of AudioJack class, please refer pslab-android-app.

### Resources

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

## 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 is similar to how other listeners are implemented .You implement an interface and call those interface methods on some value change and classes which implement those interface have overridden methods which handle the action after change.

Hopefully this post gives you an insight about how change listeners are implemented.

Note: This post was specific to PSLab Android App, you can create custom change listener on any variable in any class and perform action on value of the variable getting changed.

### Resources

Continue Reading Making 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 file as-is.

### Resources

Continue Reading Opening 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

Continue Reading Custom 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:

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:

### 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.

An Oscilloscope

In order to implement a graph similar to that of Oscilloscope in PSLab Android App using MPAndroidChart library, the graph needed to be customized.

The following step was taken to customized the graph in Oscilloscope Activity.

### Background Color

```mChart.setBackgroundColor(Color.BLACK);
```

This sets the background color of the graph as black. mChart is an object of the Line graph.

### Legend

```Legend l = mChart.getLegend();
l.setForm(Legend.LegendForm.LINE);
l.setTextColor(Color.WHITE);
```

Here we are setting the Legend form. There are many options available for the same like SQUARE, CIRCLE, and LINE. We are using LINE Legend form.  Also, we set the white color for the legend text.

### X Axis Customization

```x = mChart.getXAxis();
x.setTextColor(Color.WHITE);
```

First, we create an object of XAxis and set the textcolor as white.

```x.setDrawGridLines(true);
```

The above method draws the grid lines along the x axis.

```x.setAxisMinimum(0f);
x.setAxisMaximum(875f);
```

Now we will set the range of x axis by setting minimum value as 0 and the maximum value is 875.

### Y Axis  Customization

```y1 = mChart.getAxisLeft();
y1.setTextColor(Color.WHITE);
y1.setAxisMaximum(16f);
y1.setAxisMinimum(-16f);
y1.setDrawGridLines(true);
```

This is similar to what we did in x axis formatting.

After performing the above steps we got the following results.

To follow the entire code for graph customization refer chartinit method in Oscilloscope Activity, PSLab Android repository.

### Resources

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

## Plotting Digital Logic Lines In PSLab Android App

The PSLab device offers the Logic Analyzer functionality. A Logic Analyzer is a laboratory instrument that can capture and display digital signals from a digital system or circuit. It is similar to what an oscilloscope is for analog signals and is used to study timing relationship between different logic lines. It plots the logic lines/timing diagram which tells us the information about the state of the Digital System at any instant of time. For example, in the image below we can study the states of digital signals from channels ID1, ID2, ID3 at different times and find parameters like the propagation delay. It’s also used to find errors in Integrated Circuits (ICs) and debug logic circuits.

How I plotted ideal logic lines using MPAndroid Chart library?

Conventional method of adding data points results in the plot as illustrated in the image below. By conventional method I mean basically adding Y-axis (logic state) values corresponding to X-axis values (timestamp).

In the above plot, logic lines follow non-ideal behaviour i.e they take some time in changing their state from high to low. This non-ideal behaviour of these lines increases when the user zooms in graph to analyse timestamps.

Solution to how we can achieve ideal behaviour of logic lines:

A better solution is to make use of timestamps for generating logic lines i.e time instants at which logic made a transition from HIGH -> LOW or LOW -> HIGH. Lets try to figure out with an example:

Timestamps = { 1, 3, 5, 8, 12 } and initial state is HIGH ( i.e at t = 0, it’s HIGH ). This implies that at t = 1, transition from HIGH to LOW took place so at t = 0, it’s HIGH, t = 1 it’s both HIGH and LOW,  at t = 2 it’s LOW.
Now at t = 0 & t = 2, you can simple put y = 1 and 0 respectively. But how do you add data-point for t = 1. Trick is to see how transition is taking place, if it’s HIGH to LOW then add first 1 for t = 1 and then 0 for t = 1.
So the set of points look something like this:

( Y, X ) ( LOGIC , TIME ) -> ( 1, 0 ) ( 1, 1 ) ( 0, 1) ( 0, 2 ) ( 0, 3 ) ( 1, 3 )  ( 1, 4 ) …

Code snippet for adding coordinates in this fashion:

```int[] time = timeStamps.get(j);
for (int i = 0; i < time.length; i++) {
if (initialState) {
// Transition from HIGH -> LOW
} else {
// Transition from LOW -> HIGH