How to Collaborate Design on Hardware Schematics in PSLab Project

Generally ECAD tools are not built to support collaborative features such as git in software programming. PSLab hardware is developed using an open source ECAD tool called KiCAD. It is a practice in the electronic industry to use hierarchical blocks to support collaboration. One person can work on a specific block having rest of the design untouched. This will support a workaround to have a team working on a one hardware design just like a software design. In PSLab hardware repository, many developers can work simultaneously using this technique without having any conflicts in project files. Printed Circuit Board (PCB) designing is an art. The way the components are placed and how they are interconnected through different type of wires and pads, it is an art for hardware designing engineers. If they do not use auto-route, PCB design for the same schematic will be quite different from one another. There are two major approaches in designing PCBs. Top Down method Bottom Up method Any of these methods can be implemented in PSLab hardware repository to support collaboration by multiple developers at the same time. Top Down Method In this method the design is starting from the most abstract definitions. We can think of this as a black box with several wires coming out of it. The user is aware of how to use the wires and to which devices they need to be connected. But the inside of the black box is not visible. Then a designer can open up this box and break the design down to several small black boxes which can perform a subset of functionalities the bigger black box did. He can go on breaking it down to even smaller boxes and reach the very bottom where basic components are found such as transistors, resistors, diodes etc. Bottom Up Method In the bottom up method, the opposite approach of the top down method is used. Small parts are combined together to design a much bigger part and they are combined together to build up an even bigger part which will eventually create the final design. Our human body is a great example for a use of bottom up method. Cells create organ; organs create systems and systems create the body. Designing Top Down Designs using KiCAD In PCB designing, the designers are free to choose whatever the approach they prefer more suitable for their project. In this blog, the Top Down method is used to demonstrate how to create a design from the abstract concepts. This will illustrate how to create a design with one layer deep in design using hierarchical blocks. However, these design procedures can be carried out as many times as the designer want to create depending on the complexity of the project. Step 01 - Create a new project in KiCAD Step 02 - Open up Eeschema to begin the design Step 03 - Create a Hierarchical Sheet Step 04 - Place the hierarchical sheet on the design sheet and give it…

Continue ReadingHow to Collaborate Design on Hardware Schematics in PSLab Project

Generate Sine Waves with PSLab Device

Sine wave is type of a waveform with much of a use in frequency related studies in laboratories as well as power electronics to control the level of input to devices. PSLab device  is capable of generating sine waves with a very high accuracy using PSLab-firmware and a set of filters implemented in the PSLab-hardware. How Sine Wave is generated in PSLab Device PSLab device uses a PIC micro-controller as its main processor. It has several pins which can generate square pulses at different duty cycles. These are known as PWM pins. PWM waves are a type of a waveform with the shape resembling a set of square pulses. They have an attributed called ‘Duty Cycle’ which varies between 0% to 100%. A PWM wave with 0% duty cycle means simply a zero amplitude block of square pulses repeating at every period. When duty cycle is set to 100%, it is a set of square pulses with the highest amplitude throughout the period repeating in every period. The following figure illustrates how the PWM wave changes according to its duty cycle. Image is extracted from http://static.righto.com/images/pwm1.gif PSLab device is capable of generating this type of pulses with arbitrary duty cycles as per user requirements. In this context where sine waves are generated, these PWM pins are used to generate a Sinusoidal Pulse Width Modulated (SPWM) waveform as the first step to output a sine wave with high frequency accuracy. The name SPWM is derived from the fact that the duty cycle of the waveform follows an alternatively increasing and decreasing pattern as illustrated in the figure below. Deriving a set of duty cycles which follows a sinusoidal pattern is a redundant task. Without deriving them mathematically, PSLab firmware has four hard-coded sine_tables which stores different duty cycle values related to a SPWM waveform. These sine_tables in the firmware related to different resolutions set by the PSLab device user. The following code block is extracted from PSLab firmware related to one of the sine_tables. It is used to generate the SPWM wave with 512 data points. Each data point represents a square pulse with a different pulse width. The duty ratio is calculated from dividing an entry by the value 512 and converting it to a percentage. sineTable1[] = {256, 252, 249, 246, 243, 240, 237, 234, 230, 227, 224, 221, 218, 215, 212, 209, 206, 203, 200, 196, 193, 190, 187, 184, 181, 178, 175, 172, 169, 166, 164, 161, 158, 155, 152, 149, 146, 143, 141, 138, 135, 132, 130, 127, 124, 121, 119, 116, 114, 111, 108, 106, 103, 101, 98, 96, 93, 91, 89, 86, 84, 82, 79, 77, 75, 73, 70, 68, 66, 64, 62, 60, 58, 56, 54, 52, 50, 48, 47, 45, 43, 41, 40, 38, 36, 35, 33, 32, 30, 29, 27, 26, 25, 23, 22, 21, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 2, 2, 2, 1, 1,…

