Sunday, 19 February 2017

How to make a Twin T Notch Filter

Analogue Electronics can be hard!  If an engineer doesn't do much design or calculations all the time the skills can be lost.  I have personally probably forgotten far too much.  Helpfully there are reference materials both online and in books to help remind ourselves what we need to do!

I need to design and implement a band stop filter.  This because I need to make some circuit measurements and the 13.56 MHz signal (inherent to the circuit being measured) is swamping the input stage of a spectrum analyser.  I would like to be able to measure all the signal above 30 MHz without it being affected by out of band noise.  This is a common problem when using sensitive electronic instrumentation...what appears on screen is not always correct due to unknown out of band noise.

A Twin T Notch Filter Circuit
The go to circuit of choice in these situations is known as the Twin T Notch filter.  It's a great filter circuit that is easy to implement because of its low component count.  The websites below discuss the theory behind band stop filters and Twin T Notch filters:

The quick way to design such a filter is to set the required parameters and then use the formula given. The parameters for my filter are:
  • Must use preferred component values
  • Must not filter signals above 30 MHz
  • Must have at least 30 dB of rejection at 13.56 MHz
The formula for calculating the component values is:

Now we can either plug some numbers into the formula above and try and get close to where we want to be or we can use an online calculator tool.  I am all for quickness and see little point in doing mathematics when I don't have to!  Here is a very useful site for calculating Notch filter component values:

Credit should definitely be given to the engineers and Okawa-Denshi Electronics Design in Japan!

The useful thing about simulators is the component values can be selected based upon those available and not some pie in the sky value...some less helpful calculators prescribe using component values which either do not exist in the real world or require the skill of a police detective to obtain!

I also have found that when using online circuit calculators it is important to fix at least one of the component values before you start calculating things.  I entered 13.56 MHz as the centre frequency for the filter and set the value of C1 to 10 pF and C2 and C3 to 4.7 pF as these are real world (preferred) values in the E6 series.

Useful site for preferred values: 

The online calculator did it's thing and provided the circuit below:
The Centre frequencies were:
  • Flow = 13.555950 MHz
  • FHigh = 13.679649 MHz
The frequency response of filters is often shown as a special type of graph known as a Bode plot. This is shown below:

I have no doubt that if properly constructed this circuit would provide the filter response I'm looking for - It has 40 dB of rejection at 13.56 MHz, it doesn't filter the signal for frequencies above 30 MHz but the resistor values whilst available are not values I have readily to hand.  Because of that I'm going to tweak the capacitor values and run the calculator again.

I have changed the values of C2 and C3 to 22 pF which follows the rule that C2 and C3 must be roughly double C1....Here is the circuit that the calculator came up with:
Again...this circuit would probably work but I'm still not happy with the resistor values.  They are hard to obtain.  I'm going to increase the values of the capacitors again and see what happens.  The values I have chosen are C1 = 15 pF, C2 and C3 = 82 pF
The resistor values are now much more common and available.  Lets hope the filter response is good enough.

The Centre frequencies were:
  • Flow = 13.496806 MHz
  • FHigh = 13.654780 MHz
The corresponding Bode plot:

From the numbers given and by interpreting the Bode plot this circuit meets my requirements. If I wanted I could fit a 22 pF capacitor in the C1 position and a similar result will be obtained.  That will also change the resistor values as well:

I'm liking these values the most as I am certain I have all of these components available.  I wasn't sure if I have a 15 pF capacitor. It's not a value I use much - easily obtained from any good component vendor but always best to use what you have!

The resistor values are now much more common and available.  Lets hope the filter response is good enough.

The Centre frequencies were:
  • Flow = 13.374485 MHz
  • FHigh = 13.587897 MHz
The corresponding Bode plot:

Now that we have our component values we need to calculate the power requirements.  In this case I want to be able to put as much electrical power through the filter as possible.  The signal strength of the 13.56 MHz signal in my case will be at least 20 Watts.  Therefore each component must be capable of withstanding that power level without being burnt out.

