Skip navigation

Sorry For the delay in uploading, been focusing on exams.

Two Weeks ago we presented the final build of our project

The presentation went well, with only one hiccup; my cheap windows tablet not working, but that was easily fixed by using one of our laptops.


The system worked as it was supposed to, the only error which we couldn't fix in time was the label showing text on the vending form disappearing after completing a cycle. I wasn't able to get a video of the system working without the cover on, but i got one of the system dispensing all the snacks during testing and one of the sorting process


And one part of the FPGA Design which i was happy with, even though no one on my team, or in the workshop when I got it working,


I would like to take the time to thank everyone for their positive comments and suggestions throughout the course of this project.

Its been a while since i uploaded a post about the Systems Project, so sorry if this is a bit longer than normal.


We currently have nine days until the build need finished for display at the presentation. So we are all trying to get this done quickly as we also have our exams coming up in two weeks time.



The main design consists of two towers to hold the blocks. Each tower can hold about 10 blocks. 


For Sorting the blocks into the towers we have a small platform which rotates 45 degrees either direction to dispense a block into a tower. The color sensor will be mounted on one side of the inside of the towers to. The sorting works when the PC sends a 'G' command, The Mbed reads the color sensor and sorts it into a tower which is not full, and sends the servo command to the FPGA to move the servo.

To dispense the Blocks from the bottom of the towers we use a kicker mechanism which is driven by a servo with a 2:1 gear ratio, this will give us about 75mm of movement on the kicker which will be enough to move the blocks into either the Recycle bin or the Dispense bin.


The card reader uses four Sharp IS471S to read the Value of the Card reader and return it to the Visual C# and store the value within the MBed.


The Digital design has been completed, and some modifications have been made to the original servo driver, as originally it was only able to move the servo 90 degrees. I will post an updated version of my Verilog PWM post latter. The FPGA has been flashed so as we do not need someone with the Quartus Software to be program the device every time before we use it. The FPGA has three modes, Sort, Run, Servo Direct Drive. We wait for one of two commands to enter the Run or Sort modes, if it is not that command it is passed directly to Servo Direct Drive.


In the Run mode the FPGA is waiting on one of about 10 commands which will control the two bottom servos in a predetermined manner.

     ie; Tower 2 Dispense, Tower 1 Recycle

it will remain in the run mode until it receives an end run command and returns to idle waiting for command


In the Sort Mode the FPGA will wait for commands for controlling the Top servo position

     ie; Tower 1, Tower 2

it will remain in the Sort mode until it receives an end run command and returns to idle waiting for command.


Since the Verilog was fully functional, i thought i would add something to make the board look more interesting; and with having several LEDs being unused. It was obvious what to do, Knight Rider Lights;



Ive also wired up the four seven segment displays on the board to show which mode we are in. The green LEDs to the right show the current Serial Data Received.



We have also managed to complete the Maintenance mode software and have published it to allow us to all have a copy on our laptops. There are still some small issues with the software, but the majority work and I am relaying on the rest of the team to report back any issues the find with the software.


The only other modifications that need made to the Main software for running on the device is minor modifications to the layout to allow it to go full screen on the tablet without looking stretched out.

There is one more issue that arises during the development of the software. The second language we are using is Spanish, and we tell the customer what color they are allergic to, So think what the Spanish word for black is and say it with an american accent (the current speech language on my pcs). I have tried installing Spanish language packs, yet no luck; if i cannot fix it we may end up changing the language to avoid any misunderstanding.

This Weeks Deliverable is to drive the servos connected to the FPGA from the PC, In normal operation, this would be done with the Mbed in the middle. ALthough for getting it up and running I have modified our Maintenance Software to output Hex Values for the FPGA to Read.


Apologies for the poor quality Video



The main bulk of the verilog source, attached, has already been written. The Servo driver was completed for an assignment several weeks ago. The UART receiver has come from  and works well for this application.

The Serial Command the FPGA takes is a 8-bit hex value, the first nibble (4-bits) is the Servo Number and the second nibble is the Servo Position. The led_data is just to drive the onboard leds with the data received.


          led_data = rx_data;

          sv_no = rx_data[7:4];
          sv_pos = rx_data[3:0];

