Integrating Stock Sensors with PSLab Android App

A sensor is a digital device (almost all the time an integrated circuit) which can receive data from outer environment and produce an electric signal proportional to that. This signal will be then processed by a microcontroller or a processor to provide useful functionalities. A mobile device running Android operating system usually has a few sensors built into it. The main purpose of these sensors is to provide user with better experience such as rotating the screen as he moves the device or turn off the screen when he is making a call to prevent unwanted screen touch events. PSLab Android application is capable of processing inputs received by different sensors plugged into it using the PSLab device and produce useful results. Developers are currently planning on integrating the stock sensors with the PSLab device so that the application can be used without the PSLab device.

This blog is about how to initiate a stock sensor available in the Android device and get readings from it. Sensor API provided by Google developers is really helpful in achieving this task. The process is consist of several steps. It is also important to note the fact that there are devices that support only a few sensors while some devices will support a lot of sensors. There are few basic sensors that are available in every device such as

  • “Accelerometer” – Measures acceleration along X, Y and Z axis
  • “Gyroscope” – Measures device rotation along X, Y and Z axis
  • “Light Sensor” – Measures illumination in Lux
  • “Proximity Sensor” – Measures distance to an obstacle from sensor

The implementing steps are as follows;

  1. Check availability of sensors

First step is to invoke the SensorManager from Android system services. This class has a method to list all the available sensors in the device.

SensorManager sensorManager;
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);

Once the list is populated, we can iterate through this to find out if the required sensors are available and obstruct displaying activities related to sensors that are not supported by the device.