I happen to know that the 13.56 MHz signal will be coming from a signal generator and amplifier at +30 dBm.  If we convert +30 dBm into Watts we find that it is 1 Watt.  So all components need to be rated for one Watt or better. Just for fun here is the formula:

dBm = 10 * Log10 * 1 * 10^-3 (Watts)

We need to rearrange to get Watts:

10^-3 (Watts) =10^(dBm/10)) 

If we now plug the values in we get:

10^-3 (Watts) =10^(30/10))

Which is equal to 1000 * 10^-3 Watts or 1000 milli-Watts which is 1 Watt 

So all of the resistors need to be 1 Watt rated or better.  I'm going to need a small enclosure with connectors for this circuit and that means I'm probably going to need a printed circuit board.

I have used these diecast boxes in the past for this purpose - they are useful because they come with BNC connectors already fitted:
They are made by Pomona Electronics and are available from most good electronics vendors like RS components and Farnell Electronics.  My only complaint is the cost - £28.04 - yikes!

The datasheet for the box is here:

The dimensions of the Box are below:

Rather unhelpfully the inner dimensions are not provided - I hate it when that happens. However it isn't too much of a concern, reasonable estimations can be made.

If the printed circuit board is 36 mm x 33 mm and when populated is less than 25 mm high it will fit the above box well enough.

Here is how the layout came out:

I have chosen to use surface mount components throughout and 2512 size resistors so that the power requirements are met.  The board should easily fit inside the enclosure chosen.  The dimensions shown are in mm - for those that might be interested.

Just for fun here is how the PCB will look when populated:

ISO view of the Notch Filter PCB
The top side of the Notch Filter PCB
The side view of the Notch Filter PCB
Just for fun and because I wanted to practice my 3D drawing and modelling skills I have drawn up the Pomona 3231 Box.  It is available for download at the 3D warehouse if people are interested. Here is the PCB inside the box:

Top view of the PCB in the 3231 Pomona Box

ISO view of the PCB in the 3231 Pomona Box
Finally all that is left to do on this is create a bill of materials and calculate the total cost for this Filter.  I normally buy my components from Farnell Electronics but anywhere would do.

Component Value Quantity Footprint Part Number Cost (£) Notes

Resistor 390 Ohms 5 2512 2476478 0.604 3 Watt resistor from Farnell
Resistor 27 Ohms 5 2512 2476450 0.604 3 Watt resistor from Farnell
Capacitor 82 pF 10 0603 722078 0.015 C0G from Farnell
Capacitor 22 pF 10 0805 1759489 0.0323 C0G from Farnell
PCB N/A 10 N/A N/A 14.04 10 PCBS from Elecrow
Pomona 3231 Case N/A 1 N/A 1234948 28.04 From Farnell

Unfortunately I could not get an 0805 82 pF capacitor which is annoying but I can fit an 0603 part. The total cost for the above is £43.34 - That is enough components and PCBS to make one complete unit with plenty of spares.  The cost of a single unit alone is £29.70 which I think isn't too bad.  Those pomona cases are very expensive - I might investigate a cheaper solution at some point.

The good news is all of the resistors I found are 3 Watt parts which means the filter will be able to work with high power signals!

The more astute readers may know that it is possible to buy a notch filter from various RF vendors.  I did consider these options and for those that may be interested the following websites have them on sale:

I couldn't find one that specifically sells a 13.56 MHz Band Stop Filter although I suspect such products do exist.  I doubt that I would be able to buy one for less than £30

If I do decide to make one of these I will test it and provide the results and photos.  Hopefully this was of interest to someone - Take care always - Langster!

Saturday, 16 July 2016

Switch De-bouncing in VHDL for the Mimas V2 FPGA Development Board

It's been a while since I blogged about my adventures in relearning VHDL.  I am slowly regaining the knowledge I used to have when I studied at University (That seems a very long time ago now). Slowly and steadily I'm building up the knowledge needed to use an FPGA for something useful.