Continue ReadingGenerate Sine Waves with PSLab Device

Curve-Fitting in the PSLab Android App

One of the key features of PSLab is the Oscilloscope. An oscilloscope allows observation of temporal variations in electrical signals. Its main purpose is to record the input voltage level at highly precise intervals and display the acquired data as a plot. This conveys information about the signal such as the amplitude of fluctuations, periodicity, and the level of noise in the signal. The Oscilloscope helps us to observe varying the waveform of electronic signals, it is obvious it measures a series of data points that need to be plotted on the graph of the instantaneous signal voltage as a function of time. When periodic signals such as sine waves or square waves are read by the Oscilloscope, curve fitting functions are used to construct a curve that has the best fit to a series of data points. Curve fitting is also used on data points generated by sensors, for example, a damped sine fit is used to study the damping of the simple pendulums. The curve fitting functions are already written in Python using libraries like numpy and scipy. analyticsClass.py provides almost all the curve fitting functions used in PSLab. For the Android, implementation we need to provide the same functionality in Java. More about Curve-fitting Technically speaking, Curve-fitting is the process of constructing a curve or mathematical function, that has the best fit to a series of data points, possibly subject to constraints. Let’s understand it with an example. Exponential Fit The dots in the above image represent data points and the line represents the best curve fit. In the image, data points are been plotted on the graph. An exponential fit to the given series of data can be used as an aid for data visualization. There can be many types of curve fits like sine fit, polynomial fit, exponential fit, damped sine fit, square fit etc. Steps to convert the Python code into Java code. 1. Decoding the code At first, we need to identify and understand the relevant code that exists in the PSLab Python project. The following is the Python code for exponential fit. import numpy as np def func(self, x, a, b, c): return a * np.exp(-x/ b) + c This is the model function. It takes the independent variable ie. x as the first argument and the parameters to fit as separate remaining arguments. def fit_exp(self, t, v): from scipy.optimize import curve_fit size = len(t) v80 = v[0] * 0.8 for k in range(size - 1): if v[k] < v80: rc = t[k] / .223 break pg = [v[0], rc, 0] Here, we are calculating the initial guess for the parameters. po, err = curve_fit(self.func, t, v, pg) curve_fit function is called here where model function func, voltage array v, time array t and a list of initial guess parameters pg are the parameters. if abs(err[0][0]) > 0.1: return None, None vf = po[0] * np.exp(-t/po[1]) + po[2] return po, vf 2. Curve-fitting in Java The next step is to implement the functionalities in Java. The…

Continue ReadingCurve-Fitting in the PSLab Android App

Designing Control UI of PSLab Android using Moqups