for (Sensor sensor : sensors) {
   switch (sensor.getType()) {
       case Sensor.TYPE_ACCELEROMETER:
       case Sensor.TYPE_GYROSCOPE:

  1. Read data from sensors

To read data sent from the sensor, one should implement the SensorEventListener interface. Under this interface, there are two method needs to be overridden.

public class StockSensors extends AppCompatActivity implements SensorEventListener {

    public void onSensorChanged(SensorEvent sensorEvent) {


    public void onAccuracyChanged(Sensor sensor, int i) {


Out of these two methods, onSensorChanged() method should be addressed. This method provides a parameter SensorEvent which supports a method call getType() which returns an integer value representing the type of sensor produced the event.

public void onSensorChanged(SensorEvent sensorEvent) {
   switch (sensorEvent.sensor.getType()) {
       case Sensor.TYPE_ACCELEROMETER:
       case Sensor.TYPE_GYROSCOPE:

Each available sensor should be registered under the SensorEventListener to make them available in onSensorChanged() method. The following code block illustrates how to modify the previous code to register each sensor easily with the listener.

for (Sensor sensor : sensors) {
   switch (sensor.getType()) {
       case Sensor.TYPE_ACCELEROMETER:
           sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
       case Sensor.TYPE_GYROSCOPE:
           sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_UI);

Depending on the readings we can provide user with numerical data or graphical data using graphs plotted using MPAndroidChart in PSLab Android application.

The following images illustrate how a similar implementation is available in Science Journal application developed by Google.


Continue Reading Integrating Stock Sensors with PSLab Android App

The Pocket Science Lab: Who Needs it, and Why

Science and technology share a symbiotic relationship. The degree of success of experimentation is largely dependent on the accuracy and flexibility of instrumentation tools at the disposal of the scientist, and the subsequent findings in fundamental sciences drive innovation in technology itself. In addition to this, knowledge must be free as in freedom. That is, all information towards constructing such tools and using them must be freely accessible for the next generation of citizen scientists. A common platform towards sharing results can also be considered in the path to building a better open knowledge network.

But before we get to scientists, we need to consider the talent pool in the student community that gave rise to successful scientists, and the potential talent pool that lost out on the opportunity to better contribute to society because of an inadequate support system. And this brings us to the Pocket Science Lab

How can PSLab help electronics engineers & students?

This device packs a variety of fundamental instruments into one handy package, with a Bill-of-materials that’s several orders of magnitude less than a distributed set of traditional instruments.

It does not claim to be as good as a Giga Samples Per second oscilloscope, or a 22-bit multimeter, but has the potential to offer a greater learning experience. Here’s how:

  • A fresh perspective to characterize the real world. The visualization tools that can be coded on an Android device/Desktop (3D surface plots, waterfall charts, thermal distributions etc ), are far more advanced than what one can expect from a reasonably priced oscilloscope. If the same needs to be achieved with an ordinary scope, a certain level of technical expertise is expected from the user who must interface the oscilloscope with a computer, and write their own acquisition & visualization app.
  • Reduce the entry barrier for advanced experiments.: All the tools are tightly integrated in a cost-effective package, and even the average undergrad student that has been instructed to walk on eggshells around a conventional scope, can now perform elaborate data acquisition tasks such as plotting the resonant frequency of a tuning fork as a function of the relative humidity/temperature. The companion app is being designed to offer varying levels of flexibility as demanded by the target audience.
  • Is there a doctor in the house? With the feature set available in the PSlab , most common electronic components can be easily studied , and will save hours while prototyping new designs.  Components such as resistors, capacitors, diodes, transistors, Op-amps, LEDs, buffers etc can be tested.

How can PSLab help science enthusiasts ?

Physicists, Chemists and biologists in the applied fields are mostly dependent on instrument vendors for their measurement gear. Lack of an electronic/technical background hinders their ability to improve the gear at their disposal, and this is why a gauss meter which is basically a magnetometer coupled with a crude display in an oversized box with an unnecessarily huge transformer can easily cost upwards of $150 . The PSLab does not ask the user to be an electronics/robotics expert , but helps them to get straight to the acquisition part. It takes care of the communication protocols, calibration requirements, and also handles visualization via attractive plots.

A physicist might not know what I2C is , but is more than qualified to interpret the data acquired from a physical sensor, and characterize its accuracy.

  • The magnetometer (HMC5883L) can be used to demonstrate the dependence of the axial magnetic field on distance from the center of a solenoid
  • The pressure,temperature sensor (BMP280) can be used to verify the gas laws, and verify thermodynamic phenomena against prevalent theories.

Similarly, a chemist can use an RGB sensor (TCS3200) to put the colour of a solution into numbers, and develop a colorimeter in the process. Colorimeters are quite handy for determining molality of coloured solutions., and commercial ones are rather expensive. What it also needs is a set of LEDs with known wavelengths, and most manufacturers offer proper characterisation information.

What does it mean for the hobbyist?

It is capable of greatly speeding up the troubleshooting process . It can also instantly characterize the expected data from various sensors so that the hobbyist can code accordingly. For example, ‘beyond what tilt threshold & velocity should my humanoid robot swing its arms forward in order to prevent a broken nose?’ . That’s not a question that can be easily answered by said hobbyist who is currently in the process of developing his/her own acquisition system.

How can we involve the community?

The PSLab features an experiment designer that speeds acquisition by providing spreadsheets, analytical tools, and visualisation options all in one place. An option for users to upload their new experiments/utilities to the cloud, and subject those to a peer-review process has been planned. Following which , these new experiments can be pumped back into the ecosystem which will find more uses for it, improve it, and so on.

For example , a user can combine the waveform generator with an analog multiplier IC, and develop a spectrum analyzer.

The case for self-reliance

The average undergraduate laboratory currently employs dedicated instruments for each experiment as prescribed by the curriculum. These instruments often only include the measurement tools essential to the experiment, and students merely repeat the procedure verbatim. That’s not experimentation, it’s rather just verification. PSLab offers a wide array of additional instruments that can be employed by the student to enhance the experiment with their own inputs.

For example, a commonly used diode IV curve-tracer kit usually has a couple of power supplies, a voltmeter, and an ammeter. But, if a student wishes to study the impact of temperature on the band gap, he will hard pressed for the additional tools, and software to combine the acquisition process. With the PSLab, however , he/she can pick from a variety of temperature sensors (LM35, BMP180, Si7021 .. ) depending on the requirement, and explore beyond the book. They are thus better prepared to enter research labs .

And in conclusion , this project has immense potential to help create the next generation of scientists, engineers and creators.


Continue Reading The Pocket Science Lab: Who Needs it, and Why

Understanding PN Junctions with the Pocket Science Lab

The boundary layer between two thin films of a semiconducting material with Positive type and Negative type doping is referred to as a P-N junction, and these are one of the fundamental building blocks of electronics. These junctions exhibit various properties that have given them a rather indispensable status in modern day electronics.

The PSLab’s various measurement tools enable us to understand these devices, and in this blog post we shall explain some uses of PN junctions, and visualize their behaviour with the PSLab.

One might easily be confused and assume that a positive doping implies that the layer has a net positive charge, but this is not the case. A positive doping involves replacing a minute quantity of the semiconductor molecules with atoms from the next column in the periodic table. These atoms such as phosphorus are also charge neutral, but the number of available mobile charge carriers effectively increases.

A diode as a half-wave rectifier

A diode is basically just a PN junction. An ideal diode conducts electricity in one direction offering a path of zero resistance, and it is a perfect insulator in the other direction. In practice, we may observe some additional properties.

Figure : The circuit used for making the half-wave rectifier and studying it. A bipolar sinusoidal signal is input to a diode, and the output voltage is monitored. The 1uF capacitor is used to filter the output signal and make it more or less constant, but it has not been used while obtaining the data shown in the following image

Figure : A diode used as a half-wave rectifier. The input waveform shown in green was passed through a forward biased diode, and monitored by CH2 (red trace ) .

We can observe that only the positive half of the signal passes through the diode. It can also be observed , that since this is not an ideal diode, the conducted portion has lost some amplitude. This loss is a consequence of the forward threshold voltage of the PN junction, and in case of this diode, it is around 0.6 Volts. This threshold voltage depends on the band structure of the diode , and in the next section we shall examine this voltage for various diodes.

Measurement of Current-Voltage Characteristics of diodes

In practice, diodes only start conducting in the forward direction after a certain threshold potential difference is present. This voltage, also known as the barrier potential, depends on the band gap of the diode, and we shall measure it to determine how the electrical properties affect the externally visible physical properties of the diode.

A programmable voltage output of the PSLab (PV1) will be increased in small steps starting from 0 Volts, and a voltmeter input (CH3) will be used to determine the point when the diode starts conducting. The presence of a known resistor between PV1 and CH3 acts as a current limiter, and also enables us to calculate the current flow using some elementary application of the Ohm’s law. I = (PV1-CH3)/1000 .

The following image shows I-V characteristics of various diodes ranging from Schottky to Light Emitting Diodes (LEDs).

It may be interesting to note that the frequency of the light emitted by LEDs is directly proportional to the threshold voltage. In case of the white LED, it is almost similar to the blue LED because white LEDs are composed of blue LEDs, and a phosphor coating that partially converts blue light to yellow. The combination results in white light.

Zener diodes

Zener diodes are a special variant of diodes that also conduct electricity in the the reverse direction once a certain threshold has been crossed. This threshold can be determined during the manufacturing process, and zener diodes with breakdown voltages such as 3.3V , 5.6V , 6.8V etc are commercially available.

In the following image, the I-V characteristics of a 3.3V zener diode have been measured with the PSLab . As can be observed, the diode starts to conduct small amounts of current from around 2V itself, but significant current flow is usually present once the rated voltage is achieved.

In the forward direction, the zener appears to behave as a regular diode.


Continue Reading Understanding PN Junctions with the Pocket Science Lab

Using Hierarchical Blocks in KiCAD to Collaborate in PSLab Hardware Development

The PSLab hardware project designed in KiCAD, an ECAD tool; doesn’t support collaborative features like Git providing for software projects. As explained in a previous blog post on techniques to help up with project collaboration, this blog post will demonstrate how two developers can work together on the same hardware project.

The difficulties arise as the whole project is in one big schematic file. Editing made by one developer will affect to the editing done by the other developers causing merge conflicts. KiCAD doesn’t compile nicely if the changes were fixed manually most of the cases.

The solution practiced in the pslab-hardware project is using hierarchical blocks. This blog post will use a KiCAD project with an oscillator implementation and a voltage regulator implementation just like the ones in pslab-hardware schematics. To avoid complications in understanding changes in a huge circuit, only these two modules will be implemented separately in the blog.

Initially the project will look like the following figure;

Sheet1 Sheet2

These two hierarchical blocks will be created as different .sch files in the project directory as follows;

Assume two different developers are working on these two different blocks. That is the key concept in collaborating hardware projects in KiCAD. As long as the outer connections (pins) don’t get changed, edits made to one block will have no effect on the other blocks.

Developer 1 decided that the existing power circuit is not efficient for the PSLab device. So he decided to change the circuit in Sheet 1. The circuit before and after modification is shown in the table below.

Sheet 1 (Before) Sheet 1 (After)

If we take a look at the git status now, it will be as follows;

From this it is noticeable that neither the main schematic file nor Developer2.sch hasn’t been touched by the edits made to Developer1.sch file. This avoids merge conflicts happening when all the developers are working on the same schematic file.

Resources :

Continue Reading Using Hierarchical Blocks in KiCAD to Collaborate in PSLab Hardware Development

How to Read PIC Data-Sheet and Add a New Functionality to PSLab Firmware

Reading data-sheets is not a fun task. Going through tens of hundreds of pages with numerical, mathematical and scientific data is not fun reading. This blog post attempts to simplify reading the available data-sheets related to PIC24 micro-controller used in the PSLab device to help reader with implementing a new feature in PSLab firmware.

There are many features available in the PSLab device, such as; UART, SPI, I2C, ADC and Basic I/O reading. The “basic” implementation techniques do not vary much from one feature to other. That being stated this blog will carry out the basic implementation techniques one should follow and basic knowledge on PIC micro-controller programming to save himself from the trouble going through the 500+ pages in PIC data-sheets.

PIC Basics:

Before go into implementation there are few facts one should know about PIC programming.

– In the micro-controller values are saved in a memory block known as Registers. The values saved in these registers are volatile as they are all set to 0 regardless the value they were assigned when the power is off.

– Micro-controller configurations are made by setting values to these registers. Even turning on and off a whole feature like UART in PSLab device can be done using setting 0 to UARTEN register bit.

– When it comes to I/O ports, there are two different types of registers called TRIS and LAT/PORT. By setting 1 to TRIS ports will make the relevant pin an input pin. Setting it to 0 will make it an output pin. Easy way to remember this is think 1 as I in input and 0 as O in output. In UART implementation of PSLab, pin RP40 is set as an input pin to receive the data stream and pin RP39 is set as an output pin to send the data stream out. These settings are made using TRIS port settings. PORT registers save the value received by the relevant input pin attached to it.

The above figure extracted from mikroe learning materials, illustrates different stages an I/O pin can handle. As an extra point, ANSEL register makes the pin support digital signals or analog signals as per user requirements.

– In PIC, some registers such as PORT, TRIS and registers with similar functionalities are combined together. To access the value of each individual register can be done using dot notation. Assume the program requires to access the 8th register in TRISB register set. Note that the registers are indexed from zero. This implies that the 8th register will have the index 8 in the register sub-set. The following syntax is used to access the register;



The above points cover the basic knowledge one should have when developing firmware to PSLab device.

How to implement a feature like UART in PSLab firmware?

The first thing to know when implementing a new feature is that the developer needs to be familiar with the relevant hardware protocols. As an example, to implement UART; relevant protocol is RS232. If the feature is I2C; one should know about the I2C protocol.

Once the feature is familiar, next step is to refer the PIC data-sheet and resources on how to implement it in firmware. As for demonstrative purposes, this blog will continue with UART implementation.

Download the latest data-sheet from MicroChip official website and browse to the table of content. It consists of a set of features supported by the micro-controller implemented in the PSLab device. Find the entry related to the feature being implemented. In this case it will be Universal Asynchronous Receiver Transmitter (UART).

Each feature will contain a description following this format explaining what are the options it support and its constraints.

One must be aware of the fact that not every pin in the micro-controller can be used for any feature as he desires. The “PINOUT I/O DESCRIPTIONS” section in the data-sheet explains which pins are capable of the feature being implemented. According to these details, the pins should be initiated as Input/Output pins as well as Digital/Analog pins.

The next step is to refer to the control registers related to the feature. They are all mentioned in the data-sheet under the specific feature. There are some notations available in this section which resembles something like the following;

PDSEL<1:0>: Parity and Data Selection bits
11 = 9-bit data, no parity
10 = 8-bit data, odd parity
01 = 8-bit data, even parity
00 = 8-bit data, no parity


This represents a register with two bits. By setting either 11 or 10 or 01 or 00; different implementations can be achieved.

In PSLab firmware this is implemented as;

U1MODEbits.PDSEL = 0;


which implements UART feature with 8-bits stream having no parity bits for error correction.

In UART feature implemented in PSLab device, receiving bit stream is fetched by reading the register values in U1STAbits.URXDA and data is transmitted using U1TXREG. All these registers are mentioned in the control registers section in the feature.


Continue Reading How to Read PIC Data-Sheet and Add a New Functionality to PSLab Firmware

Create a Distance Sensor using PSLab

PSLab device is a small lab which supports a ton of features. Among its many features, integrating a distance measuring sensor like HC SR04 sonar sensor into it is one of them. This blog post will bring out the basic concepts behind a sonar sensor available in the current market, how it measures distance and how it is implemented in the PSLab device.

A sonar sensor uses a sound wave with a very high frequency. These waves are called ultrasonic waves. They cannot be heard by the naked ear. Human ear can only hear frequencies from 20 Hz up to 20 kHz. Generally HC SR04 sensors use a wave with frequency as high as 40 kHz so this makes sense. The basic principal behind the sensor is the reflectance property of sound. Time is calculated from the transmission time up to the time receiving the reflected sound wave. Then using general moment equation S = ut; with the use of speed of sound, the distance can be measured.

The figure shows a HC SR04 ultrasound sensor. They are quiet famous in the electronic field; especially among hobbyists in making simple robots and DIY projects. They can be easily configured to measure distance from the sensor up to 400 cm with a measuring angle of 15 degrees. This angular measurement comes into action with the fact that sound travels through a medium in a spherical nature. This sensor will not give accurate measurements when used for scenarios like measuring distance to very thin objects as they reflect sound poorly or there will not be any reflectance at all.

There are four pins in the HC SR04 sonar sensor. Corner pins in the two sides are for powering up the Sonar sensor. The two pins named ECHO and TRIG pins are the important pins in this context. When the TRIG pin (Trigger for short) is excited with a set of 8 square pulses at a rate of 40 kHz, the ECHO pin will reach to logic HIGH state which is the supply voltage (+5 V). When the transmitted sound wave is reflected back to the sensor, this high state of the ECHO pin will shift to logic LOW state. If a timer is turned on when the ECHO pin goes to logic HIGH state, we can measure how long it was taken for the sound beam to return to the sensor by turning off the timer when the ECHO pin goes to logic LOW state.

Having described the general implementation of a sonar sensor; a similar implementation is available in PSLab device. As mentioned earlier, TRIG pin requires a triggering pulse of 8 set of square waves at 40 kHz. This is achieved in PSLab using SQR pulse generating pins. The time is measured from the transmitting point until the receiving point to evaluate the distance. The real distance to the obstacle in front of the sensor can be calculated using following steps;

  1. Measure total round trip time of the sound beam. Take it as t
  2. Calculate the time taken for the beam to travel from sensor to the obstacle. It will be t/2
  3. Use motion equation S = ut to calculate the actual distance taking u = speed of sound in air. Substituting the time value calculated in step 2 to t, S will produce the distance


Continue Reading Create a Distance Sensor using PSLab

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 a name

Step 05 – Enter sheet

Step 06 – Place components and create a schematic design inside the sheet and place hierarchical labels

Step 07 – Define the labels as input or output and give them an identifier. Once done, place them on appropriate places and connect with wires

Step 08 – Go back to main sheet to complete the hierarchical block

Step 09 – Place hierarchical pins on the block

Click on the “Place hierarchical pin” icon from the toolbar and click on the block. The pins can be placed on anywhere on the block. As a convention, input pins are placed on the left side and the output pins are placed on the right side of the block.

Step 10 – Complete the circuit


Continue Reading How 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 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 29, 30, 32, 33, 35, 36, 38, 40, 41, 43, 45, 47, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 73, 75, 77, 79, 82, 84, 86, 89, 91, 93, 96, 98, 101, 103, 106, 108, 111, 114, 116, 119, 121, 124, 127, 130, 132, 135, 138, 141, 143, 146, 149, 152, 155, 158, 161, 164, 166, 169, 172, 175, 178, 181, 184, 187, 190, 193, 196, 200, 203, 206, 209, 212, 215, 218, 221, 224, 227, 230, 234, 237, 240, 243, 246, 249, 252, 256, 259, 262, 265, 268, 271, 274, 277, 281, 284, 287, 290, 293, 296, 299, 302, 305, 308, 311, 315, 318, 321, 324, 327, 330, 333, 336, 339, 342, 345, 347, 350, 353, 356, 359, 362, 365, 368, 370, 373, 376, 379, 381, 384, 387, 390, 392, 395, 397, 400, 403, 405, 408, 410, 413, 415, 418, 420, 422, 425, 427, 429, 432, 434, 436, 438, 441, 443, 445, 447, 449, 451, 453, 455, 457, 459, 461, 463, 464, 466, 468, 470, 471, 473, 475, 476, 478, 479, 481, 482, 484, 485, 486, 488, 489, 490, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 503, 504, 505, 505, 506, 507, 507, 508, 508, 509, 509, 509, 510, 510, 510, 511, 511, 511, 511, 511, 511, 511, 511, 511, 511, 511, 510, 510, 510, 509, 509, 509, 508, 508, 507, 507, 506, 505, 505, 504, 503, 503, 502, 501, 500, 499, 498, 497, 496, 495, 494, 493, 492, 490, 489, 488, 486, 485, 484, 482, 481, 479, 478, 476, 475, 473, 471, 470, 468, 466, 464, 463, 461, 459, 457, 455, 453, 451, 449, 447, 445, 443, 441, 438, 436, 434, 432, 429, 427, 425, 422, 420, 418, 415, 413, 410, 408, 405, 403, 400, 397, 395, 392, 390, 387, 384, 381, 379, 376, 373, 370, 368, 365, 362, 359, 356, 353, 350, 347, 345, 342, 339, 336, 333, 330, 327, 324, 321, 318, 315, 311, 308, 305, 302, 299, 296, 293, 290, 287, 284, 281, 277, 274, 271, 268, 265, 262, 259};


The frequency of the sine wave is achieved using interrupts generated at different time intervals depending on the frequency set by the user. The accuracy of the frequency depends on the number of elements in the sine table array which is known as resolution. As the number of points in the table increases, the accuracy will be increased or resolution will be high. PSLab uses Timer3 and Timer4 counters available in the PIC micro-controller to generate the interrupt time intervals. If the required frequency is f, the interrupt time interval can be derived as

Interrupt time = f/512

The derived SPWM waveform will be then passed through a cascaded setup of Op Amp and RC filter as in Figure 1 to cut off the high frequency components and combine the square pulses in such a manner that a smoother waveform is derived resembling a sine wave.

Filter Circuit in PSLab

Figure 1

This is an inverting filter circuit designed using Op Amps available in PSLab-hardware. The SPWM waveform will be connected to the circuit through R1 resistor. It uses C1 capacitor which creates a short circuit path to high frequency components to ground which will let only the low frequency components to pass through. This will smoothen the square waves reducing the sharp edges forming a simple RC filter circuit.

The C2 capacitor plays an important role in generating the sine wave. It will compensate any voltage drops and absorb excess voltage levels that might occur during transition to let the output waveform follow a path which is similar to a smooth sine wave.

The output waveform can be observed from the SINE1 pin of the PSLab device. As in this schematic, it is the ‘Sine Wave’ pin to the right starting from the Op Amp output.


Continue Reading Generate Sine Waves with PSLab Device

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


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.


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 block A and B, we can generate a wide range of frequencies that are supported by the Op Amp because Op Amps have a limited bandwidth it can be functional inside.

It’s worth to note a few facts about generating sine waves using a digital implementation. In analog circuitry, the component values have a tolerance which makes the calculations not perfectly align with the real values. Due to this reason, the actual output will differ from the desired output. In our example to generate 500 Hz sine wave, the capacitors and resistors may have different values and they may have not matched. But with a digital implementation, we can achieve the accuracy and flexibility we require.

External Links:


Continue Reading Sine 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 DiodeZener 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.


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;

  1. Base
  2. Collector
  3. 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 at the output terminals.

Generally there will be a load impedance and the supplied voltage cannot be easily calculated as the load impedance is unknown to the regulator.

Resistor-Zener Voltage Regulator

Due to the load dependability of the previous model with the load, an improved model can be introduced as follows. This is the current implementation of voltage regulator in PSLab device.

Unlike the previous model, this model ensures that the output voltage will be maintained constant across the output terminals within a range of supply voltage values.

Let’s assume the supply voltage is increased. Then the current flow through the zener diode will increase in order to maintain a constant voltage across the output terminals. In case if the supply voltage drops, then the zener current will decrease and a stable voltage across the output terminals will be maintained.

This design also comes with a slight draw back. This can be explained using the characteristic curve of a zener diode. (Figure is taken from : http://www.electronics-tutorials. ws/diode/diode_7.html)

For a zener diode to maintain a constant voltage level across output terminals, there should be a minimum current flowing through the diode. If this current is not flowing in the zener, there won’t be a regulation. Assume there is a very low load impedance. Then the current supplied by the source will find an easier path to flow other than through the diode. This will affect the regulatory circuit and the desired voltage will not appear across the output terminals.

To compensate the drawback, a much improved design is available using transistors.

Transistor-Zener Voltage Regulator

This is the proposed improvement to the voltage regulatory circuit in PSLab device. In this model, the zener diode is taken away from the load circuit as the current to the load is supplied from the transistor directly. This avoids current limitations to the zener diode had in the previous model and transistor acts as a bridge.

A small current through the Base terminal (1) will support a higher current flow through the output terminal via Collector (2) and Emitter (3). This amplification ratio is in the range of few hundreds for a typical BJT.

A capacitor has been added to compensate ripples from the supply source. If a higher current flow is required through the output terminals, the NPN transistor can be replaced by a Darlington pair.

Using a 5.6 V zener diode and MMBT3904/6 transistors, this model has been implemented in the newest version of PSLab device. They will be supplying a constant voltage of +/- 5V to V+ and V- pins in the device.

External Links:

Continue Reading Regulating Voltage in PSLab