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

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.

## Designing A Virtual Laboratory With PSLab

### What is a virtual laboratory

A virtual lab interface gives students remote access to equipment in laboratories via the Internet without having to be physically present near the equipment. The idea is that lab experiments can be made accessible to a larger audience which may not have the resources to set up the experiment at their place. Another use-case scenario is that the experiment setup must be placed at a specific location which may not be habitable.

The PSLab’s capabilities can be increased significantly by setting up a framework that allows remote data acquisition and control. It can then be deployed in various test and measurement scenarios such as an interactive environment monitoring station.

### What resources will be needed for such a setup

The proposed virtual lab will be platform independent, and should be able to run in web-browsers. This necessitates the presence of a lightweight web-server software running on the hardware to which the PSLab is connected. The web-server must have a framework that must handle multiple connections, and allow control access to only authenticated users.

### Proposed design for the backend

The backend framework must be able to handle the following tasks:

• Communicate with the PSLab hardware attached to the server
• Host lightweight web-pages with various visual aids
• Support an authentication framework via a database that contains user credentials
• Reply with JSON data after executing single commands on the PSLab
• Execute remotely received python scripts, and relay the HTML formatted output. This should include plots

### Proposed design for the frontend

• Responsive, aesthetic layouts and widget styles.
• Essential utilities such as Sign-up and Sign-in pages.
• Embedded plots with basic zooming and panning facilities.
• Embedded code-editor with syntax highlighting
• WIdgets to submit the code to the server for execution, and subsequent display of received response.

### A selection of tools that can assist with this project, and the purpose they will serve:

#### Backend

• The Python communication library for the PSLab
• FLASK: ‘Flask is a BSD Licensed microframework for Python based on Werkzeug, Jinja 2 and good intentions.’   . It can handle concurrent requests, and will be well suited to serve as our web server
• MySQL: This is a database management utility that can be used to store user credentials, user scripts, queues etc
• WerkZeug: The utilities to create and check password hashes are essential for exchanging passwords via the database
• Json: For relaying measurement results to the client
• Gunicorn + Nginx: Will be used when more scalable deployment is needed, and the built-in webserver of Flask is unable to handle the load.

#### Frontend

• Bootstrap-css: For neatly formatted, responsive UIs
• Jqplot: A versatile and expandable js based plotting library
• Ace code editor: A browser based code editor with syntax highlighting, automatic indentation and other user-friendly features. Written in JS
• Display documentation:  These can be generated server side from Markdown files using Jekyll. Several documentation files are already available from the pslab-desktop-apps, and can be reused after replacing the screenshot images only.

#### Flow Diagram

[1]: Tutorial series  for creating a web-app using python-flask and mysql. This tutorial will be extensively followed for creating the virtual-lab setup.

[2]: Introduction to the Virtual Labs initiative by the Govt of India

[3]: Virtual labs at IIT Kanpur

## Creating Sensor Libraries in PSLab

The I2C bus of the PSLab enables access to a whole range of sensors capable of measuring parameters ranging from light intensity, humidity, and temperature, to acceleration, passive infrared, and magnetism.

Support for each sensor in the communication library is implemented as a small Python library that depends in the I2C communication module for PSLab.

However, most sensors have capabilities that are not just limited to data readouts, but also enable various configuration options.

This blog post explains how a common format followed across the sensor libraries enables the graphical utilities such as data loggers and control panels to dynamically create widgets pertaining to the various configuration options.

##### The following variables and methods must be present in each sensor file in order to enable the graphical utilities to correctly function:

Name: A generic name for the sensor to be shown in menus and such. e.g. ‘Altimeter BMP180’

GetRaw(): A function that returns a list of values read from the sensor. The values may have been directly read from the sensor, or derived based on some parameters/equations.

For example, the BMP180 altitude sensor is actually a pressure and temperature sensor. The altitude value is derived from these two using an equation. Therefore, the getRaw function for the BMP180 returns a list of three values, viz, [temperature, pressure, altitude]