Mockups are an essential part of app development cycle. With numerous mock-up tools available for android apps (both offline and online), choosing the right mock-up tool becomes quite essential. The developers need a tool that supports the latest features like drag & drop elements, support collaboration upto some extent and allow easy sharing of mockups. So, Moqups was chosen as the mockups tool for the PSLab Android team. Like other mock-up tools available in the market, using moqups is quite simple and it’s neat & simple user interface makes the job easier. This blog discusses some of the important aspects that need to be taken care of while designing mockups. A typical online mock-up tool would look like this having a palette to drag & drop UI elements like Buttons, Text boxes, Check boxes etc. Additionally a palette to modify the features of each element ( here on the right ) and other options at the top related to prototyping, previewing etc. The foremost challenge while designing any mock-up is to keep the design neat and simple such that even a layman doesn’t face problems while using it. A simple UI is always appealing and the current trend of UIs is creating flat & crisp UIs. For example, the above mock-up design has numerous advantages for both a user and also as a programmer. There are seek bars as well as text boxes to input the values along with the feature of displaying the value that actually gets implemented and it’s much simpler to use. From the developer’s perspective, presence of seven identical views allows code reuse. A simple layout can be designed for one functionality and since all of them are identical, the layout can be reused in a Recyclerview. The above design is a portion of the Control UI which displays the functionalities for  using PSLab as a function generator and as a voltage/current source. The other section of the UI is of the Read portion. This has the functionalities to measure various parameters like voltage, resistance, capacitance, frequency and counting pulses. Here, drop-down boxes have been provided at places where channel selection is required. Since voltages are most commonly measured values in any experiment, voltages of all the channels have been displayed simultaneously. Attempts should always be made to keep the smaller views as identical as possible since it becomes easier for the developer to implement it and also for the user to understand.   The Control UI has an Advanced Section which has features like Waveform Generators allows to generate sine/square waves of a given frequency & phase, Configuring Pulse Width Modulation (PWM)  and selecting the Digital output channel. Since, the use of such features are limited to higher level experiments, they have been separately placed in the Advanced section. Even here drop-down boxes, text boxes & check boxes have been used to make UI look interactive. The common dilemma faced while writing the XML file is regarding the view type to be chosen as Android provides…

Continue ReadingDesigning Control UI of PSLab Android using Moqups

Using ButterKnife in PSLab Android App

ButterKnife is an Android Library which is used for View injection and binding. Unlike Dagger, ButterKnife is limited to views whereas Dagger has a much broader utility and can be used for injection of anything like views, fragments etc. Being limited to views makes it much more simpler to use compared to dagger. The need for using ButterKnife in our project PSLab Android was felt due to the fact binding views would be much more simpler in case of layouts like that of Oscilloscope Menu which has multiple views in the form of Textboxes, Checkboxes, Seekbars, Popups etc. Also, ButterKnife makes it possible to access the views outside the file in which they were declared. In this blog, the use of ButterKnife is limited to activities and fragments. ButterKnife can used anywhere we would have otherwise used findViewById(). It helps in preventing code repetition while instantiating views in the layout. The ButterKnife blog has neatly listed all the possible uses of the library. The added advantage of using Butterknife are- The hassle of using Boilerplate code is not needed and the code volume is reduced significantly in some cases. Setting up ButterKnife is quite easy as all it takes is adding one dependency to your gradle file. It also has other features like Resource Binding (i.e binding String, Color, Drawable etc.). Other uses like simplification of code while using buttons. For example, there is no need of using findViewById and setOnClickListener, simple annotation of the button ID with @OnClick does the task. Using butterknife was essential for PSLab Android since for the views shown below which has too many elements, writing boilerplate code can be a very tedious task. Using ButterKnife in activities The PSLab App defines several activities like MainActivity, SplashActivity, ControlActivity etc. each of which consists of views that can be injected with ButterKnife. After setting up ButterKnife by adding dependencies in gradle files, import these modules in every activity. import butterknife.BindView; import butterknife.ButterKnife; Traditionally, views in Android are defined as follows using the ID defined in a layout file. For this findViewById is used to retrieve the widgets. private NavigationView navigationView; private DrawerLayout drawer; private Toolbar toolbar; navigationView = (NavigationView) findViewById(org.fossasia.pslab.R.id.nav_view); drawer = (DrawerLayout) findViewById(org.fossasia.pslab.R.id.drawer_layout); toolbar = (Toolbar) findViewById(org.fossasia.pslab.R.id.toolbar); However, with the use of Butterknife, fields are annotated with @BindView and a View ID for finding and casting the view automatically in the layout files. After the annotation, finding and casting of views ButterKnife.bind(this) is called to bind the views in the corresponding activity. @BindView(R.id.nav_view) NavigationView navigationView; @BindView(R.id.drawer_layout) DrawerLayout drawer; @BindView(R.id.toolbar) Toolbar toolbar; setContentView(R.layout.activity_main); ButterKnife.bind(this); Using ButterKnife in fragments The PSLab Android App implements ApplicationFragment, DesignExperimentsFragment, HomeFragment etc., so ButterKnife for fragments is also used. Using ButterKnife is fragments is slightly different from using it in activities as the binded views need to be destroyed on leaving the fragment as the fragments have different life cycle( Read about it here). For this an Unbinder needs to be defined to unbind the views before they are destroyed. Quoting…

