The Pocket Science Lab Android app has got various functionality such as voltmeter, resistance measurement, capacitance measurement, frequency measurement as well as Count pulse measurement , one of the missing functionality among these is the Ammeter, currently in PSLab there is no direct way of measuring current. In this blog I will be discussing an indirect method of measuring current in PSLab.
Basics of measuring current
Generally in all multimeters , current is measured using an Ammeter which uses the property of galvanometer to measure to measure current in PSLab. But as the PSLab doesn’t has any such embedded Galvanometer we cannot have a seperate Ammeter in it, but there is another method to measure the current, which is using the famous OHm’s law i.e V/I = R
In PSLab we can measure the voltage across any elements, plus we can also measure the resistance of any circuit element in PSLab, the theory used for measuring current is stated as follows.
We connect the current-source to any known resistant(or any resistance) and then measure the voltage across the resistor.
Finally using ohm’s law the current will be voltage / resistance.[2]
Step-by-step guide on measuring the current
Here is the step by step guide on how to measure the current in PSLab:-
Take any arbitrary resistor and measure it’s resistance. To measure the resistance follow these steps :-
Take a resistance and connect it to any two pins of breadboard
Connect one end to the sen pin and the other end to the GND pin of PSLab device.
Now go to the Android app and select multimeter instrument.
Now in the multimeter instrument set the knob to resistance, in the measure section
Now click on the read button and then it will show the resistance of the resistor
Now that you have measured the resistance of the resistor, now connect the current source across the resistors.
Now finally measure the voltage across the resistor. To measure the voltage follow these steps.
Take two male to male wires and connect it’s two individual ends to the two ends of the resistor.
Now connect one of the other two ends of the wire to the any one of the CH1, CH2 or CH3 and the other end to GND respectively.
Now go to the Android app and select multimeter instrument.
Now in the multimeter instrument set the knob to the channel which you have selected i.e CH1, CH2 or CH3 , in the voltage section.
Now click on the read button and then it will show the voltage across the resistor.
Now using the using ohm’s law the current will be voltage / resistance.
Thus using these steps one can find the current in PSLab Android App.
The Pocket Science Lab Android app has various functionalities implemented in it, one of the major implemented functionalities is the knob in the multimeter, In my previous blog I have mentioned about the knobs and how exactly it has been implemented, one the major problems in the knob is that it doesn’t fits correctly in all layouts, even though constraint layout is used , as it has different text-views positioned in a circular constraint in which exact circular radius has to be mentioned (which cannot be constrained), mentioned in my previous-blog there comes the idea of creating different layouts for different-screens in android.
Need to create multiple layouts for different screen
There arises this question of the use of creating multiple layouts for different screens when you can create a flexible layout using tools such as constraint layout. The answer to this question is that in some cases such as as the case of circular constraint or using a linear-layout one has to use use hard-coded dimensions which thus makes difference in various screens on, there comes the need of using size and orientation quantifiers i.e making layout according to screen sizes. Als
Figure 1:Screenshot
Figure 1 shows how different layouts are made for multimeter according to the screen-size.
Size quantifiers in android
Size quantifier is a name that specifies an individual configuration (in this case size) corresponding to which resources can be used.
For example, here are some default and alternative resources:
In this case -hdpi is a size quantifier, there are default size quantifiers at the drawable folder.
Making different layouts according to size-quantifiers[1][2]
This blog will give a step by step guide on how to make layouts using size quantifiers.
Right click the res folder in android studio and select New-> Android Resource directory.
A screen like below will appear
Change the resource type to layout.
From the available quantifiers select the quantifier which you would require, (in our case it is size).
After selecting the quantifier click the >> button after which the following screen will get displayed.
Now select the screen-size and click ok to make the directory, note that only one directory can be made in a single go.
After this make different layouts according to the screen-sizes and then save the respective alternative resources in this new directory. The resource files must be named exactly the same as the default resource files.
Thus by following these steps one can make different layouts according to screen-sizes in android.
In my previous blog [2I have discussed about how to implement normal rotary knob using an open source library, this blog will be about the new user interface (UI) of multimeter in the PSLab Android app, how a custom rotary knob is implemented in it and how how the text views are positioned circular in them.
Implementation of Custom Rotary Knob
In the PSLab device the rotary knob is implemented using the BeppiMenozzi Knob library[1] as by doing this we don’t have to manually create the extra class for the knob and we don’t have to write the code from scratch.
Figure 1: A basic rotary knob
Figure 1 shows a basic knob implemented using the BeppiMenozzi library whereas figure 2 shows the implementation of a custom knob using the basic knob.
Figure 2: A custom Knob
Steps of making a Custom-Knob using a simple Knob
Implement the the basic knob using the steps given in my previous knobs explained in my previous blogs.
Download the images of the knob which has to be implemented.
Using the above code amend the knob as per the requirement. The advantage of using the beppiMonzi library is that the knob is fully amenable , we can even define the minimum and maximum angle and many more stuffs can be done using the library.
Figure 3: Showing the implementation of other custom knobs
The above figure shows the example of custom knobs implemented using the simple knob and by following the steps.
Implementation Circular positioning
One of the other major issues while making the new UI of the multimeter is the positioning of text-view around the circular knob. The issue was made overcome by implementing a circular positioning constraints in the text-views.
Steps of implementing circular positioning
Use the constraint layout version 1.1.0 or above as the previous versions do not support the circular positioning feature.
Add the circular constraint individually to every text-view.
The above code snippets shows the addition od circular constraints added to a text-view. Using these constraint it decides positions the views relative to another views at a particular angle which thus makes up circular positioning.
Thus, this is how we can implement circular positioning in the views.
In this blog I will discuss about how we have measured capacitance in Pocket Science Lab and the issues in capacitance measurement which was finally solved.
Measuring capacitance in PSLab device
To measure capacitance we need to go to the multimeter instrument from the instrument section of the PSLab
Figure 1. Showing Multimeter Tile
Capacitance in PSLab is measured by keeping the capacitor or the element of which capacitance is to be measured between the CAP and ground pin.
Figure 2. Showing CAP pins in PSLab
For measuring capacitance in PSLab we use a specific method in which we supply a constant current to the CAP pin and thus we charge the capacitor to the maximum level, the math involved in it is as follow:-
We know that
Q{charge stored} = C*V
Also
Q= I * time
Where
I=current (constant)
Thus the capacitance
C = Q / V
Therefore
C = I*time / V (measured). – (1)
Therefore we know the current supplied, we know the voltage measured and we have also set the time to charge the capacitor and thus we get the capacitance from equation (1).
Code implementation for measuring capacitance
This is the primary code for getting the data for measuring capacitance in which we pass the current range and the current time through which the data gets fetched from the device which is then further processed in another function in which we finally get the capacitance.
publicdouble[] getCapacitance(int currentRange, int chargeTime) { // time in uSectry {
mPacketHandler.sendByte(mCommandsProto.COMMON);
mPacketHandler.sendByte(mCommandsProto.GET_CAPACITANCE);
mPacketHandler.sendByte(currentRange);
mPacketHandler.sendInt(chargeTime);
Thread.sleep((long)(chargeTime * 1e-6 + .02));
int VCode;
do VCode = mPacketHandler.getVoltageSummation();
while (VCode == -1);
double v = 3.3 * VCode / 4095;
mPacketHandler.getAcknowledgement();
double chargeCurrent = this.currents[currentRange];
double c = 0;
if (v != 0)
c = (chargeCurrent * chargeTime * 1e-6 / v - this.SOCKET_CAPACITANCE) / this.currentScalars[currentRange];
returnnewdouble[] {
v,
c
};
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
returnnull;
In the above function we can clearly see how we send the bytes in the device by the sendByte function through which various functions are sending current, setting voltage, setting current range etc are done in the device and then we can see how the voltage measured is taken using the getVoltageSummition method (of packet Handler class) , how we get the current and finally using them in equation (1) we get the capacitance of the element.
The following implementation is taken from the PSLab desktop app where the same method is used to measure capacitance.
Bugs in measuring capacitance
The capacitance measurement although was working in the desktop app but had bugs in the android app. It could never read the correct value also everytime gave a null value for capacitance.
Figure 3. Showing null value for capacitance PSLab
Solving the Bug [2]
After a deep research in the inside the code of the capacitance measurement it was found that the error was caused while fetching the incorrect data from the device and processing it. The device gives a negative one value when there is any error in capacitance measurement and that was being processed, thus the error was solved by introducing a do while loop as shown
doVCode = mPacketHandler.getVoltageSummation();
while (VCode == -1);
And thus now only the correct data fetched is processed further and thus the bug was solved after which the capacitance measurement was correct.
The Pocket Science Lab multimeter has got three channels namely CH1,CH2 and CH3 with different ranges for measuring the voltages, but there was a channel communication error occuring at CH1 and CH2 pins of PSLab. This blogs will give a brief description of the channel communication error and how was it solved by me.
In the previous blog I have discussed about the channel communication of PSLab and how it works. In this blog i will be discussing about the channel communication error which was occuring while using CH1 and CH2 pins of PSLab android.
Communication between PSLab device and Android App
As discussed in the previous blog the communication between the PSLab and the android occurs with the help of the USBManger class of android.
One of the major function which makes it possible is the bulk transfer function of the android
As shown in the above code, there is a timeout that some time required for this function to be executed, and otherwise this function will return a negative value which will mean that the communication is not successful.
Voltage Measuring Functions
The main function which gets called while pressing the button for measuring voltage is the getVoltage function which simultaneously calls the volmeterAutoRange function as well as the getAverage voltage function. The voltageAutoRnge function also calls the getAverage function inside of it.
public double getVoltage(String channelName, Integer sample) {
this.voltmeterAutoRange(channelName);
double Voltage = this.getAverageVoltage(channelName, sample);
if (channelName.equals("CH3")) {
return Voltage;
} else {
return2 * Voltage;
}
}
Calling both these functions simultaneously results in calling of the bulktranfer method
The getAverage voltage function calls the getRawableVoltage function which thus calls the USBManger class functions of read and write, thus calling the bulkTranfer function.
Thus as the bulk transfer function is called simultaneously it caused problem in communication.
Solving the issue
The communication related issues were finally solved when these bugs were spotted, the solution to this issue is that the voltageAutoRange function’s return value was never used in the codes and was thus not required.[2]The voltageAutoRange function was calling the getAverageVoltage function just to get a return value. Thus I formatted the function and now it looks like this-
This blog demonstrates how to work with Shared Preferences in an Android app. The blog includes a detailed explanation about what are the methods available to store data in Android and where to use Shared Preferences (a type of data storage method) to save extra memory usage and work efficiently. After the detailed explanation is a step by step guide on how to use Shared Preferences in any Android app by taking an example of one used in PSLab Android app under PR #1236
What are methods available in Android for data storage ?
Android provides a variety of methods to store data some of which are
Shared Preferences
Internal Storage
External Storage
SQLite Database
A very brief description of the above four data storage method would be
Shared Preference – Used to store key-data pair for a given app
Internal Storage – Used to store any type of data such as pictures, videos, etc. which can be used only within the app
External Storage – Used to store any type of data such as audio, video, etc. which can be shared between different apps or different systems
SQLite database – It is also a type of Internal Storage method but with a different programming language in use which is SQL
Where to use different data storage methods?
Following are some of the distinct cases where the above-mentioned data storing methods can be differentiated
Shared Preference – Shared Preference should be used when a very small amount of data i.e. key-value pair data is to be stored. An example of it would be storing the state of a widget when an app is closed and restoring the state when the app is opened again.
Internal Storage – Internal storage should be used while storing data such as text files, audio, video, photographs, etc. but occupying a very less device memory space. So, internal storage should be used when a limited amount of data needs to be stored for app execution.
External Storage – External storage should be used when data to be stored is very large and as a result, Internal storage can’t be used. External Storage can also write data on external memories like SD Card, etc.
How to use Shared Preferences in an Android app?
Following is a step by step guide on how Shared Preferences were used in PSLab Android app
First, declare a variable using final and static keyword so as to make its value permanent because it will be used to differentiate current activity/fragment data from other activity/fragment data in a common folder of Shared Preference.
Now, we can make Shared Preferences for current activity/fragment by using the code:
When in Activity:
final SharedPreferences settings = getSharedPreferences(FRAG_CONFIG, Context.MODE_PRIVATE);
When in fragment:
final SharedPreferences settings = getActivity().getSharedPreferences(FRAG_CONFIG, Context.MODE_PRIVATE);
Here Context.MODE_PRIVATE is a context through which we define our Shared Preference i.e. for the current context it means that the above made Shared Preference can only be used inside the current activity/fragment. A detailed description of other modes available can be found in [1].
Now, Shared Preference for current activity/fragment is ready for use and so now, we can add as many numbers of the key-value pair as we want by using the following code
settings.getInt("HighValue", 2000);
Here, “HighValue” is the key whereas 2000 is the value. The above method is used to give a default value when a pair is created.
Now to edit the value of any before-made pair, we can use the Editor method available in the Shared Preference class to edit the default value.
Here, the editor is an instance of edit() method available in Shared Preference class. After changing the default value of the key, we can use apply() method to apply the changes to the default key-value pair.
Where to find the Shared Preference folder on the target device?
To find the Shared Preference folder for any Android application, do the following steps:
Connect the target device (device on which app is installed) to the system running Android Studio.
Now click on the “Device File Explorer” button in Android Studio as shown in figure 1.
Figure 1. Device File Explorer button in Android Studio
Now after clicking the button, a list of folders would pop up as shown in figure 2.
Figure 2. Screenshot of Android Studio showing list of folders on the device
Now follow the given path, and you can see the desired folder
This blog is a step by step guide on how to make a functional progress bar in an Android app by taking an example of the progress bar implemented in PSLab Android application. The example is based on my work done in PSLab Android repository under PR #1077 and so it will only demonstrate making a simple progress bar (both linear and circular) and not the one showing progress in percentage too.
How progress bar was implemented in the PSLab app?
Both horizontal and circular progress bar is available in the Material Design Library provided by Google in Android Studio. So, no extra dependencies are needed.
Just drag and drop the progress bar of whichever shape necessary i.e. circular or horizontal, directly on the screen available in the Design tab as shown in Figure 1.
Figure 1. Design tab in Android Studio
There are two ways to use the progress bar available in the Material Design Library.
To show a loading screen
To show the progress of a process
Loading Screen
Loading Screens are used when the time that will be taken by the process is not known. So, an indeterminate circular progress bar is used to show that some process is going on and so the user needs to wait.
Layout
A circular progress bar is used for this process and so drag and drop the circular progress bar as shown in figure 1. Now set the position, height, and width of the progress bar in the layout as necessary. To set the color of the progress bar, use attribute android:indeterminateTint
Backend
To implement this type of functionality, use the setVisibility function to show the progress bar while some process is taking place in the backend and immediately remove it as soon as the result is ready to be displayed. To make the progress bar visible use progressBar.setVisibility(View.VISIBLE) and to make it invisible use progressBar.setVisibility(View.GONE)
Showing Progress
This is a very common type of process and is used by most of the apps. A horizontal progress bar is used to show the actual progress of the process taking place in the backend on a scale of 0-100 (the scale may vary) where 0 means the process hasn’t started and 100 means the result is now ready to be displayed.
Layout
Horizontal Progress bars are used for this type of usage. So, drag and drop the horizontal progress bar as shown in figure 1. Now set the position, height, and width of the progress bar in the layout as necessary. Different styles of the progress bar can be found in the documentation [1].
Backend
Initially, set the progress of the bar to 0 as no process is taking place by using method setProgress(). Now as soon as the process starts, to increase the progress by a fixed value, use progressBar.incrementProgressBy() method and to set the progress directly, use progressBar.setProgress() method.
So in this way, a progress bar can be implemented in an Android application. Other features like adding custom designs and animations can be done by making the necessary shapes and animations respectively and using the functions available in the documentation [1].
This blog covers the topic of how to create custom dialog boxes in an Android app by taking an example of how it was implemented in PSLab Android application. The custom dialog box that will be illustrated in this blog will have a layout similar to that from my PR feat: added a guide for Logic Analyzer Instrument using Alert Dialog Box in PSLab Android repository. But all the main functionalities that can be added to a custom dialog will be illustrated in this blog.
How custom dialog was implemented in the PSLab app?
The first step is to make a layout for the custom dialog box. The layout of custom dialog should be such that it shouldn’t occupy thewhole screen as the idea here is to overlay the dialog over the activity and not replace the whole activity with the dialog layout. The layout can be implemented by using the following attributes :
The result of the above layout after adding proper margins and padding is as shown in figure 1.
Figure 1. The output of the layout made for custom dialog
Now as the layout is ready, we can focus on adding Java code to inflate the layout over a particular activity. Make a function in the activity or the fragment in which the custom dialog is to be inflated. Add the following code (if the layout is same as that in PSLab app else modify the code as per the layout) in the function to display the custom dialog box.
publicvoidhowToConnectDialog(String title, String intro, int iconID, String desc){
try {
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog_box, null);
// Find and set all the attributes used in the layout and then create the dialog as shown
builder.setView(dialogView);
builder.setTitle(title);
final AlertDialog dialog = builder.create();
ok_button.setOnClickListener(new View.OnClickListener() {
@OverridepublicvoidonClick(View v){
dialog.dismiss();
}
});
dialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
Here, the LayoutInflater inflates the custom dialog layout in the Alertdialog builder. The Alertdialog builder is used to hold and set values for all the views present in the inflated layout. The builder then creates a final custom dialog when builder.create() method is called. Finally, the dialog is shown by calling method dialog.show() and is dismissed by calling method dialog.dismiss().
Now the dialog box is ready and it will be inflated when the above method is called. But the “Don’t show again” checkbox currently has no functionality and so the dialog box will pop up although “Don’t show again” checkbox is ticked mark by the user. For adding this functionality, we will need to use Shared Preferences to save the state of the dialog box. For using Shared Preferences, first, add the following lines of code in the above method
final SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);Boolean skipMessage = settings.getBoolean("skipMessage", false);
The PREFS_NAME is the key to distinctly identify the state of the given dialog box from the stored state of many dialog boxes (if any). A suggested key name is “customDialogPreference”. The skipMessage is a boolean used here to check the state if the dialog box should be inflated or not.
Now format the onClickListener of the OK button with the following code :
The following code checks the state of “Don’t show again” dialog and then inflates the custom dialog if applicable. If the checkbox is ticked mark then on pressing the OK button the dialog won’t be inflated again.
In this blog, we will use the data stored in the Realm to display a list of recorded experiments in the form of well defining card view items so that it is easier for the user to understand.
For showing the list we will make use of RecyclerView widget provided by Android which is a more advanced version of the List view and is used to display large data sets in a vertical list, horizontal list, grid, staggered grid etc.
RecyclerView works in accordance with RecyclerView Adapter which is core engine that is responsible of inflating the layout of list items, populating the items with data, recycling of list item views when they go out of viewing screen and much more.
For this blog, we are going to use a special RecyclerView Adapter provided by Realm itself because it integrates properly with the Realm Database and handles modifying, addition, deletion or updating of Realm data automatically and efficiently.
Step 1 Adding the dependencies
As always first we need to add the following code in our build.gradle file to add the dependency of Realm database and RealmRecyclerViewAdapter.
Step 2 Adding RecyclerView widget in our Activity layout file
First, we need to create an activity and name it as “DataLoggerActivity”, inside the layout of the Activity add the <RecyclerView> widget. This RecyclerView will act as a container of our list item.
Step 3 Creating the layout and View holder for the list item
We have to create the layout of the list item which will be inflated by the Adapter. So for this create an XML file in res folder and name it “data_list_item.xml”. For the list of the experiments, we want to show Name of the experiment, recording time, recording date for every list item. For this we will make use of <CardView> and <TextView>. This gist shows the code of xml file.
The layout of the list item created is shown in Figure 2
Now we need to create a view holder for this layout which we need to pass to the Adapter, the following code shows the implementation of View Holder for above list item layout.
In this step, we will start by creating a class called “SensorLoggedListAdpater” and for using use the RecyclerView adapter provided by Realm we need to make this class extend the RealmRecyclerViewAdpater class.
But for that we need to pass two generic parameter:
Model Class : This is class which define a Realm model, for this, we will pass a reference of “SensorLogged.class” which is defined in the previous blog as we want to show the list experiments which are stored using “SensorLogged” model class.
ViewHolder : For this, we will pass the ViewHolder that we have created in Step 3.
As every RecyclerView Adapter needs a arraylist which contains the list of object containing information which we have to populate on the list item, the RealmRecyclerViewAdpater needs data in form of RealmResult to operate on, so we will create a constructor and pass in the RealmResult list in the super() method which we need to provide when we initialize this adapter in our “DataLoggerActivity” class.
Now we need to override two methods provided by RealmRecyclerViewAdapter class that are:
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType): In which we will inflate the layout of list item “dta_list_tem.xml” which we have created in Step 3.
public void onBindViewHolder(@NonNull final ViewHolder holder, int position): In which we will populate the list item view using references stored in the ViewHolder with the data which we have provided while initializing the adapter.
@NonNull@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.logger_data_item, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
SensorLogged temp = getItem(position);
holder.sensor.setText(temp.getSensor());
Date date = new Date(temp.getDateTimeStart());
holder.dateTime.setText(String.valueOf(sdf.format(date)));
}
Step 5 Initializing the Adapter in Data Logger Activity and connecting with RecyclerView
Now we head to our Data Logger Activity, here in OnCreate() method first we will create a object of RecyclerView, then we will initialize our adapter by passing the RealmResult<SensorLogged> list which we have queried from the Realm Database.
Then we will set the LinearLayoutManager and finally, we will connect the the Adapter with the RecyclerView.
PSLab android app provides various new features like accessing data from the sensors that are either inbuilt into the Android phone or common I2C sensors which are connected to the PSLab device through PIC microcontroller. But the problem is that if the user records the data one time he/she may not be able to view that data in the future as there was no way to save that data somewhere. Saved data can be used for school experiments, preparing reports, research purposes etc.
So, now we have integrated Realm database with the Sensor Data Logger module which is a mobile database that can be used to store real-time data in fast and flawless manner. It is a object oriented database so it stores data in the form of objects which makes it usage with object oriented programming language like Java much easier.
In this blog we will demonstrate the process of storing data from one instrument i.e., Lux Meter which records illuminance with respect to time to understand the process.
First, we have defined a model class “SensorLogged” which contains information pertaining to all one experiment performed by the user. It will have fields like time of start of recording, the time of the end of the recording, date of recording, sensor name etc.
Whenever a user performs an experiment we will store a object of the SensorLogged model class in realm database containing info for that experiment.
We will use the object of this class for every reading of one measurement and provide them with the same Foreign Key which will be Primary key uniqueRef of “SensorLogged” model class.
In this way, we can query all the reading belonging to one measurement from the database containing all the LuxData entries.
For storing the data in Realm database we will follow these steps:
Begin the Realm transaction.
realm.beginTransaction();
Create a object of “SensorLogged” model class for every measurement with the unique Ref as the primary key and store the information like time of start, date of start, sensor name etc. copy it to the Realm Database.
For every sensor, reading create a object of LuxData and store the reading in it with the time elapsed and set all the object to same Foreign Key which is same as the Primary key stored in “SensorLogged.class” for this experiment in the previous step and copy it to Realm Database.
for (int i = 0; i < luxRealmData.size(); i++) {
LuxData tempObject = luxRealmData.get(i);
tempObject.setForeignKey(uniqueRef);
realm.copyToRealm(tempObject);
}
Commit the transaction
realm.commitTransaction();
Therefore now the data fetched for each sensor for every experiment is now being saved to the Realm database which we can easily query by using the following code.
Below code will query all the SensorLogged object in the form of RealmResult<SensorLogged> list which we can use to show to the user the list of all experiments.
And the code below will query all the LuxData object that contains reading belonging to one experiment whose uniqueRef has been provided as the ForeignKey.