always@(posedge clk)
     4'b0001: SV1_pos = {sv_pos, 4'b0000};
     4'b0010: SV2_pos = {sv_pos, 4'b0000};
     4'b0011: SV3_pos = {sv_pos, 4'b0000};
          SV1_pos = 8'd255;
          SV2_pos = 8'd255;
          SV3_pos = 8'd255;
          SV1_pos = 8'd0;
          SV2_pos = 8'd0;
          SV3_pos = 8'd0;


The Module outputs high for one clock period when there is new data, when this happens it cuts the data in half to get the two nibbles of data. Then on each clock pulse the second always block decodes the commands and sets the servo pulse width. To allow the pulse width to be described as 4-bits instead of 8-bits, four zeros are added onto the end of the data.


The Case statement also allow for setting all to their maximum and minimum with the hex values 0xFF and 0x00 respectively, although it doesn't look at the second nibble it will be best practice to have it the same as the first.


I've spent most of today getting this to work, and am so happy for it. There was one moment when I became incredibly confused, I was using Termite to control the FPGA and I could not figure out why no matter what values i sending that i was getting the same value 0x0A. It wasn't until I looked into Termite's setting and realised that it was appending LF, whose ASCII Value is 0x0A.


This did give me an idea, and once i had connected a second servo to the FPGA to test, I tried sending 0x1F2F; and both servos moved to maximum at the same time. I have no idea why it is working like that, but I am not complaining, as it means that from the terminal we can control multiple servos at once. We will be sitting down at some point tomorrow to get the Mbed software converting the more readable commands to hex commands for the FPGA.


by more readable i mean, the command sent to the Mbed are in the form



One more bit to add,as it just scare the life out of me. If the FPGA is left alone for a while with no commands being sent. It acts as though it received the all go command. I suspect this has something to do with the UART module; and should probably look into it.

I thought I would share this project that I have been working on for about six years, on and off. It is a controller for four aspect model railway signalling.

Image result for 4 aspect signallingFunctionality of four aspect signals


When most people drive these signals on a layout, the will use a rotary switch to change the signal, but when you have a layout with multiple of these signals, the control board becomes very cumber sum and hard to maintain.


When I first designed the controller I designed it for use on a Picaxe MCU, as at the time the only MCU I had looked into. The basic Functionality of the system was to take tow inputs, a binary number and to then drive the LED's on the signal, as the majority of manufactures of the model signals use 3mm leds with a common cathode, this requires four outputs. The driver for the LED's would also include a small RC Circuit to have them fade as a incandescent bulb would.


Signal Output
Pin Output
00Green (Go)0010
01Yellow (Next Block Red)0100
10Double Yellow (Red Two Blocks Away)0101
11Red (Stop)1000


The second design, again on the picaxe had more complex functionality, in an attempt to make the system more autonomous. It included functionality for a TOTI (Train on Track Indicator) which would set the signal to Red, and the ability to chain the systems together, bu adding one onto the input and passing it out.Along with the functionality to include a feather, which is used to indicate which way a point is going, and a second input which it would use when the track was switched. I use input as the system is moving in the opposite direction to the train.

Image result for 4 aspect signalling