NUMPLOTS: A constant that stores the number of available dataPoints in the list returned by the getRaw function. This enables the graphical utilities to create required number of traces . In case of the BMP180, it is 3

PLOTNAMES: A list of text strings to be displayed in the plot legend . For the BMP180, the following list is defined : [‘Temperature’, ‘Pressure’, ‘Altitude’]

params: A dictionary that stores the function names for configuring various features of the sensor, and options that can be passed to the function. For example, for the BMP180 altimeter, and oversampling parameter is available, and can take values 0,1,2 and 3 . Therefore, params = {‘setOversampling’: [0, 1, 2, 3]}

The Sensor data Logger application uses this dictionary to auto-generate menus with the ‘key’ as the name , and corresponding ‘values’ as a submenu . When the user opens a menu and clicks on a ‘value’ , the ‘value’ is passed to a function whose name is the corresponding key , and which must be defined in the sensor’s class.

When the above are defined, menus and plots are automatically generated, and saves considerable time and effort for graphical utility development since no sensor specific code needs to be added on that front.

The following Params dictionary defined in the class of MPU6050 creates a menu as shown in the second image:

```self.params = { 'powerUp':['Go'],
'setGyroRange':[250,500,1000,2000],
'setAccelRange':[2,4,8,16],
'KalmanFilter':[.01,.1,1,10,100,1000,10000,'OFF']
}
```

As shown in the image , when the user clicks on ‘8’ , MPU6050.setAccelRange(8) is executed.

### Improving the flexibility of the auto-generated menus

The above approach is a little limited, since only a fixed set of values can be used for configuration options, and there may be cases where a flexible input is required.

This is the case with the Kalman filter option, where the user may want to provide the intensity of the filter as a decimal value. Therefore we shall implement a more flexible route for the params dictionary, and allow the value to certains keys to be objects other than lists.

Functions with user defined variable inputs are defined as Spinbox/QDoubleSpinBox.

KalmanFilter is defined in the following entry in Params:

‘KalmanFilter’:{‘dataType’:’double’,’min’:0,’max’:1000,’prefix’:’value: ‘}

In this instance, the user can input a custom value, and the KalmanFilter function is called with the same.

[2]: Analyzing sensor data with PSLab android
[3]: YouTube video to understand analysis of data from MPU6050 with Arduino – https://www.youtube.com/watch?v=taZHl4Mr-Pk

## Environment Monitoring with PSLab

In this post, we shall explore the working principle and output signals of particulate matter sensors, and explore how the PSLab can be used as a data acquisition device for these.

### Working Principle

A commonly used technique employed by particulate matter sensors is to study the diffraction of light by dust particles, and estimate the concentration based on a parameter termed the ‘occupancy factor’. The following image illustrates how the most elementary particle sensors work using a photogate, and a small heating element to ensure continuous air flow by convection.

### Occupancy Rate

Each time a dust particle of aerodynamic diameters 2.5um passes through the lit area, a phenomenon called Mie scattering which defines scattering of an electromagnetic plane wave by a homogenous sphere of diameter comparable to the wavelength of incident light, results in a photo-signal to be detected by the photosensor.  In more accurate dust sensors, a single wavelength source with a high quality factor such as a laser is used instead of LEDs which typically have broader spectra.

The signal output from the photosensor is in the form of intermittent digital pulses whenever a particle is detected. The occupancy ratio can be determined by measuring the sum total of time when a positive signal was output from the sensor to the total averaging time. The readings can be taken over a fairly long amount of time such as 30 seconds in order to get a more accurate representation of the occupancy ratio.

### Using the Logic analyzer to capture and interpret signals

The PSLab has a built-in logic analyzer that can acquire data signals up to 67 seconds long at its highest sampling rate, and this period is more than sufficient to record and interpret a dataset from a dust sensor. An inexpensive dust sensor, DSM501A was chosen for the readings, and the following results were obtained

