Working with Logic Analyzer in PSLab application

This blog demonstrates the working of Logic Analyzer instrument available in PSLab Desktop Application. It also includes a detailed description of the features available in the Logic Analyzer instrument. Also, it provides a step by step guide on how to work with the Logic Analyzer provided by PSLab which will be beneficial to first-time users.

What is a Logic Analyzer?

A Logic Analyzer is an electronic instrument used to capture and display digital signals with an added functionality of providing the time difference between different edges of different pulses. It is mainly used to observe the time relationship between different digital signals. An example of a standard Logic Analyzer available in the market is as shown in figure 1.

Figure 1. Standard Logic Analyzer

How to generate different digital pulses in PSLab?

Logic Analyzer needs to be provided with some input of digital pulses among whom time relationship is to be found out. Digital pulses generated from different systems can be directly provided as input to the logic analyzer for analyzing. But PSLab provides a functionality to generate digital pulses up to some constrained frequency.

Following are the steps to generate different digital waves in the PSLab desktop application :

  • Go to Advanced Control Section of PSLab app. The screen should look like one as shown in Figure 2.

Figure 2.  Advanced Control Section

  • PSLab device provides generation of maximum four digital waves at once. In this example, I will proceed by utilizing all the four pins i.e. SQR1, SQR2, SQR3, SQR4 (where SQR = Acronym of square wave generator and the number next to it is the pin ID available on the PSLab device). Set the duty cycles for each of the pins as desired (try to keep all the duty cycles different from each other to understand the process of measurement easily). After setting it should look something like Figure 3.

Figure 3. Configuring PWM

NOTE: User can also set phase angle for different waves but I will proceed keeping all without any phase difference.

  • Now set the frequency of the digital waves in the tab provided next to text Frequency and then press the SET button. This should generate desired digital waves when connected.

How to analyze the generated waves in Logic Analyzer?

  • Now go to the Experiments section and click on the Logic Analyzer instrument as shown in Figure 4.

Figure 4. Test and Measurement Page

  • Now a screen as shown in Figure 5 should open which is the main screen for Logic Analyzer Instrument.

Figure 5. Logic Analyzer Main Page

On the right, you can see three buttons i.e Start, Plot Data and Raw Data. Below that selection for the number of channels is provided. And at last, the time measurement tool is provided which can measure the time difference between different edges of different digital waves. The graph at the center is the place where all the waves generated will be plotted.

  • Now as we have generated four different waves, we need to navigate to Four Channel Mode in the Channel Selection section. There you can observe four pins i.e. ID1, ID2, ID3, and ID4 are selected by default as shown in Figure 6. So, we need to connect the pins SQR1, SQR2, SQR3 and SQR4 with pins ID1, ID2, ID3 and ID4 on the PSLab device.

Figure 6. Channel Selection Section

NOTE: There are several options available for plotting the digital waves besides the one selected in the above image i.e.

  1. Every Edge – Plot every edge of the signal
  2. Falling Edges – Plot only falling edges of the signal (When a signal comes from 1 to 0 state)
  3. Rising Edges Only – Plot only rising edges of the signal (When a signal comes from 0 to 1 state)
  4. Disabled – Don’t plot the selected wave

Figure 7. Connecting wires on PSLab device

  • Connect the wires on the PSLab device as shown in Figure 7.
  • Now, as the device is connected, we can use the three buttons located at the top right corner to plot the digital waves. The functionalities of all the three buttons are as follows:
  1. Start – It collects exactly 2500 sample points from the wave generated to be plotted
  2. Plot Data – It plots the data on the graph if the samples are collected successfully
  3. Raw Data – It provides a sheet containing time at particular intervals and the difference between the data points at that particular time
  • Press the Start button and as soon as the samples are collected, press the Plot Data button. Then the screen should look something like Figure 8.

Figure 8. Final graph of input provided

Zoom in further, and the screen will look like Figure 9.

Figure 9. Zoomed In graph for better visualization

  • So now, the waves are plotted and are ready to be analyzed. Time difference between any two edges for any two distinct or a similar wave can be found out by using the TIME INTERVAL MEASUREMENT TOOL which is as shown in Figure 10.

Figure 10. Time Interval Measurement Tool

  • The working of this tool can be explained by taking an example as follow :

Figure 11. Configuring the Time Interval Measurement Tool