Continue ReadingUsing ButterKnife in PSLab Android App

Prototyping PSLab Android App using Invision

Often, while designing apps, we need planning and proper designing before actually building the apps. This is where mock-up tools and prototyping is useful. While designing user interfaces, the first step is usually creating mockups. Mockups give quite a good idea about the appearance of various layouts of the app. However, mockups are just still images and they don’t give a clue about the user experience of the app. This is where prototyping tools are useful. Prototyping helps to get an idea about the user experience without actually building the app. Invision is an online prototyping service which was used for initial testing of the PSLab Android app. Some of pictures below are the screenshots of our prototype taken in Invision. Since, it supports collaboration among developers, it proves to be a very useful tool.  Using Invision is quite simple. Visit the Invision website and sign up for an account.Before using invision for prototyping, the mockups of the UI layouts must be ready since Invision is simply meant for prototyping and not creating mockups. There are a lot of mock-up tools available online which are quite easy to use. Create a new project on Invision. Select the project type - Prototype in this case followed by selecting the platform of the project i.e. Android, iOS etc. Collaborators can be added to a project for working together. After project creation and adding collaborators is done with, the mock-up screens can be uploaded to the project directory Select any mock-up screen, the window below appears, there are a few modes available in the bottom navbar - Preview mode, Build mode, Comment mode, Inspect Mode and History Mode. Preview Mode - View your screen and test the particular screen prototype. Build Mode - Assign functionality to buttons, navbars, seek bars, check boxes etc. and other features like transitions. Comment Mode - Leave comments/suggestions regarding performance/improvement for other collaborators to read. Inspect mode - Check for any unforeseen errors while building. History Mode - Check the history of changes on the screen. Switch to the build mode, it would now prompt to click & drag to create boxes around buttons, check boxes, seek bars etc,(shown above). Once a box ( called as “hotspot” in Invision ), a dialog box pops up asking to assign functionalities. The hotspot/box which was selected must link to another menu/layout or result in some action like app closing. This functionality is provided by the “Link To:” option. Then the desired gesture for activating the hotspot is selected which can be tap for buttons & check boxes, slide for navbars & seek bars etc from the “Gesture:” option. Lastly, the transition resulting due to moving from the hotspot to the assigned window in “Link To:” is selected from the “Transition:” menu. This process can be repeated for all the screens in the project. Finally for testing and previewing the final build, the screen which appears when the app starts is selected and further navigation, gestures etc. are tested there. So, building prototypes is quite…

Continue ReadingPrototyping PSLab Android App using Invision

Android App Debugging over WiFi for PSLab