The second design came rather far, but i wanted to focus on a more generic system which would be near fully automated. and so i designed it using logic gates (sorry as don't have an image of the Logic). I then started thinking about making the design more user accessible, ie making a kit, posting PCB layouts and schematics. So i am now looking at what would be the best way for me to implement this design so that I can share the whole System.


My main Goal for doing this would be small form factor (I working in 4mm:1ft scale and the signals are small), low cost, ease of self assembly and although not necessary low power consumption.

The other options i would like to be able to add; are a control board, basically a mimic layout device (a device with a sketch of the layout on it) to change the signal to Red, or even other states,


Having thought about how to implement it I have considered a couple of options;

1. Generic Logic Gates

2. Field Programmable Gate Array, or other programmable logic device

3. Arduino programmable Micro controller

4. Micro controller, such as pic or avr.


I would like to hear any suggestions or advice the community have on how i should implement the system, and hopefully i may be able to share files about it with you when it is finished.

After this mornings Team Meeting we agreed that i could put up some pictures of the goings on within the group.

The prototype for the mechanical design has been decided on and construction of the prototype has begun. Apologize for not having any pictures of the actual prototype, just the sketch.

The main idea of the prototype consist of two towers which will hold the blocks. At the top there is a platform where the colour of the blocks will be determined. then deposited into one of the towers, the colour will then be stored into an array for use in dispensing.


The towers will dispense into one of two bins, one for recycling, and one for collecting by the customer. The will be dispensed using a arm attached to a servo.


At the moment, that is all i know regarding the mechanical build.

    • Code numberAllergy (colour)
      0000No allergy


For the Project we need to be able to read a card code determine the Allergen of the person. To read the bar code we are going to use a Sharp IS471F Light detector which has circuitry built in to operate the infrared led and process whether the light is on or off. So just connect the IR Led up and its ready to go.


The challenge for designing this, is that we only want to use the one chip to read the card, and that the card will be swiped through. Think of a magnetic card reader, that how we want it to operate. The main design issue will be that customers can swipe their cards at various rates and this will give various pulse width for the output


Above the image on the right is a slow pass with the card, the right is a quick pass with the card. Card value was 1111, as a test.

At the moment I am prototyping with an arduino uno, but the final build will need to be embedded on the MBed. Since i am not sure what will convert easily from Arduino to C++, I need to try and program the arduino as basically as possible (if that makes sense).


My first thought was to use the pulse width of the high pulse (when there is a cut) compared to the Low Pulse. This would appear to work for a couple which i have tested with., at least for the single bit values.

0001 Card Slow Pass

If i measure the Low pulse at the start, it is ~272ms and the first high pulse is ~20ms. Dividing them, is ~14 since we have double the slots, let me quickly explain. As the card uses 5mm spacing between the slots and the slots are also 5mm wide we have eight slots in total, but only four carry data. Therefore we have twice the number slots. Not the best description, sorry.


So taking the 14 and dividing it by two, we have 7. So seven empty slots before the high. So therefore the 8th bit is High, again divided by two, the forth bit is high. producing 0001, or Red.


I am going to be testing out this  with more cards and trying to adapt it to multi bit cards, then implementing it onto my arduino for testing outputting the card code data via the serial terminal.

As part of the project we need to have a visual c# program read a sensor connected to the MBed. The sensor we decided to use was the Adafruit TCS34725 Colour Sensor, as we already have the colour sensor working on the mbed all we needed to do was to set up the program to read the serial in line and respond to the command sent from the c# application when it wants to receive the data.


The basic c++ source for the MBed looks like this;

#include "mbed.h"

Serial pc(USBTX, USBRX);

int main() {
    while(1) {
        if (pc.readable()){
                char Data_in = pc.getc();
                    case 'R' : /*Do Something*/ break;


using the case statement to decode the input allows us to add more functionality to the source if we want to read other sensors, we will just create more functions to read the sensor and return the values in a way for us to decode them in the c# application. The Data returned from the MBed is in the form [Red<space>Green<space>Blue<space>Clear<newline>].


The application is simple;

and the source for reading the sensor, when "Read Senor" button is clicked;

private void BTN_Read_Click(object sender, EventArgs e)
            string Data_In = null;
                Data_In = serial.ReadLine();
            catch (TimeoutException)
                MessageBox.Show("ERROR: Timeout");
            catch (InvalidOperationException)
                MessageBox.Show("ERROR: Open Serial Port");
            string[] in_Data = Data_In.Split(' ');

            int W_col = int.Parse(in_Data[3]);
            float R_col = (float.Parse(in_Data[0]) * 255) / W_col;
            float G_col = (float.Parse(in_Data[1]) * 255) / W_col;
            float B_col = (float.Parse(in_Data[2]) * 255) / W_col;

            LBL_Red.Text = in_Data[0];
            LBL_Green.Text = in_Data[1];
            LBL_Blue.Text = in_Data[2];
            LBL_Clear.Text = in_Data[3];

            int R = (int)R_col;
            int G = (int)G_col;
            int B = (int)B_col;

            LBL_Col_red.Text = R.ToString();
            LBL_Col_Green.Text = G.ToString();
            LBL_Col_Blue.Text = B.ToString();

            Color sample_Colour = new Color();
            sample_Colour = Color.FromArgb(R, G, B);
            TXT_Colour.BackColor = sample_Colour;


in the try catch block we attempt to send the command to the MBed, two catch exceptions were added; the first is for the COM port read timeout, the second for if the COM Port is closed.

The line

string[] in_Data = Data_In.Split(" ");

is used to take the input and split it into an array, using the <space> in between the values. The data in the array can then be manipulated.


The labels in the Returned group box will be updated with the raw value from the serial data.

To make the application a little more interesting a textbox is updated with the colour from the sensor. As the  max value of the sensor is 2^16 (65,536) and the FromARGB method only takes a byte (255) as an input we need to multiply the data by 255 and divide by the clear value.


FromARGB then produces a new colour object which we set to the backcolor property of the text box.

and the result is


The colours seam to be a tad off, think it will probably be due to fluctuations in the sensor. Might be worth while averaging the sensor reading and returning the average, but for now i think it's close enough to complete this week's deliverable.

Some fun news first, We now have a logo for the "Company" (as this is a mock project, its a mock company). We are Called Alpha Vending Solutions


I have just managed to get working the Maintenance mode Software using visual c#. The fix to get the serial port object to work was annoyingly simple once I found it.

The main use of this software will be to test functionality of the system, Send servo commands, read sensors and such. As we still are not fully sure on what software we will need, it has been made as a MDI (Multiple Document Interface) to allow more forms and controls to be added as needed.

The fix i found for getting the serial ports to work over multiple forms was to pass the Serial Port which has been opened in the main form to the other forms as an argument, see bellow

On the Form to be opened


using System.IO.Ports;
SerialPort serial = new SerialPort();
public Servo(SerialPort port)
            serial = port;

On the Main Form

using System.IO.Ports;
SerialPort sp = new SerialPort();
private void servoToolStripMenuItem_Click(object sender, EventArgs e)
            Servo SVR = new Servo(sp)
                MdiParent = this



So in the main form 'sp' is opened with the required com port, using the menu. Then it is passed to the other forms when they are opened, and set to another serial port object. So far this solution is working for me and i hope to keep it that way.


The only issue I can see being with this, is that it requires me to use the readline() and Writeline() method in every form and have the required exception handling every time. although after the trouble I had trying to get this to work in the first place, i really don't mind having the extra work. I could also see an error happening if you open the form before opening the Com port.


This afternoon we will be interfacing the MBed with the software to read the colour sensor and display the results, and i will be sitting down with the mechanical design team to work out the state machine i will need to implement on the FPGA. Ill try and post about them as well

For the Digital Design (FPGA) aspect of the project we need the system to take inputs from the Mbed. Mostly it will be controlling Servos in a finite state machine, but when the system is in maintenance mode it needs to control the servos individually. This has lead me to come up with  a quick block diagram of how the system should operate.


It will take the inputs via UART, the commands are then decoded (not shown) and sent to the relevant module. Both modules will output the to the same servo modules. This means that a buffer will probably be implemented on the maintenance mode outputs to force them high impedance during FSM operation. I am lucky in the fact that the FPGA board which we are provided with already has a UART Module on it, so I will not need to worry about writing one in verilog, i will just need to write the decoder.



As for the servos Drivers they are complete and have been tested via an oscilloscope. I would have tested with a servo attached, but it would appear that the IO Buffers on the board are busted and so the max output voltage is currently 66mV and i will be talking to the lab technician about fixing/ replacing it. This is why the Signals bellow are so noisy, just due to a cheap scope and low voltages ( i am hopping)


the images are not as clear as i would like and the software for my scope did not include the measurements of the period, and pulse width.

to Summarize the images, the first is a zero input to the servo module, which is producing a pulse width of approx 1ms.

the second is 255(Max) sent to the servo module, and is producing a pulse approx 2ms wide. So it works, apart from the low voltage, What i will probably try is an IO Port on a different buffer see if that fixes the issue. If you are interested in The Verilog Servo MOdule i have a write up here Verilog PWM

Just a quick update on the project. The initial mechanical design has been completed by my team members, and once they explain it to me; I can explain it here. As right now their scribbles make no sense to me.


A couple members of the team are beginning to work on reading sensor data via the MBed, and failing miserably. I am starting to notice a pattern in the source code examples our lecture is giving up, they are (for lack of a better work) crap. If you don't know what i am refering to check my previous blog post on the Verilog PWM assignment we had to to for the course here Verilog PWM.


Since the MBEd will just be a passthrough for serial command, I decided that i will do the maintenance mode software; using C#. As once the main bulk of the FPGA Design is completed, I will just need to wait on mechanical design being completed before I can design the state machine to operate the system.


The main idea is to have the main form as an MDI, Multiple Document Interface, as you see some DEvelopment environments. This gives us the opportunity to just design more forms and add functionality as we need it. Just one big problem, it would seam that C# and Serial Ports hate me just now. I have tried using the example code given to me by my lecturer, but it doesn't do what I am looking for. I have looked online and when i try to duplicate, it does nothing.


Let me explain a little;

as I am using a MDI which means that several forms will be either sending serial data out, or receiving it. I am looking to set up a public function in the main form which watches the serial port and then returns the value. This way any other form can call the function to watch the serial port, without having to set it up in every form. yet no matter how i try to do this it either throws a runtime error at me, or just does nothing. I am testing it by having two FTDI chips connected to each other and to my computer(and before anyone asks, my connections are working and have checked them using a serial terminal).


If anyone has any ideas on how i can accomplish this, or know someone that does; please help. I'm running out of hair to pull out.

Im currently studying my third year Electrical and Electronics Engineering at Heriot Watt University. This semester we have a Project to complete as part of a team of fellow EEE students and Computing Students, and i though i would let the community know about it.


The majority of the project is technical, but we also have to look at it from a project management aspect, i will leave out the project management side to be nice. I will mostly be doing the digital design aspect of the project, but will most likely be helping out with the other aspects of the project, i will try and upload as frequently as i can. I will welcome any comments, or suggestions which you have.


Here is the specification that we were given

Project Background

Sensing is key to many autonomous systems and this project will be making extensive use of a variety of sensors to develop a system that can operate with a level of autonomy

Design ability is one of the key objectives of the engineering process. A successful design requires the application of a combination of creativity, skill, and the ability to analyse and synthesise.

The purpose of this design project is to provide an opportunity for these abilities, which you have begun to acquire in the first, second and third years of the course, to be exercised in conditions similar to those under which engineers work in industry.

Many industrial products and processes use a combination of computing, and embedded software and digital technologies applied to some physical system, the design project contains elements of each. This project is structured to give you experience of designing across artificial disciplinary boundaries, its successful completion requires you to exercise system integration skills.


Snack-O-Mat is a newly formed company to produce intelligent solutions for sensor based snack systems. Their business model is to manage the design, delivery and maintenance of the automated equipment for a robotic supply system. However, they outsource the technical development of the equipment to 3rd party electro-mechanical design companies.

Their first project is with a company that runs a snack supply system that reads a card to indicate known allergies and automatically dispenses the required number of snacks to a user. They have specified the need for an automated analysis system to sort out the snacks which contain particular allergens.The analysis will be done (in a similar what to spectroscopy) by looking and the different colours present in the presented sample.

The company has contracted Snack-O-mat to design and deliver an automated system that will work in conjunction with the user to supply the required snacks.

A set of companies have been asked to bid for the contract by building and demonstrating a proof-of-concept unit. The final decision on which company gets the contract will be based on a public competition to be run in December 2017. At this event, each machine will be demonstrated and supported by the submission of a suitable technical document.


    • 1. Design and build a small system that reads a user's card indicating what allergies the user has and gets an input from the user indicating how many snacks they require. The system reads the colours on the snacks to defines which allergens they contain. Then the allergen free snacks are to be dispensed. The system must ensure that the user is present whilst using the analysis system, but they must be at least 10cm from the machine. Upon analysis the required set of snacks should be dispensed automatically to the user.
    • 2. The system should indicate if it was unable to fulfill the required action, i.e. if it does not have an adequate supply of snacks or there is some other issue
    • 3. Once started, the machine is to run without operator intervention. It should however, interact with the user through the PC interface and any appropriate LED indicators to show the user what is happening, whilst ensuring the user remains present, but is not too close.
    • 4. A connected PC will allow initial setup of working parameters and show progress of the machine
    • 5. The system should have TWO distinct MODES.
      1. • Operate mode
      2. • Maintenance mode
    • 6. Operate mode is the normal mode with the machine selecting blocks of a specific size and checking the colour of the selected snacks.

    • 7. The maintenance mode allows an engineer to test and diagnose any machine problems.

    • 8. A PC computer will provide the following
      1. • Operate mode
        1. • Monitor progress and display appropriate data on screen
        2. • Maintain simple database of snacks that have been analyzed and those needing reprocessed.
        3. • Tell the operator, through a speech facility, what the machine is doing. This facility to be switchable between English and another language (e.g. French, Chinese, etc.)
        4. • Show result of the snacks that have been analyzed for allergens and the appropriate snacks dispensed.
      2. • Maintenance mode
        1. • Provide a facility to test the different aspects of the machine for maintenance purposes.
        2. • Move servo motors
        3. • Read sensors
        4. • Provide suitable GUI interface to run the maintenance commands
    • 8. The Altera Cyclone FPGA system
      1. • Operate mode
        1. • Once a GO signal has been received, the FPGA unit will control all aspects of the actual snack sorting process
        2. • Show some simple information on the FPGA board displays
      2. • Maintenance mode
        1. • Receive commands from the MBED unit
        2. • Send command to FPGA
        3. • Move servos and motors
    • 9. MBED unit
      1. • Operate mode
        1. • Communicate with the PC
          1. • Generate “go” command to FPGA
          2. • Read monitoring sensors and send to PC
      2. • Maintenance
        1. • Communicate with the PC
          1. • Read commands from the PC
          2. • Execute these commands and return data to the PC
          3. • Read sensors and return data to the PC
    • 10. A card will identify the users' allergies. The user will then enter into the system the number of snacks required. The snacks will not be loaded into the system already sorted for allergens, but they will be stored together. The system will test each snack for allergens. The dispenser will indicate if it is unable to fulfill the required action, i.e. there when it runs out of suitable snacks in the machine. The user card will be the size of a credit card with FOUR notch areas, which can be filled, or cut-out. This would give 16 possible combinations.
    • Code numberAllergy (colour)
      0000No allergy

    1. Insertion of the card will prompt a set of activities
      1. • Read card code
      2. • Check code against central data file and indicate any allergy issues.
      3. • Request entry of the number of snacks required
      4. • Check that machine can satisfy order
      5. • Indicate problem if machine has insufficient snacks
      6. • Dispense snacks if all is OK.
      7. • Prompt for user to collect snacks and card
  • 11. Sorter to fit onto a 300mm by 300 mm baseboard. Height to be less that 500mm.
  • 12. Teams may add additional features after agreement with the project manager.
Duncan Fraser

Hantek 6022BL

Posted by Duncan Fraser Oct 6, 2017

So I ordered myself a Hantek 6022BL this week, as I have wanted an oscilloscope since i started tinkering with electronics. Since I am a student though, a couple hundred pounds is a lot of drinking money to spend on one item, especially since knowing myself I would most likely blow it up at some point as I don't have much experience with them. Not going to be a full review, just my first reaction upon playing with it this evening.


I was watching Dave Jones (EEVBlog) video on starting an electronics lab on the cheap, and he mention this one, although he did go on to say to get the other one as it has USB Isolation. So for £65 off amazon i thought why not, the specifications seem fair enough for the type of hobby electronics I do.

2 Channels , 20Mhz Bandwidth, 48MSa/s sample rate and a 1M memory depth, along with a 16 channel logic analyser.


The first thing that surprised me was how solid everything felt, Aluminum case, descent feeling probes.

the one part i did not like about the case was the rubber feet that surround the case. Having them in place make it annoying to attach CH1 bnc and trying to get to the pulse out pins, they are a bit difficult to remove and try to take the labels with them as well. The only other thing i can see annoying me when using this is the ribbon cables and connectors for the logic analyser. As they just use normal headers to attach the clips to the ribbon cable, they feel rather flimsy and I will probably take the effort in the future to make these a more solid connection.


It was really easy to set up. Install the current software from hantek website, install the drivers (download from website) and it's ready to go. Adjusting the compensation the probes was easy enough when reading through the manual.

So far the Software is easy enough to use and get to grips with. I haven't looked through the software much more than fiddling with a couple of the controls.


I think that this oscilloscope will be great for me to grasp the basics of using oscilloscopes and for the price i payed I am not bothered if it doesn't last a lifetime or if it is sometimes off in measuring; but i think i would recommend it as such to anyone looking into getting their first oscilloscope.

Duncan Fraser

Verilog PWM

Posted by Duncan Fraser Oct 5, 2017

For an Assignment for university my class had to write a verilog program to produce a PWM output derived from the ASCII Value of our initials which can drive a servo.

We were provided a sample verilog source from fpgas for fun, which was clear as mud, but did produce the required output. All examples a could find online where for a simpler PWM output, ie with a period the same size as the largest value of the pulse. Which is more suited for constructing a analog output.


So I have gone through the source provided and found what i considered an acceptable explanation, from which I taught a several of my classmates who where struggling. I though I would put it up here for everyone to see, I hope it is of some use to someone. And apologies for poorly drawn graphs.


For producing a Servo signal we need pulses between 1ms and 2ms with a frequency of between 50Hz - 100Hz


As we want to module to accept a 8-bit number to determine the pulse width, in the case of my assignment an ASCII Character, we need to divide the variation by the number of steps you can have in a 8-bit value.


1ms/256 steps = 3.9us per step


Therefore we need to generate a clock with period 3.9us from which we will work from to produce the outputs.

For this we take the frequency of the input clock, in this case 50MHz, multiply it by the time variation and divide by the number of steps in that variation.


(50e^(6) x 1e^(-3))/256 ~= 195


This is the value we will use to generate a saw tooth wave which will allow us to generate the clock of period 3.9us

A counter will be incremented on each 50MHZ clock edge, when this counter reaches 195; we generate a pulse on clkTick and reset the counter. This looping is what will generate the 3.9us clock



To generate the period between the pulses we will use a second saw tooth counter which will use the 3.9us clock to increment it.

To calculate the size of this counter we need to use the desired period of the output


log2(output period/clock period) = log2(16ms/3.9us) = log2(4109) ~= 12-bits


16ms was used as it gives a value closest to a whole bit. This counter will be incremented every 3.9us clock pulse so we have approximately 16ms between pulses, and will be allowed to roll over to zero when it maximum value is reached.


To generate the output pulse into we first need to take the input 8-bit and add a 4-bit binary 1 onto the front, this is done using condensation operator (can't remember actual name)


     {4'b0001, Input}

this produces a 12-bit output with a minimum value of 256 and max of  511, which when multiplied by 3.9us give us 1ms and 2ms respectively. To do this in the code, we set the output high when this number is less than the current value of the 12-bit counter.

So by giving the input a value between 0 and 255 we can produce servo pulses between 1ms and 2ms with and variation of 3.9us.


I have included below my verilog source for my assignment, which includes some extra case statements for changing between upper and lower case, and for counting the output pulse to change the value after two. I will also add the original source from fpga for fun, and you will see what i mean by mud, no disrespect to the author.


I hope someone find this useful, or just interesting, please let me know your thought in the comments