Dust sensor readings from an indoor, climate controlled environment. After the 100 second mark, the windows were opened to expose the sensor to the outdoor environment.

A short averaging time has resulted in large fluctuations in the readings, and therefore it is important to maintain longer averaging times for stable measurements.

### Recording data with a python script instead of the app

The output of the dust sensor must be connected to ID1 of the PSLab, and both devices must share a common ground which is a prerequisite for exchange of DC signals. All that is required is to start the logic analyzer in single channel mode, wait for a specified averging time, and interpret the acquired data

Record_dust_sensor.py

```from PSL import sciencelab   #import the required library
import time
import numpy as np
I = sciencelab.connect()           #Create the instance
I.start_one_channel_LA(channel='ID1',channel_mode=1,trigger_mode=0)  #record all level changes
time.sleep(30)   #Wait for 30 seconds while the PSLab gathers data from the dust sensor
a,_,_,_,e =I.get_LA_initial_states()      #read the status of the logic analyzer
raw_data =I.fetch_long_data_from_LA(a,1)  #fetch number of samples available in chan #1
stamps =I.dchans[0].timestamps    #Obtain a copy of the timestamps
if len(stamps)>2:   #If more than two timestamps are available (At least one dust particle was detected
if not self.I.dchans[0].initial_state:   #Ensure the starting position of timestamps
stamps = stamps[1:] - stamps[0]   # is in the LOW state
diff = np.diff(stamps)   #create an array of individual time gaps between successive level changes

lows = diff[::2]      #Array of time durations when a particle was not present
highs = diff[1::2]    #Array of time durations when a particle was present
low_occupancy = 100*sum(lows)/stamps[-1] #Occupancy ratio
print (low_occupancy) # datasheets of individual dust sensors also provide a mathematical
#equation to interpret the occupancy ratio as concentration of
#particulate matter
```

### Further Reading, and application notes:

[1] LED based  dust Sensor application note

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

##### 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) if required.
• Respond with an acknowledgement
• Move back to listening state
• Bytes Returned by the hardware:
• Byte #1 : 254 ACKNOWLEDGE. SUCCESSFUL.

In a similar manner, instruments ranging from oscilloscopes, frequency counters, capacitance meters, data buses etc are all handled.

For function calls that are time consuming, the communication process might be split into separate exchanges for initialization, and data download. One such example is the Oscilloscope capture routine. The first information exchange sets the parameters for data acquisition, and the second occurs when the acquisition process is complete.

##### Host-Side Scripts and Software

The software running on the host runs either a dedicated script that sequentially acquires data or executes control tasks , or it runs an event loop where user inputs are used to determine the acquisition task to be executed.

##### An example of a pulse sensor designed with just the voltmeter and a digital output of the PSLab.

A photo transistor is connected to the SEN input of the PSLab, and the host software reads the voltage on SEN at fixed intervals.

The conductance of the photo transistor fluctuates along with the incident light intensity, and this is translated into a voltage value by the internal signal processor of the SEN input.

When the photo sensor is covered with a finger, and a bright light is passed through the finger, a time linked plot of these voltage fluctuations reflects the fluctuations in blood pressure, and therefore has the same frequency of the heart beat of the owner of this finger.

* The digital output is used to power a white LED being used as the light source here

Bibliography:

[1] : Original content developed for the SEELablet’s first revision, from which PSLab is derived.

## Temporally accurate data acquisition via digital communication pathways in PSLab

This blog post deals with the importance of using a real-time processor for acquiring time dependent data sets. The PSLab already features an oscilloscope, an instrument capable of high speed voltage measurements with accurate timestamps, and it can be used for monitoring various physical parameters such as acceleration and angular velocity as long as there exists a device that can generate a voltage output corresponding to the parameter being measured.  Such devices are called sensors, and a whole variety of these are available commercially.