Why do WiFi debugging when you have USB cable? PSLab is an Open Source Hardware Device which provides a lot of functionality that is required to perform a general experiment, but like many other devices it  only provides an Android mini usb port. This means developers can’t connect another USB cable as the  mini port is already busy powering and communicating with the USB device that is connected. How can developers debug our Android App over WiFi? Please follow these steps: Connect your Android Device to PC through USB cable and make sure USB-Debugging is enabled in Developers Option. Turn on Wifi of Android Device if its off and make sure its connected to router because that’s going to act as bridge between your Android device and PC for communication. Open your terminal and type adb tcpip 5555 Now see the IP of your Android Device by About Phone -> Status -> IP or adb shell netcfg Then type adb connect <DEVICE_IP_ADDRESS>:5555 Almost Done! Disconnect USB and start with wireless debugging. Now you would see your device coming up in the prompt when clicked run from Android Studio. All the logs can be seen in Android Monitor. Similarly as you see during debugging through USB cable. To get in touch with us or ask any question about the project, just drop a message at https://gitter.im/fossasia/pslab Also if this project interest you, feel free to contribute or raise any issue. PSLab-Android.

Continue ReadingAndroid App Debugging over WiFi for PSLab

The Pocket Science Lab Hardware

PSLab is a USB powered, multi-purpose data acquisition and control instrument that can be used to automate various test and measurement tasks via its companion android app, or desktop software. It is primarily intended for use in Physics and electronics laboratories in order to enable students to perform more advanced experiments by leveraging the powerful analytical and visualization tools that the PSLab’s frontend software includes. Real time measurement instruments require specialized analog signal processors, and dedicated digital circuitry that can handle time critical tasks without glitches. The PSLab has a 64MHz processor which runs a dedicated state machine that accepts commands sent by the host software, and responds according to a predefined set of rules. It does not deviate from this fixed workflow, and therefore can very reliably measure time intervals at the microsecond length scales, or output precise voltage pulses. In contrast, a GHz range desktop CPU running an OS is not capable of such time critical tasks under normal conditions because a multitude of tasks/programs are being simultaneously handled by the scheduler, and delays of the order of milliseconds might occur between one instruction and the next in a given piece of software. The PSLab combines the flexibility and reliability of its dedicated processor, and the high computational and visualization abilities of the host computer/phone’s processor to create a very advanced end product. And now, a flow diagram to illustrate the end product[1]: An outline of how this state machine works But first, you might be interested in the complete set of features of this instrument, and maybe screenshots from a few experiments . Here’s a link to a blog post by Praveen Patil outlining the oscilloscope, controls , and the data logger. From the flow diagram above, it is apparent that the Hardware communicates to the host PC via a bidirectional communication channel, carries out instructions, and might even communicate to a secondary slave via additional communication channels. The default state of the PSLab hardware is to listen to the host. The host usually sends a 2- byte header first, the first byte is a broad category classifier, and the second refers to a specific command. Once the header is received , the PSLab either starts executing the task , or listens for further data that may contain configuration parameters An example for configuring the state of the digital outputs [These values are stored in header files common to the host as well as the hardware: Bytes sent by the host : Byte #1 : 8     #DOUT Byte #2 : 1     #SET_STATE Byte #3 : One byte representing the outputs to be modified, and the nature of the modification (HIGH / LOW ). Four MSB bits contain information regarding the  digital outputs SQR1 to SQR4 that need to be toggled, and four LSBs contain information regarding the state that each selected output needs to be set to. Action taken by the hardware: Move to the set_state routine Set the output state of the relevant output pins (SQR1-4)…

Continue ReadingThe Pocket Science Lab Hardware

Sine Wave Generator

PSLab by FOSSASIA can generate sine waves with arbitrary frequencies. This is very helpful to teachers, students and electronic enthusiasts to study about different frequencies and how systems respond to them. In the device, it uses digital signal processing to derive a smooth sine wave. Except to digital implementation, there are conventional analog implementations to generate a sine wave. Image from https://betterexplained.com/articles/intuitive-understanding-of-sine-waves/ The most famous method to generate a sine wave is the Wien Bridge Oscillator. It is a frequency selective bridge with a range of arbitrary frequencies. This oscillator has a good stability when it is functioning at its resonance frequency while maintaining a very low signal distortion.           Let’s take a look at this circuit. We can clearly see that there is a series combination of a resistor and a capacitor at A and a parallel combination of a resistor and a capacitor at B joining at the non-inverting pin of the OpAmp. The series combination of RC circuit is nothing but a high pass filter that allows only high frequency components to pass through. The parallel combination of RC circuit is a Low pass filter that allows only the low frequency components of a signal to pass through. Once these two are combined, a band pass filter is created allowing only a specific frequency component to pass through. It is necessary that the resistor value and the capacitor values should be the same in order to have better performance without any distortion. Assuming that they are same, using complex algebra we can prove that the voltage at V+(3) is one third of the Voltage coming out from the pin (1) of OpAmp. Using the resonance frequency calculation using RC values, we can determine the frequency of the output sine wave. f=1/2RC The combination of two resistors at the inverting pin of the Op Amp controls the gain factor. It is calculated as 1+R1/R2. Since the input to the non-inverting terminal is 1/3 of the output voltage, this gain factor should be maintained at 3. Values greater than 3 will cause a ramping behavior in the sine wave and values below 3 will show an attenuation. So the gain should be set preciously. Equating 1+R1/R2 to 3, we can obtain a ratio for R1/R2 as 2. That implies R1 should be as twice the resistance of R2. Make sure these resistances are in the power of kilo Ohms. That is to ensure that the leakage current is minimum to the Op Amp. Let’s select R1 = 200K and R2 = 100K This oscillator supports a range of frequencies. Let’s assume we want to generate a sine wave having 500 Hz. Using f=1/2RC, we can choose arbitrary values for R and C. Substituting values to the formula yields a value for RC = 318 x10e-6 Using practical values for R as 10k, C value can be approximated to 33nF. This oscillator is capable of generating a stable 500 Hz sinusoidal waveform. By changing the resistive and capacitive values of…

Continue ReadingSine Wave Generator

Regulating Voltage in PSLab

Electronic components are highly sensitive to voltages and currents across them. Most of the devices in the current market work in the voltage levels of 3.3V, 5V, 12V and 15V. If they are provided with a different voltage than the one required by the vendor, they would not function. If the voltage supplied is higher, they might burn off. The PSLab device requires separate voltage levels such as 3.3V and 5V for its operation. There are commercial voltage regulators available in the market designed with advanced feedback techniques and models. But we can create out own voltage regulator. In this blog post, I am going to introduce you to a few basic models capable of regulating voltage to a desired level. Current implementation of PSLab device uses a voltage regulator derived using a zener-resistor combination. This type of regulators have a higher sensitivity to current and their operation may vary when the supplied or the drawn current is lower than the expected values. In order to have a stable voltage regulation, this combination needs to be replaced with a much stable transistor-zener combination. Before go into much details, let’s get to know a few basic concepts and devices related to. Zener Diode Zener diode is a type of diode which has a different operational behavior than the general diode. General diodes allow current to flow only in one direction. If a current in the reverse is applied, they will break and become unusable after a certain voltage level known as Breakdown Voltage. But Zener diodes are specifically designed to function desirably once this break down voltage has been passed and unlike general diode, it can recover back to normal when the voltage is removed or reduced. Transistor This is the game changing invention of the 20th century. There are two types of Bipolar Junction Transistors (BJT) available in the market. They are known as NPN and PNP transistors. The difference is based on the polarity of diodes used. An NPN transistor can be modeled as a combination of two diodes --[NP → PN]-- and a PNP transistor can be modeled as --[PN → NP]-- using two diodes. There are three pins to take notice in BJTs. They are illustrated in the diagram shown here; Base Collector Emitter The amazing fact about BJTs is that the amount of current provided to the Base terminal will control the flow of current going through Collector and Emitter. Also note that always there is a voltage drop across the Base terminal and the Emitter terminal. This typically takes a value of 0.7 V Voltage Divider This is the most basic type of voltage regulator. It simply divides the voltage supplied by the battery with the ratio R1:R2. In the following configuration, the output voltage can be calculated using the voltage division rule; Which is equal to 12 * 100/(100+200) = 4 V There is a huge drawback with this design. The above calculation is valid only if there is no load impedance is present…

Continue ReadingRegulating Voltage in PSLab