Suppose time difference between the rising edge of ID1 and falling edge of ID3 is to be measured. So, set the parameters as shown in Figure 11 for the following situation.

The timeout of the Logic Analyzer can be set to any desired value from 10mS to 9999 mS. Here, I will proceed with 10mS of the timeout. Now, press the measure button to see the result. It will be same as the Figure 12 shown below if all the configurations are set as the one in the  example :

Figure 12. Calculated time difference displayed

So in this way, many calculations can be taken out very easily and can be viewed at once at a single place without manually doing any calculations. Also, the data generated can be stored in the local system by pressing the Save Data button located at the bottom right corner.

Resources

  1. PSLab Desktop Application – https://github.com/fossasia/pslab-desktop-apps (Link to repo)
  2. PSLab device pins sticker – https://github.com/fossasia/pslab-artwork/blob/master/Sticker/pslabdesign.png

 

Continue ReadingWorking with Logic Analyzer in PSLab application

Implementing Card View in PSLab app

Card View was announced by Google in I/O ‘14 conference. Although it started a bit slow, but now we can see most of the apps like Snapchat, Google, Facebook, etc. using this widget. So, this blog is solely contributed on how to implement Card View in your own app by taking example of PSLab application.

What is Card View ?

CardView is a view container or ViewGroup that inherits its nature from FrameLayout which further inherits from ViewGroup itself. The only thing that separates a CardView from any other ViewGroups is its nature to behave like a card, more specifically the shadow and rounded corners. The basic customization that a CardView provides includes CornerRadius, Elevation, MaxElevation, ContentPadding, CompatPadding, PreventCornerOverlap, and a dedicated CardBackgroundColor or say Card Background which is the most necessary feature for a card to look cool.

Step by Step description how CardView was implemented in PSLab

  • First step is to add dependencies in your project as widgets like Card View, Recyclerview, etc. are not included in a common repository of widgets provided by Google.

App level dependency :

compile 'com.android.support:cardview-v7:26.0.0'
compile 'com.android.support:recyclerview-v7:+'

If you are using Android Studio 3.0+ than add the following dependency instead of above :

implementation 'com.android.support:cardview-v7:26.0.0'
implementation 'com.android.support:recyclerview-v7:27.1.1'
  •  Now we can use Card View widget in our app. So, first make add card view in layout section like this :
<android.support.v7.widget.CardView
    	android:id="@+id/card_view"
    	android:layout_width="match_parent"
    	android:layout_height="@dimen/total_height_card"
    	android:layout_gravity="center"
    	android:layout_margin="@dimen/card_margin"
    	card_view:cardCornerRadius="@dimen/card_radius">
 </android.support.v7.widget.CardView>

These are the basic attributes that are used while declaring a card view. Other possible attributes can be :

  1. Elevation – Used to elevate card to give a depth effect
  2. MaxElevation – Used to give constraint to the depth effect
  3. ContentPadding – Used to provide padding between content and the card
  4. PreventCornerOverlap – To prevent different corners to overlap as shown in figure 1.

Figure 1. Image showing corner overlapping in CardView

  • Now to set the objects inside the Card View, mostly RelativeLayout is preferred as it gives the freedom to place objects in reference of others whereas LinearLayout provides freedom to place them in only one direction. Other layouts such as FrameLayout, Tables, etc. can be used as per the need of the app.
  • Now we will create a layout that will hold all the cards using RecyclerView.
<android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
  • Now after setting the layouts, it’s time to make adapter which inflates the information in the cards which is then represented using RecyclerView.
public class ApplicationAdapter extends RecyclerView.Adapter<ApplicationAdapter.Holder> {

	private List<ApplicationItem> applicationList;
	private final OnItemClickListener listener;
	/**
 	* View holder for application list item
 	*/
	public class Holder extends RecyclerView.ViewHolder {

    	TextView header, description;
    	ImageView applicationIcon; //Background Image

    	public Holder(View itemView) {
        super(itemView);
        this.header = itemView.findViewById(R.id.heading_card);
        this.description = itemView.findViewById(R.id.description_card);
        this.applicationIcon = itemView.findViewById(R.id.application_icon);
    	}

    	public void setup(final ApplicationItem applicationItem, final OnItemClickListener listener) {
      header.setText(applicationItem.getApplicationName());
      description.setText(applicationItem.getApplicationDescription());
      applicationIcon.setImageResource(applicationItem.getApplicationIcon());
         }
	}