I intend writing a couple of connected blog posts over the next week or so in order to demonstrate something more involved (and useful).

This post will concentrate on reading input from a momentary switch.  The Mimas V2 board has six momentary switches on the right side of the board below the micro-SD card slot.  Lets write some code which reads in one these switches with de-bounce code.  We can then use this code to implement a counter which we can display on the seven segment display.  The counter and the seven segment display section will be in later posts.  For now lets concentrate on reading in the switch properly.  For now we can display the output onto an LED

Mimas V2 Momentary Switches
Here is the general idea:
  1. Start
  2. User Presses a momentary switch.
  3. The FPGA reads in the button switch.
  4. The button read is de-bounced.
  5. The corresponding LED is illuminated until the button is released.
  6. Go back to step 1.
  7. End.
Lets fire up Xilinx WebISE and start a new project:

I called mine Mimas_switchDebounce - use any name you like!  Click next when ready:

Make sure all the above settings are entered so that the project is setup correctly for the Mimas V2. Click next when you are ready:

Click Finish to return to the main project screen.

Now left click on the project menu and select 'add new source':

In the dialog window that appears select VHDL Module and give it a suitable name - I called mine switchDebounce:

Click 'Next' when you are ready to continue:

We need to define the inputs and outputs for the debounce code.  We need to read in the raw button presses and then we need to display the results on an LED.  This all needs to be synchonised with the 100 MHz clock on the Mimas V2.  

Complete the form with the above settings and then click 'Next' to continue:

Click 'Finish' to return to the main project screen in WebISE:

Xilinx Webise has helpfully automatically generated some code for us....Let's examine the code.

LIBRARY IEEE; USE IEEE.STD_LOGIC_1164.ALL; ENTITY switchDebounce IS PORT ( CLK : IN STD_LOGIC; Switch_0 : IN STD_LOGIC; LED_0 : OUT STD_LOGIC ); END switchDebounce; ARCHITECTURE Behavioral OF switchDebounce IS BEGIN END Behavioral;

The entity statement defines the inputs and outputs to the FGPA - three standard logic pins, the switch input, the LED output and the 100 MHz system clock.

The architecture statement is where the 'behaviour' of the code will be defined.  There isn't anything in it yet but there will be!  Lets decide how we are going to achieve things.  There is more than one way of reading in buttons, checking that the button state has changed and then producing a result.

Lets make things easier for ourselves and draw a flow diagram:

This should make writing the code a little easier for us.  Every diamond is an if statement, every rectangle is a part of a process....simples!

From the flow diagram we should be able to write the behavioural section of the code:

ARCHITECTURE Behavioral OF switchDebounce IS
SIGNAL inputFlipFlop : STD_LOGIC_VECTOR(1 DOWNTO 0); CONSTANT countMax : INTEGER := 100000000; SIGNAL count : INTEGER RANGE 0 TO countMax := 0; BEGIN PROCESS (clk) BEGIN IF (clk'EVENT AND clk = '1') THEN inputFlipFlop <= inputFlipFlop(0) & Switch_0; IF (inputFlipFlop(0) /= inputFlipFlop(1)) THEN count <= 0; ELSIF (count < countMax) THEN count <= count + 1; ELSE LED_0 <= inputFlipFlop(1); END IF; END IF; END PROCESS; END Behavioral;

Lets go though how the above code works:

SIGNAL inputFlipFlop : STD_LOGIC_VECTOR(1 DOWNTO 0); -- input flip flops CONSTANT countMax : INTEGER := 100000000; -- 100 MHz clock, delay is 100 ms and 100 ms = 10,0000000 ns SIGNAL count : INTEGER RANGE 0 TO countMax := 0;

The above lines create internal signals.  The first signal inputFlipFlop is a simple flip flop.  It is used to check if the button has been pressed or released (changed state).  The constant countMax is the delay period that is set to ensure that a button has actually been pressed.  It has been set to 100 ms although any number can be used.  It was calculated from the 100 MHz source clock.  1/100,000,000 = 1 ns and 10,000,000 ns is equivalent to 100 ms.  If a second was needed then the constant should be set to 1000000000 etc.  The signal count is the value of the number of clock pulses that has passed.  It is dynamically set to the maximum delay period set by countMax.

BEGIN PROCESS (clk) BEGIN IF (clk'EVENT AND clk = '1') THEN inputFlipFlop <= inputFlipFlop(0) & Switch_0; -- read the switch state IF (inputFlipFlop(0) /= inputFlipFlop(1)) THEN -- has flipflop changed state from previous state count <= 0; -- if flipflop has changed then reset count ELSIF (count < countMax) THEN -- if flipflop has changed is count less than countMax count <= count + 1; -- increment count by one ELSE -- count has reached countMax LED_0 <= inputFlipFlop(1); -- set LED_0 to the same state as the flip flop END IF; END IF; END PROCESS; END Behavioral;

The above lines perform the function that is required - the subject of the flow diagram:  
  • If the clock has changed state and is high then check if the flip flop has changed state.  
  • If the flip flop has changed state from it's previous state - This means a button has been pressed and if a button has been pressed then the count needs to be reset.  
  • If the count is less than the delay period then the count must be incremented.  
  • If the count has reached the delay period then the LED state needs to match the flip flop state.   
Here is the entire source code in case it's needed:


ARCHITECTURE Behavioral OF switchDebounce IS
SIGNAL inputFlipFlop : STD_LOGIC_VECTOR(1 DOWNTO 0); CONSTANT countMax : INTEGER := 100000000; SIGNAL count : INTEGER RANGE 0 TO countMax := 0; BEGIN PROCESS (clk) BEGIN IF (clk'EVENT AND clk = '1') THEN inputFlipFlop <= inputFlipFlop(0) & Switch_0; IF (inputFlipFlop(0) /= inputFlipFlop(1)) THEN count <= 0; ELSIF (count < countMax) THEN count <= count + 1; ELSE LED_0 <= inputFlipFlop(1); END IF; END IF; END PROCESS; END Behavioral;

Save the file just in case - it's always a good idea to save your work!

Now we need to create an implementation constraints file to tell the system which pins are connected to the clock, switch and the LED.

Create an implementation constraints file using the same method used to create the VHDL source code.  Call it something sensible like switchDebounce.  Copy the code below into the file:

# This file is a .ucf for Mimas V2                                                                    #
# To use it in your project :                                                                         #
# * Remove or comment the lines corresponding to unused pins in the project                           #
# * Rename the used signals according to the your project                                             #

#                                            UCF for MIMAS V2 Spartan 6 Development Board             #


   NET "CLK"      LOC = V10 | IOSTANDARD = LVCMOS33 | PERIOD = 100MHz;

#                                              Push Buttons Switches                                  #
    NET "Switch_0"           LOC = M18   | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST | PULLUP; 

#                                                    LEDs                                             #
    NET "LED_0"              LOC = P15  | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST ;

Now it's time to 'compile' the code into a bit file and upload it to the Mimas V2:

Click on the green 'implement top module' arrow and wait for the code to compile.  There should not be any errors or warnings.

Now connect up the Mimas V2 board to your computer via a suitable USB cable and then fire up the Mimas V2 configuration tool.  If you are using Linux then use the appropriate python tool - I don't use linux often....only so much time to learn new things at the moment!  Select the appropriate COM port for your board and then navigate to the the newly created bin file and click program!

Once programming is complete you should see something similar to the following:

The more astute among us will notice that the LED starts high and is turned low when a button press is detected.  That is because the switches on the Mimas V2 board are active low....the code logic will need to be inverted in order to take the LED from low to high.  It's a simple enough edit.  We could also remove the seven segment display ghosting if needed...

That's all for now though people - more to come on this - next it's count the button press and display the result on the seven segment!

Hint change the line of code from LED_0 <= inputFlipFlop(1); to LED_0 <= not inputFlipFlop(1);

Wednesday, 15 June 2016

Linux on the Mimas V2

Recently I found out it's possible to run an embedded version of linux on the Mimas V2 FPGA development board.  I'm not the best person at using linux but I did manage to get it working.

It is thanks to a lot of hard work that has been performed the people at J2-Open Processor:

In order to make use of it you will probably need to update your Mimas V2 programmer firmware to work at 115200 baud.  This is so that the serial communications from the Linux core will work at a reasonable rate.

In order to achieve that you will need a micro-SD card capable of storing a small linux image.  Get hold of a micro-sd card and then download vmlinux from the link below:

Copy the file onto the micro-SD card.  Do not try to write it as an image....its not like a raspberry Pi
( I may have made this mistake - thanks for the help Goran! )

Next you will need to update the programming firmware on your Mimas V2 to work at 115200 baud.
The firmware update increases the speed of communication between the PIC microcontroller and the FPGA device to 115200 Baud which is what is needed to upload programs from the arduino IDE.

You will need to download the following things in order to update the firmware:

Hex file to update baud rate to 115200

*Warning* There is currently no firmware to return the Mimas V2 PIC Microcontroller to it's original state and the updated firmware is currently beta only - it does have some issues. These are being addressed but at the moment there is currently no way to return the PIC on the Mimas V2 board to its factory settings.

I have not found any issues from doing this upgrade as yet however.

When my version of the Mimas V2 FPGA development arrived as new it did not have some header pins soldered into P3 - So I had to solder some in. This is needed to perform the PIC firmware upgrade:

Mimas V2 FPGA Development board without Firmware Upgrade Header

Here is my board with the header pins soldered in:

Next you will need to short the pins together to put the PIC Microcontroller into firmware upgrade mode:

Connect up the Mimas V2 FPGA development board to your computer - it's time to update the PIC firmware! When you connect up the FPGA development board windows will install a generic USB driver for the PIC device - this is meant to happen.

Open the folder where the software has been downloaded and execute up the firmware downloader program, Ignore the standard windows warning message - the program is fine. You should see something similar to the image below:

Click on 'Open Hex File' and navigate to where the 115200 baud update file was extracted - it's called MimasV2W@115200Beta.hex:

Click 'Open' to continue and then click on 'Program/Verify':

If all went according to plan you should see the above message!

Once that has been done you can remove the programming link.  Now it's time to upload the bin file to the FPGA which will create a soft processor which then accesses the micro-SD card and runs a version of Linux.

Now we need to download the file below - it's the bin file for the FPGA which runs at 115200 baud and adds the soft processor to the FPGA etc

The upload it to the FPGA using the appropriate program - don't use linux so I use the MimasV2Config.exe program in Windows.  If you are using Linux then there are python scripts available.

Select the COM port associated with your Mimas V2 FPGA Development board - mine was COM 22:

Then click on 'Open File' and navigate to where the mimas_v2_115200.bin file is located:

Then Click program!

Once it has completed.  The FPGA will reboot and the seven segment display will go through a process.  At the end of the process it should look the like the picture below:

Next it is time to check all is working.  Move the programming direct switch SW7 over to the right - towards the VGA connector.  Then load up the serial terminal program of choice.  In my case I use RealTerm but in theory any serial terminal software 'should' work:

It is important to set the display to ANSI so ensure that spurious characters are not displayed.  In realTerm:

Then click on the port tab and set it to reflect the settings for the serial port on the Mimas:

Then when you are connected it should be possible to reboot the board by manipulating SW7:

Once it has completely booted the command line prompt should be displayed:

Type some commands in and check all is working!  I tried LS and DMESG etc.  All seemed to respond correctly.  I should be honest here and explain that my Linux skills are not as strong as they could be.  I use it when necessary.  I have only so much time and brain space available these days. When I have to learn something I do...I haven't 'had' to learn Linux command line stuff much yet!

I think to properly make use of this the Mimas needs an Ethernet port.  Something I was thinking of designing although I may try and cobble something together from a breakout module.  There are lots available to try.

That's all for now - take care - Langster!

Thursday, 9 June 2016

Designing a pressure sensor using Velostat

In the previous post I designed a circuit which was supposed to read in when pressure was applied to a custom sensor made from velostat.

The first post on the Piano conversion

I made a sensor out of some single sided FR4 printed circuit board material, some foam tape, two pieces of wire, a small 1 cm x 1 cm piece of velostat and some sticky tape!

Custom Pressure Sensor using Velostat
This is just a prototype and may not be my final version of the sensor. I wanted to see how well velostat worked and how it would behave. It seems to work really well!

I found from measurements with my multimeter that when the pressure sensor is not touched the resistance across the wires is 30 kΩ. When pressure is applied it drops to 1 kΩ. That should be more than good enough for the purposes of detecting a key-press!

The constructed pressure sensor
Next the PCB designed in the previous post was etched, drilled and populated. It etched well and I populated it with the designed components:

The Underside of the PCB 
The topside of the PCB with components

I then wrote some quick test code for the arduino because I'm leaning towards using an arduino for the microcontroller:

Pressure Sensor test Code
For Electronic Piano
(c) A. Lang 2016

// These constants won't change.  They're used to give names
// to the pins used:
const int analogInPin = A0;  // Pressure Sensor connected to A0

int sensorValue = 0;        // value read from the pressure sensor via the amplifier stage
float outputValue = 0;      // value output to the Serial port

void setup() {
  // initialize serial communications at 9600 bps:

void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);            

  // print the results to the serial monitor:
  Serial.print("sensor = " );                       
  // wait 10 milliseconds before the next loop
  // for the analog-to-digital converter to settle
  // after the last reading:
The code is very similar to code I had written before - what is it with me and pressure sensors at the moment! I then uploaded the code to the arduino and tested it - It didn't work as planned - I may have been a little disappointed at this point....

I then thought about my circuit and looked at the schematic:

The original Key Press schematic

I realised I had made a mistake. I didn't account for how the velostat would behave in terms of it's resistance. I thought it would have a resistance of around 1 kΩ and doesn't it's resistance is 
30 kΩ and varies down from that when pressure is applied. Because of this I need to tweak my circuit from behaving as a two stage buffer to a simple analogue comparator and buffer. Luckily it won't be too hard to change things!

Here is the new circuit:

Add caption
The Key Press Schematic Version 2 

The new circuits works in a similar fashion as the previous one. The velostat pressure sensor makes up a voltage divider. The output of the voltage divider is connected to an analogue comparator made with the first op-amp in an LM358 dual op-amp IC. The negative input has a 2.75 V reference set by the 8.2 kΩ resistor and the 10 kΩ resistor. The output of the 1st op-amp is then connected to a buffer amplifier with a gain of two and then the output is connected to a FET and an LED. The output will be sent to the ADC of the micro-controller which will probably be an Arduino.

To test the circuit I removed a 10 kΩ resistor and then added a 7.5 kΩ resistor (because I couldn't find an 8.2 kΩ resistor). Here is a photo of the modification:

Here is the modified PCB layout although I probably won't etch this board again. I'm going to re-design it to use surface mount components and be a smaller form factor. It would be nice if each board fit snugly under each piano key.

The New Key Press Layout
I then connected the circuit back up to the arduino and pressed the sensor! It worked. The LED lit up - although I wish I had used a brighter LED...but SUCCESS!! So sweet...

Here is a graph I made from the serial monitor results. It looks very similar to the simulated oscilloscope trace from the first post!
The results from the serial monitor
So now we have a valid method of reading key presses we need to scale things up - and shrink a few things down. I will redesign the key press PCB layout to use surface mount components to take up as little room as possible. Then we need to look at multiplexing all of the signals together...and for that I'm going to use the 74HC4076 integrated circuit breakout board.

That's all for now people - take care!