However, not all sensors provide an analog output that can be input to a regular oscilloscope. Many of the modern sensors use digitally encoded data which has the advantage of data integrity being preserved over long transmission pathways. A commonly used pathway is the I2C data bus, and this blog post will elaborate the challenges faced during continuous data acquisition from a PC, and will explore how a workaround can be managed by moving the complete digital acquisition process to the PSLab hardware in order create a digital equivalent of the analog oscilloscope.

Precise timestamps are essential for extracting waveform parameters such as frequency and phase shifts, which can then be used for calculating physics constants such as the value of acceleration due to gravity, precession, and other resonant phenomena. As mentioned before, oscilloscopes are capable of reliably measuring such data as long as the input signal is an analog voltage, and if a digital signal needs to be recorded, a separate implementation similar to the oscilloscope must be designed for digital communication pathways.

#### A question for the reader :

Consider a voltmeter capable of making measurements at a maximum rate of one per microsecond.

We would like to set it up to take a thousand readings (n=1000) with a fixed time delay(e.g. 2uS) between each successive sample in order to make it digitize an unknown input waveform. In other words, make ourselves a crude oscilloscope.

Which equipment would you choose to connect this voltmeter to in order to acquire a dataset?

1. A 3GHz i3 processor powering your favourite operating system, and executing a simple C program that takes n readings in a for loop with a delay_us(2) function call placed inside the loop.
2. A 10MHz microcontroller , also running a minimal C program that acquires readings in fixed intervals.

To the uninitiated, faster is better, ergo, the GHz range processor trumps the measly microcontroller.

But, we’ve missed a crucial detail here. A regular desktop operating system multitasks between several hundred tasks at a time. Therefore, your little C program might be paused midway in order to respond to a mouse click, or a window resize on any odd chores that the cpu scheduler might feel is more important. The time after which it returns to your program and resumes acquisition is unpredictable, and is most likely of the order of a few milliseconds.

The microcontroller on the other hand, is doing one thing, and one thing only. A delay_us(2) means a 2uS delay with an error margin corresponding to the accuracy of the reference clock used. Simple crystal oscillators usually offer accuracies as good as 30ppm/C, and very low jitter.

Armed with this DIY oscilloscope, we can now proceed to digitize a KHz range since wave or a sound signal from a microphone with good temporal accuracy.

### Sample results from the PSLab’s analog oscilloscope

If the same were taken via a script that shares CPU time with other processes, the waveform would compress at random intervals due to CPU time unavailability. Starting a new CPU intensive process usually has the effect of the entire waveform appearing compressed because actual time intervals between each sample are greater than the expected time intervals

##### Implementing the oscilloscope for data buses such as I2C

With regards to the PSLab which already has a reasonably accurate oscilloscope built-in, what happens if one wants to acquire time critical information from sensors connected to the data bus , and not the analog inputs ?

In order acquire such data , the PSLab firmware houses the read routine from I2C in an interrupt function that is invoked at precise intervals by a preconfigured timer’s timeout event. Each sample is stored to an array via a self incrementing pointer.

The I2C address to be accessed, and the bytes to be written before one can start reading data are all pre-configured before the acquisition process starts.

This process then runs at top priority until a preset number of samples have been acquired.Once the host software knows that acquisition should have completed, it fetches the data buffer containing the acquired information.

The plots that overlap accurately with a simulated damped sinusoidal waveform are not possible in the absence of a real-time acquisition system

The sensor in question is the MPU6050 from invensense, used primarily in drones, and other self-stabilising robots.

Its default I2C address is 0x68 ( 104 ) , and 14 registers starting from 0x3B contain data for acceleration along orthogonal axes, temperature, and angular velocity along orthogonal axes. Each of these values is an integer, and is therefore represented by two successive registers. E.g. , 0x3B and 0x3C together make up a 16-bit value for acceleration along the X-axis.