	public ApplicationAdapter(Context mContext, List<ApplicationItem> applicationList, OnItemClickListener listener) {
    	this.mContext = mContext;
    	this.applicationList = applicationList;
    	this.listener = listener;
	}

     @Override
	public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
    	View itemView = LayoutInflater.from(parent.getContext())
            	.inflate(R.layout.application_list_item, parent, false);
    	return new Holder(itemView);
	}

Following is the detailed explanation of each and every method :

  1. Holder(View ) – As name suggests, it holds all the items that are included in a single card together
  2. setup() – This method can contain any number of parameters as per requirement. It basically sets the data in the views in the card
  3. ApplicationAdapter() – Constructor
  4. onCreateViewHolder() – It inflates the layout containing CardView as soon as the data gets ready to be fed in it
  • Now as adapter is ready, we can declare RecyclerView in Java code to implement CardView. The main reason to use RecyclerView is that it provides the feature of scrollability so that a number of cards can be adjusted on the screen. ScrollView can also be used but it slows down the app as it tries to load all the card at once rather than loading cards as per use like RecyclerView.
RecyclerView listView = view.findViewById(R.id.applications_recycler_view);
    	RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(context, rows);
    	listView.setLayoutManager(mLayoutManager);
    	listView.setItemAnimator(new DefaultItemAnimator());
    	listView.setAdapter(applicationAdapter);

Here, we have used GridLayoutManager to use grids along with RecyclerView. It is optional and can be used as per requirement. Also, before setting adapter, fill the adapter with relevant data or else no card will be seen in actual app.

  • Now the app is ready to be built and tested on mobile device. This is how it looks in the PSLab application after implementing the above guide :

Figure 2. Screenshot of CardView implemented in PSLab app

So, in this way great user experience can be given by using this very basic widget. But great attention should be given while designing the objects inside the card as the selection and position of the objects is what makes the card look good. Objects used in making cards for PSLab very well suited the app and so are designed like that. Practice should be done by taking reference of some very good apps like Snapchat, Google, etc. and from Material Designs provided by Google before implementing them in actual project.

Resources

  1. https://www.androidhive.info/2016/05/android-working-with-card-view-and-recycler-view/ – This article gives a better practice by implementing a real world example
  2. https://developer.android.com/reference/android/support/v7/widget/CardView – Official documentation by Google on CardView
  3. https://developer.android.com/guide/topics/ui/layout/recyclerview – Official documentation by Google on RecyclerView

Continue ReadingImplementing Card View in PSLab app

Implementing Leak Canary in PSLab Android App

This post discusses the issue of memory leaks and how to handle them efficiently and what are the tools available which help developers in managing the memory leaks. After working on PR #824 opened under PSLab – Android repository I have got a greater idea about how to manage the memory efficiently and what are the tools that should be used to ease the work.

What are memory leaks and how it affects the quality of app?

In simple words, memory leaks happen when you hold on to an item for long after its purpose have been served. It is as simple as that. But let us dive in further to understand more about this topic. Programming languages like C and C++ need memory management done by user whereas in higher level languages like Java, Python, etc. low-level memory management and garbage collection is done automatically by the system. But it is due to programming faults that memory leaks happen and so care needs to be taken with higher level languages too in handling memory efficiently.

In Android or say in any OS (operating system), every item has to be destroyed or say deleted or freed from the memory after its purpose is served. But if the reference of this object is passed on to any other object which has a greater time of importance than this, then it will try to hold this object for long and so the garbage collector won’t be able to collect it and so there will be memory leaks in the code. This is how memory leaks occurs inside an app.

Now, the issue of memory leaks is utmost important among developers as due to it, the app becomes slow, laggy, eats up a lot of memory and the app crashes after some time of use which creates a very bad user experience. As the user keeps on using the app, the heap memory also keeps on increasing and due to memory leaks, this heap can’t be freed by the garbage collector. Thus, all these issues contribute to making the threads or processes running inside the app slower and it can result in a lag of time from microseconds to milliseconds too!!

How can you detect these memory leaks?

This blog is mostly for Android developers and so I will use the environment of Android Studio for reference. For controlling memory leaks, Android Studio has a very powerful tool named Monitors. There are individual monitors not only for memory usage but for CPU, GPU, and network usage as well. An example of it is shown in figure 1 below.

Figure 1. Monitor in Android Studio

Now how to observe the graphs that are produced by Monitors to see if there are any memory leaks? The first alarming case is when the memory usage graph constantly increases and doesn’t come down as time passes and even not decreases when you put the app in the background. The tools which are used to undo memory leaks as soon as they are found are:

  1. Allocation Tracker: The allocation tracker comes with an indicator to show the percentage of memory allocated to different types of objects in your app. The developer can have a clear idea about which object is taking what amount of memory and which objects are exceeding the memory limit. But it is itself not enough as the developer needs other tools to dump the extra memory.
  2. Leak Canary Library: It is the most used library by developers to check for memory leaks in an app. This library runs along with app and dumps memory when needed, looks for potential memory leaks  and gives a notification for a memory leak with a clean trace to find the root of the leak with sub-roots attached to it as shown in figure 2 :

Figure 2. Screenshot from Leaks application made by Leak Canary for PSLab app

It is clearly visible from the image that the applications show the root of the memory leak with an indication of how much memory is leaked in the toolbar.

Explanation of leak shown in figure 2 :

In the PSLab app, there is a navigation drawer consisting of all main functionalities in it. It is as shown in figure 3 :

Figure 3. Navigation drawer in PSLab

The memory leak as shown in figure 2 originated in the following steps :

  • It started with ArrayList which is here the list of items as shown in figure 3.
  • After it comes to the ScrollContainer which helps in scrolling this list on small screens.
  • Then comes the Drawer Layout which is the actual layout seen in figure 3 that slides over the main layout which is here the Instruments layout.
  • At last, comes the InputMethodManager which is introduced by Leak Canary library which watches the activity that is being opened.
  • Here, InputMethodManager kept watching on Drawer Layout but after closing the layout too it referenced it which is due to the source code of LeakCanary Library and so memory Leak occurred.

How to stop this leak from occurring ?

A simple way is to add a transparent activity as soon as the layout is closed for a very small time i.e. 500 ms so that the reference watcher gets shifted from the actual layout. This solution is based on the article published on Medium [5].

How to implement Leak Canary in your app?

Below is the step-by-step guide on implementing Leak Canary library in your app to implement a watcher for memory leaks :

    • Add dependencies (App Level) in your project to implement Leak Canary
debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
testImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
      1. debugImplementation – For debug flavor of app
      2. releaseImplementation – For release flavor of app
      3. testImplementation – For testing the current flavor of the app

Add dependencies according to the need for the application.

Add Realm dependencies (Project Level) in your app to create a database which can be used by Leak Canary to maintain and provide crash reports as shown in the figure above.

NOTE: Any database can be used here according to the need of the app

buildscript {
            repositories {
                     jcenter()
                         }
            dependencies {
                classpath "io.realm:realm-gradle-plugin:0.88.2"
           }
       }
 apply plugin: 'realm-android'

App-level dependency :

compile 'io.realm:android-adapters:2.0.0'
  • Add an activity class in your application to construct the Leak Canary for your entire application. In PSLab Android application, it was made as under :
package org.fossasia.pslab;

import android.app.Application;

import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;

import io.realm.Realm;

public class PSLabApplication extends Application {

	public RefWatcher refWatcher;

	@Override
	public void onCreate() {
    	super.onCreate();
    	Realm.init(this);

    	initializeLeakCanary();
	}

	private void initializeLeakCanary() {
    	if (LeakCanary.isInAnalyzerProcess(this)) {
        	return;
    	}
    	refWatcher = LeakCanary.install(this);
	}
}

Explanation of the above-implemented code :

  1. First import all the necessary libraries
  2. Realm.init(this) is used to initiate the database as soon as the layout of the Leak Canary is ready to work so that before any crashes, the database is ready to accept the entry
  3. initializeLeakCanary() method first checks if the analyzer is in the process i.e. if the Leak Canary is already initiated so that there’s no need to again initiate it else a reference watcher is initiated with variable refWatcher which looks out for any potential memory leaks

After this, you can provide a watcher with an object to watch by writing :

refWatcher.watch(object);

Now your app is ready to handle any case of memory leaks and thus the developer can find the root of the issue if any and can solve it with ease. The app will now work 94% more efficiently than what it used to be with memory leaks. Thus, a greater user experience can be provided now but in the backend!!

Resources

  1. How to use Leak Canary – Article on Stack Overflow
  2. Everything you need to know about memory leaks – Article on medium.com
  3. Leak Canary: Detect all memory leaks -Another great article on medium.com
  4. https://github.com/square/leakcanary – Actual GitHub repo of Leak Canary library
  5. https://medium.com/@amitshekhar/android-memory-leaks-inputmethodmanager-solved-a6f2fe1d1348 – Medium article on how to solve InputMethodManager related leaks

 

Continue ReadingImplementing Leak Canary in PSLab Android App

Implementing search bar in PSLab app

PSLab offers a large range of functions with a large field of applications. This results in the long access path to certain information and functionality in the app, which affects the user experience (UX) negatively. In this blog post, I will show how the UX in Android applications with many functions can be improved by implementing a ‘Search Bar’. Further, I have created a screencast that follows the step-by-step description shown in this blog post [1].

Search Bar is the functionality which can be seen nowadays in almost all the apps. It is a handy widget for users to navigate the app. PSLab’s Android app was lacking this functionality and so I added it using an external library from Mirrajabi called ‘search-dialog’ [3]. I decided to use this library as it provides a search bar with built-in functionality of highlighting the text that’s selected or written down in the ‘Edit Text’ field by the user and also it overlays on the screen which provides a good user experience rather than other search bars which overlap on the text provided on the screen with a ListView. Further working with this dependency was easier than working with others as it seems well designed.

The Search Bar was added in the Saved Experiments section which contains a lot of default experiments along with their respective manuals. The search bar was intended to provide the user with a greater UI so that they don’t need to navigate through sections every time to find an experiment.

This blog is a step by step guide on how to implement it in any app.

  1. First, add dependencies in the gradle at both project level and app level. By adding these dependencies, we don’t need to worry about writing code for how the Search Bar will filter searches and how it will be placed on the screen.

App Level :

'com.github.mirrajabi:search-dialog:1.1'

Project Level :

maven { url "https://jitpack.io" }
  1.  Create a SearchModel class which will help to carry out the search operations.
public class SearchModel implements Searchable {

	private String mTitle;

	public SearchModel(String mTitle) {
    	this.mTitle = mTitle;
	}

	public void setTitle(String mTitle) {
    	this.mTitle = mTitle;
	}

	@Override
	public String getTitle() {
    	return mTitle;
	}
}

The SearchModel class helps to communicate with the filtered search results by returning the string which is selected:

  • SearchModel(String string) – It is a default constructor
  • setTitle(String string) – It is a method used to set the string provided in the search results
  • getTitle() – It is also a method to get the string selected by the user from the filtered search result provided
  1.  Now provide some data which needs to be searched using an ArrayList or by using StringArrays and then converting it to Search Model Object.
private ArrayList<SampleSearchModel> createSampleData(){
        ArrayList<SampleSearchModel> items = new ArrayList<>();
        items.add(new SampleSearchModel("First item"));
        items.add(new SampleSearchModel("Second item"));
        items.add(new SampleSearchModel("Third item"));
        items.add(new SampleSearchModel("Fourth item"));

        return items;
    }
  1.  At last add the constructor in MainActivity to make the search bar.
SimpleSearchDialogCompat(Context context, String title, String searchHint, @Nullable Filter filter, ArrayList<T> items,
SearchResultListener<T> searchResultListener)

All the parameters can be given according to requirement. The function of each and every parameter are as under :

  • Context – Provide context of the current activity
  • String title – To provide title to Search Bar
  • String searchHint – To provide hint text to the user
  • Filter – To provide any additional filters to the search made by the user
  • ArrayList<T> – To provide data that can be searched
  • SearchResultListener<T> – The method which handles what to do when a user clicks on the filtered searches provided

Let’s try to search for the Piezo Buzzer and UltraSonic Range Finder Experiments in the Search Bar :

Figure 1. GIF of implemented Search Bar

So, in this way, I have implemented the Search Bar functionality in the PSLab application. One last note that try to practice this widget before implementing it in the main project as it requires some practice of filters as per requirements and also its location needs to be defined as per the requirement of an organization as it can be placed anywhere from the main screen to the toolbar to navigation drawer. Below are some of the useful resources to get best practice.

Resources

  1. https://youtu.be/QyqbRHt1NUE – How to make a search bar like above (By – Harsh Patel (me))
  2. https://github.com/mirrajabi/search-dialog – This is the GitHub Page of the library which I used in making an attractive screen overlaying search bar rather than the old one with the list view placed in the toolbar
Continue ReadingImplementing search bar in PSLab app