Johan’s Applied Math projects

Projects that I built by myself

For these project, I conducted the research and development at home. As always, my father supervised the project and helped me with architecture and code reviews to keep it readable and maintainable. He also provided suggestions to organize the code
to make modules reusable and testable.

derived work
Building Math Hardware
This article shows some implementation of the math operations introduced in chapter 7 of the inquiry “How do computers do Math?” The combinational logic is described in the HDL Verilog 2001. «not public yet»

Johan’s Theoretical Math

I love math. Math proves the theorems about sciences such as physics and helps solve difficult problems. I envision problems in mathematical terms, and like to talk about it until I fall asleep. I love learning about math, because it is intuitive and forms the basis for many of my favorite sciences.


AMC 10/12

Learning at home

I jumped ahead of the school curriculum, and spent much of the summer with my dad and learned about applications of calculus.

Euler’s Formula
Proof of Euler’s formula, identify and relation to trigonometry. «read more»
Laplace Transforms
Proof of Laplace transforms as used in my Electronics article «read more»
own work
Laplace in Mechanical Systems
Using Laplace transforms to solve mechanical ordinary differential equations «read more»
own work
Introduces the formulas for Capacitor and Inductor impedance. «read more»
Evaluating Transfer Functions.
Evaluating transfer functions with impulse, unit step and sinusoidal input signals «read more»
own work
RC Low-pass Filter
Low-pass filters remove high frequency components from a signal. A single-pole passive RC filter consists of a resistor and capacitor in series. «read more»
own work
RLC Low-pass Filter
Filters can remove low and/or high frequencies from an electronic signal. They can be used to suppress unwanted frequencies such as background noise. This article shows the math and visualizes the poles in the
s-place, examines and visualizes the the step and frequency response. «read more»
own work
RLC Resonator
RLC circuits are resonant circuits, as the energy in the system “resonates” between the inductor and capacitor. We will examine the properties of a resonator consisting of series circuit of an inductor (L), capacitor
(C) and resistor (R), where the output is taken across the resistor. «read more»

Johan’s Art


This is a zoomable Mandelbrot sequence using Node JS. Zoom in on an interesting area by dragging your cursor and go back to the previous view by pressing the “space” key. The program uses imaginary numbers to generate the sequence. These numbers have separate real and imaginary pieces. The different coordinates in the Mandelbrot set must pass a test. The set is white and the rest is another color. 

My code for this project is at or at

Getting started with FPGA design using Altera Quartus Prime 16.1

A (relatively) short introduction to compiling, simulating and uploading using the Altera Quartus development environment for the Terasic Altera Cyclone IV DE0-Nano under Windows 10. An equivalent tutorial is available for the reader who prefers Xilinx based boards.

Install the FPGA Design Suite

Start by installing the free Quartus Prime Lite, this includes the IDE and required tool chain to create configuration files for the Altera FPGA.

  1. Install Quartus Prime Lite 16.1
    • download the Quartus Prime Lite Edition from
    • include device support for Cyclone IV and ModelSim-Altera Starter Edition.
    • run QuartusLiteSetup-, install to a path without spaces in the name (e.g. C:\intelFPGA_lite\16.1)
    • authorize USB JTAG Blaster II driver installation
  2. Run the Quartus Prime 16.1 Device Installer
    • install Cyclone IV and ModelSim-Altera Starter support

The USB JTAG driver needs some finishing up

  1. Use a USB cable to connect your computer to the NE0-Nano board
  2. Go in Window’s Device Manager
    • Right-click Other devices » USB-Blaster » Update Driver Software
    • Browse my computer for driver software at C:\intelFPGA_lite\16.1

Install Board Support for DE0-Nano

The Teraasic board support for DE0-Nano includes examples, user manual and the Terasic System Builder tool.

Download DE0-Nano CD-ROM from

  • unzip to a directory of your liking (e.g. C:\altera_lite\DE0-Nano)

Note that its Control Panel fails with Load DLL (TERASIC_JTAG_DRIVE.dll) under 64-bit Windows. No biggie, we do not need it.

Before you start

The simulator doesn’t play well with UNC paths (e.g. network shares). It triggers numerous errors and may cause timing simulations to disregard delays. Keeping the files on the server is fine, for as long as you access them through a symbolic link. To create a symbolic link, change to your home directory (cd %USERPROFILE%) and create a symbolic link to your file server (mklink /d symlink \\server\service\path).

If you add the symbolic link to Explorer’s Quick Access, it will resolve the link first. To work around this, first create a regular directory and add that to the Quick Access. Then replace that directory with the symbolic link.

A few last tip before you take off:

Stay clear of absolute path names. Not only do they cause havoc when moving a project to a new directory, but they also confuse the simulator. If the ellipsis () file selector returns an absolute path, simply edit it to make the file relative to the project directory. E.g. change \C:\Users\you\path\project.v to project.v. If you want to quickly change all absolute paths, I suggest closing Quartus and pulling .qsf into an text editor (e.g. emacs).

Lastly, store the files on a local drive. It makes the process of compiling much faster.

Build a circuit

Terasic advises to start with their System Builder to reduce the risk of damaging the board by incorrect I/O settings. I will throw this caution to the wind and use an example Quartus Setting file instead

Start Quartus Prime and create a new project

  • File » New Project Wizard
    • Choose a working directory (.c:\users\you\whatever\example1); project name = example1
    • Project type = Empty Project
    • do not add files
    • Family = Cyclone IV E; name filter = EP4CE22F17C6; click the only device that matches
    • Finish, accepting the default EDA Tools Settings

Start with a Verilog HDL module that tests if inputs are equal (File » New » Design file > Verilog HDL, and later save it as eq1.v)

`timescale 1ns / 1ps
module eq1( input i0, input i1, output eq ); 
    wire p0, p1; // internal signal declaration
    assign eq = p0 | p1; 
    assign p0 = ~i0 & ~i1;
    assign p1 = i0 & i1; 

Add a Verilog HDL module (File » New » Design file > Verilog HDL, and later save it as eq2.v)

`timescale 1ns / 1ps
module eq2( input [1:0] a, input [1:0] b, output aeqb ); 
    wire e0, e1; // internal signal declaration
    eq1 eq_bit0_unit(.i0(a[0]), .i1(b[0]), .eq(e0));
    eq1 eq_bit1_unit(.i0(a[1]), .i1(b[1]), .eq(e1));
    assign aeqb = e0 & e1; // a and b are equal if individual bits are equal

For the top level, we will use a schematic. Create a symbol file (eq2.sym) for the eq2 module so we can reference it in the schematic.

  • File » Create/Update » Create Symbol Files for Current File

Create the top level schematic

  • File » New » Design file » Block Diagram/Schematic
  • File » Save as » example1.bdf
  • Make sure that this top-level module has the same name as its source file and is the same name as your project name.
  • Update the block diagram (.bdf)
    • select the block diagram tab
    • place the new symbol
      • double-click the canvas
      • expand the project directory and select the eq2.sym file that we just created
      • place the symbol in the block diagram
    • add inputs
      • double-click the canvas
      • expand the libraries directory and select “primitive » pin » input”
      • place the pin so that it touches input a
      • change the pin name to SWITCH[1..0]
      • copy and paste the input pin, and place it so that it touches input b
      • change the pin name to SWITCH[3..2]
    • add output
      • double-click the canvas
      • expand the libraries directory and select “primitive » pin » output”
      • place it so it touches output aeqb (a equals b)
      • change the pin name to LED[0]
  • Last, but not least: Mark this file as the top-level module
    • Right-click the file name, and select “Set as Top-Level Entry”


  • Processing » Start » Start Analysis & Elaboration

Implementation Constraints

Time to constrain the implementation by specifying the input and output pins along with timing requirements.

External pins assignments

  • Assignments » Pin Planner
    • This will show the five I/O pins
    • Don’t worry about the Fitter Location, it is just whatever the fitter chose last time
    • Double-click the Location field next each of the pin names to add the pin numbers (based on Table 3-2 and 3-3 in the Terasic board’s user manual)
      LED[0] PIN_A15
      SWITCH[3] PIN_M15
      SWITCH[2] PIN_B9
      SWITCH[1] PIN_T8
      SWITCH[0] PIN_M1
    • Change the I/O standard to 3.3V_LVTTL based on the same user manual (change the first one, then copy and paste)

You should end up with something like

Pin assignments

If you plan to branch out, I suggest downloading and importing the settings file (.qsf) with pin assignments from

Timing requirements

For most design you will want to specify timing requirements. For our simple example however we will not do this.

For the record, to request specific timing requirements (default time quest) you would create Synopsys Design Constraints (File » New SCD File) and save it with the same base name as the top level file (e.g. example1.sdc). For our example it just contains some comments as a reminder.

#create_clock -period 20.000 -name CLOCK_50

For more info, refer to Altera’s class Constraining Source Synchronous Interfaces.

Synthesize and upload to FPGA

Before moving ahead, I like to shorten the path names in the Quartus Settings file (.qsf). This prevents problems when you move the project and especially when you have it stored on a file server. As we will see later, the ModelSim simulator doesn’t support UNC path names, but will honor relative paths even when the projects is on a file server.

  • Assignments » Settings
    • Remove the files (.bdf, .v, .sdc)
    • Add the files back in. After selecting each file using the ellipsis () file selector, edit the resulting path name to exclude the path and press Add.
  • Project Navigator
    • Right-click example1.v and choose Set as Top-Level Entry
  • Alternatively, you can close Quartus and pull the .qsf file in a text editor (e.g. Emacs) and shorten the path names (*_FILE) at the end of the file.

Let us move ahead and generate the binary SRAM Object File (.sof). This is the configuration file to be uploaded to the FPGA

  • Click Compile Design in the Tasks window, or press the Play button in the toolbar.
    • The Compilation Report tab shows the result
    • Correct any critical warnings or errors

This would be the moment to do a timing analysis and/or simulation. However, at this point I’m simply too curious to see if it works just out of the box, so let’s give it a shot.

Connect the DE0-Nano board with a USB cable and upload the configuration file to the FPGA SRAM. (Alternately upload to Flash)

  • Quartus Prime Lite » Tools » Programmer (or double-click Program Device in the task list)
    • Click Hardware Setup, and select USB-Blaster [USB-0]
    • Click Add File, and select your SRAM object file (.sof) in the output_files directory
    • Click Start
    • Save as example1.cdf, so it opens with these settings next time
    • Great! We did it, the design is now on the FPGA (until we remove the power)

Give it a spin

With the FPGA configured, time has come to test it

  • Input is through the DIP switches (SWITCH) on the bottom-left of the board.
  • Output is the right LED (LED[0]) located at the top of the board.
  • We expect the LED to be “on” when switch positions 0 and 1 are identical to positions 2 and 3.

If you prefer bigger switches, you can wire up a breadboard to the GPIO-0 connector.

  • VCC3p3 and Ground are available on the 40-pin expansion header at respectively pin 29 and 12 (or 30) as specified in the board manual.
  • welldoneGPIO_00, 01, 02, 03 are on FPGA BGA pins at respectively D3, C3, A2, A3 and on the 40-pin expansion header at respectively pin 2, 4, 5 and 6.
  • Modify the user constraints file accordingly.

Give yourself a pat on the back; you have achieved something new today!

Timing Analysis

With the first hurdle cleared, we are going to take a closer look at the circuit. The first step will analyze the delays in the circuit to determine the conditions under which the circuit operates reliably. We will follow up with a functional and timing simulation.

If you just want to the timing information on the port-to-port path, you can use

  • Task » Reports » Custom Reports » Report Timing
    • From » click ...
      • Collection = get_ports; List; select SWITCH[0] through SWITCH[3]; click ‘>
    • To » click ...
      • Collection = get_ports; List; select LED[0]; click ‘>

To place timing constraints on the port-to-port paths:

  • Tools » TimeQuest Timing Analyzer
    • Tasks » Update Timing Netlist ; double-click
      • Constraints » Set Maximum Delay
      • From » click ...
        • Collection = get_ports; List; select SWITCH[0] through SWITCH[3]; click ‘>
      • To » click ...
        • Collection = get_ports; List; select LED[0]; click ‘>
      • Delay value = 100 ns (more or less random value)
      • Run
    • Constraints » Write SDC File to example1.sdc
    • Task » Reports » Custom Reports » Report Timing
      • no need to specify the path, just click Report Timing
      • this reveals a Data Delay of about 6.7 ns.

If you want Quartus to meet more stringent restrains, you need to specify these and recompile. This will direct Quartus to seek an implementation that meets these constraints. However, in this case we only specified restraints because we’re interested in the values. [TimeQuest User Guide]

Functional Simulation

functionalThe Verilog HDL (.v) instructions are compiled (Analysis and Synthesis) into Register Transfer Logic (RTL) netlists, called Compiler Database Files (.cdb). As the name implies, data is moved through gates and register, typically subject to some clocking condition. A functional simulation tests the circuit at this RTL level. As such it will simulate the functionality, but not the propagation delays.

Altera Quartus ships bundled with their flavor of ModelSim that lets you draw waveforms for the signals going to the module under test. You can then save these waveforms as a file or HDL test bench. For this example we to skip the step of drawing waveforms, and jump straight to using test benches.

Start by creating a test bench (eq2_tb.v) that instantiate module under test and drive its inputs. As before, you should remove the path from the file name (Assignments » Settings » Files).

`timescale 1ns / 100ps
`default_nettype none

module eq2_tb;
  reg [1:0] a;  // inputs
  reg [1:0] b; 
  wire aeqb;  // output
  // Instantiate the Device Under Test (UUT)
  eq2 dut ( .a(a), 
            .aeqb(aeqb) );
  initial begin
    a = 0;  // initialize inputs
    b = 0;
    #100;  // wait 100 ns for global reset to finish (Xilinx only?)
    // stimulus starts here
    a = 2'b00; b = 2'b00; #10 $display("%b", aeqb);
    a = 2'b01; b = 2'b00; #10 $display("%b", aeqb);
    a = 2'b01; b = 2'b11; #10 $display("%b", aeqb);
    a = 2'b10; b = 2'b10; #10 $display("%b", aeqb);
    a = 2'b10; b = 2'b00; #10 $display("%b", aeqb);
    a = 2'b11; b = 2'b11; #10 $display("%b", aeqb);
    a = 2'b11; b = 2'b01; #10 $display("%b", aeqb);
    #200 $stop;

Configure Quartus to create a script that compiles the test bench and modules for ModelSim

  • Assignments » Settings » EDA Tool Settings » Simulation » Compile test bench
    • New
    • Test bench name = Functional test bench
    • Top level module in test bench = eq2_tb
    • File name = eq2_tb.v, eq1.v, eq2.v (name the test bench and all the modules that ModelSim needs to compile). After selecting each file using the ellipsis () file selector, edit the resulting path name to exclude the project path, then press Add.

If things don’t go your way, please check:

  • I strongly suggest putting the test bench in a separate file, when doing timing simulations. This keeps ModelSim from using the .v file instead of the .vo file what causes propagation delays not to show in timing simulations.
  • (sdfcomp-7) Failed to open SDF file “whatever.sdo” in read mode is most likely caused by the files residing on a UNC path. Refer to the quote at the beginning of this article.
  • (sdfcomp-14) Failed to open “modelsim.ini” specified by the MODELSIM environment variable is also most likely caused by the files residing on a UNC path. Refer to the quote at the beginning of this article.
  • When you get error deleting “msim_transcript” permission denied, close ModelSim first before starting it.
  • Errors like Instantiation of ‘cycloneive_io_obuf’ failed. The design unit was not found indicate that the global libraries altera_ver or cycloneive_ver were not included in Assignments » Settings » Libraries.
  • Keep in mind that the Windows filename limit (260) may be exceeded.
  • To prevent Warning: (vsim-WLF-5000) WLF file currently in use: vsim.wlf, quit ModelSim and delete simulation/modelsim/sim.wlf and simulation/modelsim/wlft*.

Compile the circuit to RTL netlists

  • Processing » Start » Start Analysis & Elaboration

Start the simulation

  • Tools » Simulation Tool » RTL Simulation
  • Select signals of interest
    • Objects » select the signals of interest » Add Wave (or the green circle with the + sign)
    • In the text field in the toolbar, change the simulation time from 1 ps to 200 ns and click the run button to the right (or type run 1 us at the command prompt)
    • Undock the Wave Window (icon on the far top right of the window). In case the Wave Window is hidden, use Windows » Wave.
    • Click “zoom full” and observe the simulated waveforms.

You should see something like

own work

If you make a change to either your DUT or your test bench

  • right-click the test bench and select recompile.
  • make sure that you click the Restart button directly to the right of the simulation time window (or simply type restart at the command prompt).

For more information, refer to Quartus II Handbook 3: Verification

Timing Simulation

timingBefore you start a timing simulation, first close ModelSim.

After compiling your circuit into RTL netlists (.cdb), it is fitted to the physical device (.qsf) trying to satisfy resource assignments and constraints. It then attempts to optimize the remaining logic. The Netlist Writer can export this information for ModelSim in the form of Verilog Output Files (.vo), Standard Delay Format Output Files (.sdo) and scripts to prepare ModelSim through compilation and initialization.

For this exercise, we will do a timing simulation for the whole system. With our top-level entry being a schematic (.bdf), we first need to convert this to Verilog HDL

  • Open the schematic
  • File » Create/Update » Create HDL Design File from Current File
    • File type = Verilog HDL
  • Assignments » Settings » Files
    • replace the example1.bdf file with example1.v
  • Make it the top-level module (so much for using a schematic … eh)

Create a system test bench (example1_tb.v). As before, you should remove the path from the file name (Assignments » Settings » Files).

`timescale 1ns / 100ps
`default_nettype none

module example1_tb;
  reg [3:0] SWITCH;  // inputs
  wire LED;          // output
  example1 uut ( .SWITCH(SWITCH), 
                 .LED(LED) );
  initial begin
    SWITCH[3:0] = 2'b0000; // initialize inputs
    #100;  // wait 100 ns for global reset to finish (Xlinx only?)
    // stimulus starts here
    SWITCH[1:0] = 2'b00; SWITCH[3:2] = 2'b00; #10 $display("%b", LED);
    SWITCH[1:0] = 2'b01; SWITCH[3:2] = 2'b00; #10 $display("%b", LED);
    SWITCH[1:0] = 2'b01; SWITCH[3:2] = 2'b11; #10 $display("%b", LED);
    SWITCH[1:0] = 2'b10; SWITCH[3:2] = 2'b10; #10 $display("%b", LED);
    SWITCH[1:0] = 2'b10; SWITCH[3:2] = 2'b00; #10 $display("%b", LED);
    SWITCH[1:0] = 2'b11; SWITCH[3:2] = 2'b11; #10 $display("%b", LED);
    SWITCH[1:0] = 2'b11; SWITCH[3:2] = 2'b01; #10 $display("%b", LED);
    #200 $stop;

Create the verilog output files

  • Processing » Start » Start EDA Netlist Writer

Configure Quartus to create a script that compiles the test bench and modules for ModelSim

  • Assignments » Settings » Libraries » Global
    • Add
      • altera_ver
      • cycloneive_ver
  • Assignments » Settings » EDA Tool Settings » Simulation
    • Compile test bench
      • Delete the old Functional test bench
      • New
      • Test bench name = Timing test bench
      • Top-level module in test bench = example1_tb
      • Add the files listed below. After selecting each file using the ellipsis () file selector, edit the resulting path name to exclude the project path, then press Add.
        • example_tb.v
        • simulation/modelsim/example1.vo
          • it appears that eq2 and eq1 were included inside simulation/modelsim/example1.vo. If you have larger modules, make sure you include al the .vo files here.
        • if the simulation/modelsim directory doesn’t exist: recompile, and then add the .vo module.
      • If things don’t go your way, refer to the section “Some hints ..” under “Test bench for functional simulation”.

Start a full synthesis for the circuit

  • Processing » Start » Start Compilation

Start ModelSim

  • Tools » Simulation Tool » Gate Level Simulation
    • Timing model = Slow -6 1.2V 85 Model (default), this simulates a slow -6 speed grade model at 1.2 V and 85 °C.

Select the signals

  • Objects » select the signals of interest » Add Wave
  • Increase simulation time to 1 µs and click the run button on the right
  • Undock the Wave Window (so you can expand it)
  • Click “zoom full” and observe the simulated waveforms. You should see something like

Expect something like

own work

For more hands on experience, refer to Altera’s excellent University Program lessons, or the Terasic CD-ROM files (C:\altera_lite\DE0-Nano) for examples and documentation. Altera also has a more generic Become a FPGA Designer video-based class.

Our first implementation is the SPI interface Math Talk. This is then used to build a demonstration of math operations in FPGA as eluded to from the inquiry How do Computer do Math?.

c’est tout

Pitch Detection on Arduino using Autocorrelation

By our entrepreneur in residence, Johan Vonk

While playing my clarinet, I realized that it would be fun to hear other instruments playing alongside me. Instruments like guitar, piano or even a choir. It would also be nice if the melodies could be transcribed on paper. All existing solutions to these problems require a bulky computer or a cell phone. I realized that creating this compact device would combine my interest for music with my passion for engineering and math.

This project creates a small, affordable and accurate device that listens to a musical instrument and recognizes the notes played. These notes can then be sent to a synthesizer in the common MIDI format. This allows musician to hear other instruments playing alongside with them, and allows them store their compositions.\(\)

The implementation is in C++ and uses an Arduino UNO, breadboard, microphone and optional display. It displays the music as a piano roll and sends it to an external synthesizer.

Those that want to jump straight to the core, read at least the hardware page and download the code through GitHub.


Five years ago, I asked my dad “How do computer do math?”. Ever since, we have spent countless hours learning about the semiconductor physics, diode logic, programmable logic and microprocessors. I find it fascinating to learn about physics and engineering. With the help and dedication of my father, I then started programming. He has provided valuable insights and suggestions allowing me grow. While it can be frustrating at times, I also find it very enlightening to build programs with ever increasing complexity.

For this project, I conducted the research and development at home. As always, my father supervised the project and helped me with architecture and code reviews to keep it readable and maintainable. He also provided suggestions to organize the code to make modules reusable and testable. In particular, he helped me when the software appeared to have random crashes. He explained about heap and stack pointers, and suggested to test for at least a 50 bytes headroom after the data structures.

Goal, design criteria and constraints

The project creates a small embedded monophonic music transcription system. Monophonic means one sound, so you can transcribe one note at a time. Therefore you cannot use this device to analyze what a band is playing without each instrument playing separately.

The device samples an analog audio signal, processes it and creates a digital MIDI output. MIDI is a digital annotation for music that signals the beginning and ending of each note.

I set out to adhere to the following design criteria:

  1. It should detect the correct pitch for notes produced by a B♭ clarinet but also work for other monophonic instruments.
  2. The beginning and duration of each notes should be identified, regardless of it being followed by a rest, note change or note repetition. This process is called segmentation.
  3. There should be no noticeable delay between the incoming audio signal and the digital MIDI output.

The cost of the initial prototype, excluding the optional display, should be under $20 and fit on a credit card size PCB. To address these constraints, I chose to build the device around the commonly available Arduino UNO, an open source prototyping platform based on an 8-bit 16 MHz microcontroller with only 2 Kbyte SRAM. Using such a slow microcontroller with limited memory posed interesting challenges but also keeps the cost down. By creating a custom PCB, the final product can be approximately 1 inch in diameter what allows it to be clipped onto an instrument.


The common method of detecting a note pitch is by using a fast Fourier transform (FFT). This project shows that similar results can be achieved using autocorrelation. This method has the advantage of requiring only half the amount of memory compared to a FFT. The algorithm incorporates optimizations such using a low sample rate, simplifying the autocorrelation formula, using interpolation and asynchronously sampling the audio signal.
Testing with public audio samples, I found that all clarinet notes from 155.6 Hz (Eb3) to 1568 Hz (G6) are recognized correctly. Using normalization, this range can be extended to 98 Hz (G2) to 1568 Hz (G6) for the wider range of the piano. This small device enhances the experience of playing an instrument.
The source code is shared through GitHub what allows others to learn and improve this product.
Following chapters describe my project in detail. From the hardware schematic to verification methods. I hope you enjoy learning from my experience.

Table of contents

  1. Hardware
  2. Signal path
  3. Toolchain
  4. Digitizing the analog signal
  5. Frequency and pitch detection
  6. Note level segmentation and buffering
  7. Visualizing the notes
  8. Sending MIDI events
  9. Verification
  10. Conclusion

Building Math Hardware

derived work
Primary school teaches our students methods for addition, subtraction, multiplication and division. Computer hardware implements similar methods and performs them with astounding speed. This enables applications such as computer vision, process control, encryption, hearing aids, video compression to dubious practices as high-frequency trading.


This article describes how to build such hardware. In such, it is a sequel to the inquiry “How do Computers do Math?” that in chapter 7 introduced conceptual circuits using logic gates. We will model the various math operations using digital gates. Here we combine the gates into circuits and describe them using the Verilog Hardware Description Language (HDL). These Verilog HDL descriptions are compiled and mapped to a Field Programmable Gate Array (FPGA). Working knowledge of the Verilog HDL is assumed. To learn more about Verilog HDL, I recommend the book FPGA Prototyping with Verilog Examples, an online class or lecture slides. To help you get up to speed with the development boards, wrote Getting Started documents for two popular Altera and Xilinx boards. We aim to study algorithms to implement the algorithms in generic VLSI, and as such do will not use the highly optimized carry chain connections present on many FPGAs.

Hail to the FPGA

Let’s take this moment to honor the virtues of the FPGA. A FPGA can do many things at the same time and still respond immediately to input events. It is generally more complicated to create and debug the same logic in a FPGA compared to a microprocessor. Because of the challenges that FPGA development poses, many systems combine FPGAs and microprocessors to get the best of both worlds. For example, to recognize objects in a video stream, one would implement the pre-processing (noise removal, normalization, edge detection) in an FPGA, but the higher-level logic on a CPU or DSP. With a FPGA, you can put massive parallel structures in place. For example, an high-speed data stream can be distributed across the whole FPGA chip to be processed in parallel, instead of having a microprocessor deal with it sequentially. FPGAs can accelerate machine learning algorithms, video encoding, custom algorithms, compression, indexing and cryptography. By implements a soft microprocessor as part of the FPGA it can also handle high level protocols such as handle board management, protocol bridging and security tasks. [IEEExplore]


The first chapter describes the demonstration setup. Remaining chapters implement the concepts introduced in the inquiry How do Computers do Math?.
  1. Introduction
  2. Demonstration
  3. Adder (and subtractor)
  4. Faster adder (and subtractor)
  5. Multiplier
  6. Faster multiplier
  7. Divider
  8. Square root
  9. Conclusion


The code examples were tested on an Altera “Cyclone IV E” FPGA using Quartus Prime 16.1. Earlier code iterations used a Xilinx “Spartan-6” with their ISE Design Suite. The Verilog descriptions should work equally well on other boards or environments. For debugging, we used gate level simulation. In the real world, a DSLogic Logic Analyzer proved valuable in diagnosing problems.

Johan’s Software

Software that I wrote

Mandelbrot calculations that I wrote in Node JS «read more»
Countdown to Christmas animation that I wrote in Node JS «read more»

Learning at home

Getting started with Arduino
Breakout and shields. Development environment. «read more»
Web browser accessing Arduino data
Shows how an external web site can change i/o values on your Arduino. «read more»
Lego Mindstorms Graphical Programming
Bridges the gap between C programming and Lego NXT [2012] «read more»

Web browser accessing Arduino data

This article shows how an external web site can change i/o values on your Arduino. All you need is a RGB LED and an Arduino with an Ethershield or the newer Arduino Ethernet. (The other choice was a module around the Microchip ENC28J60. This has a lower price, but relies of the Arduino for the TCP/IP stack.)

To develop the web page, we use that enables rapid prototyping and testing. The web page consists of HTML, JavaScript and a style sheet. The JavaScript code handles the communication with the Arduino. No need to embedding web pages in your sketches, or shuffling an µSD card back and forth each time you want to try something new.


In this example we use a web interface to control a RGB LED on the Arduino. The web interface has a slider for each primary color. When a slider is changed, the new value is sent to the Arduino. The sketch on the Arduino then adjust the intensity of that color.

User Interface

jQueryMobile lets you build a sleek user interface with minimum effort. The complete HTML code for the page that we will be using is shown below. Note that when using jsFiddle, you only need the element It will add the based the libraries that you select. For the complete page with the CSS and JavaScript, please refer to the web page code further down.

<!DOCTYPE html>
<html class="ui-mobile">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <base href=".">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Web browser accessing Arduino data">
    <script src=""></script>
    <link rel="stylesheet" href="">
    <script src=""></script>
    <div data-role="page" id="pageone" data-theme="b">
      <div data-role="content">
	<div id="slider-r-div">
	  <label for="slider-r" class="ui-hidden-accessible">Red:</label>
	  <input id="slider-r" type="range" name="r" value="0" min="0" max="255" data-highlight="true" data-role="slider"></input>
	<div id="slider-g-div">
	  <label for="slider-g" class="ui-hidden-accessible">Green:</label>
	  <input id="slider-g" type="range" name="g" value="0" min="0" max="255" data-highlight="true" data-role="slider"></input>
	<div id="slider-b-div">
	  <label for="slider-b" class="ui-hidden-accessible">Blue:</label>
	  <input id="slider-b" type="range" name="b" value="0" min="0" max="255" data-highlight="true" data-role="slider"></input>


“A life without challenge, a life without hardship, a life without purpose, seems pale and pointless. With challenge come perseverance and gumption. With hardship come resilience and resolve. With purpose come strength and understanding.” ― Terry Fallis, The High Road

While writing the code, I encountered and tackled a few unexpected things. First, the Arduino Ethernet library could not support multiple clients to the same server port. Second, the Ethernet controller didn’t come up reliably. Last, the same-origin policy, intended to protect web surfers, required a work around. Let’s look at these issues one by one.

Multiple clients

We like to support up to four simultaneous browser sessions that communicate with the Arduino. Two support this, we need address two things. First, the Arduino Ethernet library needs to be patched to allow multiple clients to the same server port. A detailed description can be found here. Second, the browser needs to periodically read the color values from the Arduino, in case another browser session changed them. This is done by calling setInterval(scheduduledUpdate, 1000) from JavaScript.

Ethernet controller timing

After searching the internet and finally reading the datasheet, I realized that the Wiznet based Ethernet Controller takes longer than the Arduino to come out of reset. I later found a good write up at freetronics. It comes down to that the Ethernet Controller needs an additional 50 milliseconds before it is ready to communicate with the Arduino.

Same-origin policy (JSON-P)

As a JavaScript developer, you probably used asynchronous JavaScript and XML (Ajax) to exchange data with a server or update a web page. While sending an Ajax request to a server in the same domain is fairly straight forward, exchanging data with a server on different domain is a different story. The same-origin policy restricts scripts running in a browser to pages in the same domain. With your web site on and your Arduino on your local LAN, we need to work around this policy. We exploit the fact that <script> tags are not subjected to the same-origin policy. This is the same method that allows you to include the jQueryMobile library even it it is hosted on Google’s content delivery network.

JSONP requests are made by dynamically requesting a <script> tag from the Arduino. The Arduino responds with JSON wrapped in a function call. When making the request, the function name is specified as a callback function. When the server responds, the callback function (which must exist on your page) is executed with the JSON data as parameters. JSON is a human-readable format consisting of attribute-value pairs

For example, the browser evaluates the code. It replaces the missing callback name (?) with a unique name for the anonymous function, and adds an unique _= parameter to prevent caching by the browser.

$.getJSON("" + "?callback=?", { r: 12 }, function (jsonData) {

The browser will treat this as the HTML code shown below, and sent it over HTTP to the Arduino.

<script src=""></script>

The Arduino receives this as

GET /json?r=12&callback=jQuery210015603271196596324_1431060286376_=143106

and replies with the current values for red, green and blue

jQuery210015603271196596324_143106028637({ r: 12, g: 20, b: 20 })

The browser then executes this JavaScript.

(jsonData={"r": "12", "g": "20", "b": "20" }) {console.log(jsonData);}

That concludes the exchange.

The code

Now where we have all been waiting for. As mentioned earlier, the web page is hosted on jsfiddle. The sketch should be placed on the Arduino. I tested the sketch with the UNO R3 and version 1.6.3 of the IDE. Other versions may require some adjustments.

Bread board

Use a common cathode RGB LED, or just three separate LEDs. On the Arduino, digital outputs 5, 6 and 9 are each connected through a 220Ω current limiting resistor to the corresponding LED anodes. The cathode is, as you might guess, connected to ground. (note to self: use KiCAD and embed using CircuitBee.)

RGB-LED_schem RGB-LED_bb

Web page

jsFiddle to develop the HTML, JavaScript and CSS code for the web page. For development, I use the external resource firebug-lite-debug.js that among many other things shows the debug output (console log).

The web page presents three sliders. The fiddle is embedded below. Click on the Edit on the top right to make changes. Resize the top of the result tab to see the sliders.

Arduino Sketch

The sketch is not very earth shaking. It gets an DHCP assigned IP address. Make sure that you change the MAC address in the sketch listed below. You should use the MAC that was assigned to your shield. If you don’t have that, at least make sure that the number unique on your network.

The sketch listens on port 80. It parses the HTTP command into the command itself (GET), the URL and the parameters. One of the parameters is the name of the callback function as explained when we discussed the JSON-P protocol. Other parameters may be ‘r’ for red, ‘g’ for green and ‘b’ for blue. When found, their value is stored in the sketch, and used to adjust the intensity of that primary color At the end it sends a JSON-P response. The code is at GitHub.

Have fun! You can leave comments below.

Johan’s Science

I have enjoyed a great many hours in the pursuit of science. My ambition is to solve real problems using math and science.


Flight inquiry
An inquiry into how flight works. Also includes a video presentation from our school project and a Q&A about how flight works. [2010]
Land veroverd op de zee
How the Dutch make land from water. This was filmed on location in the Netherlands. [2011]


I enjoy watching NOVA and TED broadcasts.
Stanford Splash
I participated in Stanford Splash for the past 3 years

Studying at home

Below are some of the projects we did at home.

Flour, yeast, water and salt makes bread
Baking bread is an experiment in biochemistry. The fermentation makes the bread chewy, fluffy and tasty. «read more»
How do computers do math?
Solid-state chemistry, Ohm’s law, semi-conductors, logic gates and combinational logic, simple arithmetic logic unit. «read more»
How do microprocessors work?
Introducing a computer architecture, the microprocessor and its finite state machine and implemention on a field programmable gate array. «read more»
Electromagnetism Inquiry
Starting from electrons spinning around their axis all the way to electromagnetic fields. [2012] «read more»
Web browser accessing Arduino data
Shows how an external web site can help change i/o values on your Arduino. «read more»

Lego Mindstorms Programming (NXT-G 2.0)

The NXT-G graphical integrated development environment (IDE) provides the five basic elements of programming: input/output, conditionals, loops, variables and functions. It combines research ideas from MIT, with a graphical IDE from National Instruments.

The graphical IDE reduces the initial learning curve. Novices can start programming by combining Action blocks to make the motors move and generate light or sound. Once these concepts they can introduce flow elements such as conditionals, loops and wait. These flow elements can used embedded sensor readings. More advanced programmers can read the sensors directly and process the outputs using math and logic functions.

Coming from a more traditional text based programming environment, and trying stay a step ahead of my children, I read Terry Griffin’s excellent book [1] along with some other resources [2,3,4,5,6,7,8]. This is a write up for my future reference.

Work Flow

To create a program, you connect blocks.

  • Drag and drop blocks from the palette onto the work space. Each block performs an unique function such as turning the motors, or measuring a distance.
  • Use the tabs on the bottom of the palette to switch between sets of blocks.
  • To save your work as a package use Tools > Create Pack and Go.
  • As always, keep it simple. Divide up the problem in small steps, and test each step before combining them.

To compile, download to the NXT robot and run, you use the controls in the bottom-right of the work space.

  • middle-button, compiles the program, downloads and runs it to the NXT
  • top-right button, compiles selected blocks, downloads and runs it to the NXT
  • bottom-left button, compiles the program and downloads it to the NXT
  • bottom-right button, stops the program on the NXT.
  • top-left button, manages the NXT memory space, click the top-left button; click on the bar graph on the left to select a memory. This will also let you transfer files.
  • Bluetooth dongle, such as the AZiO BTD-V201 (don’t install the drivers from CD). To configure the connection use the top-left button on the NXT controls shown above.
  • Gyro Sensor, such as the HiTechnic part to build a Segway.
  • To change the default project directory: change settings.ini located in “shell:UsersFilesFolder\Documents\LEGO Creations\MINDSTORMS Projects\Profiles\Default”. For example:
    • Data Directory=”//FILESERVER/Your Name/Lego Mindstorms/Default”
  • Organizer to store the set, such as DeWalt Deep Pro Organizer.
  • Rechargeable batteries, max voltage is 1.75 V for each of the six AA batteries. NiMH appears to be a good fit.

I/O blocks (equiv. to library functions in C)

A program is composed by connecting blocks on a sequence beam. Blocks are executed sequentially.


Outputs functions are called “Action blocks” in NXT-G jargon. The Motor block controls a single motor that for example moves a robot arm, or rotate a wheel. The Move block, on the other hand, drives two motors, such as to rotate the wheels on a robot to make it go forward. The Move block synchronizes the motors to keep the robot travelling in a straight line. In all cases, you specify how far the motor turns, not how far an arm moves or a wheel travels. For a wheel, the distance traveled depends on the number of motor rotations, optional gears and the circumference of the wheel (14 cm for the snap-on tires).

Other output blocks generate sound, light or write to the display or Bluetooth device.

  • Motor action
    • Motor block
      • Controls a single motor
      • Automatically corrects for rotation errors.
      • Parameters:
        • action, constant or ramp up/down until target is met.
        • power, <10 will not move; >75 moves out of control.
        • control, automatically adjust the power to correct for resistance or slipping.
        • duration, unlimited = switches the motor on and continues with the next block on the Sequence beam.
        • wait, when unchecked, it will move on to the next block on the Sequence beam while the motor meanwhile completes its action.
    • Move block
      • Controls two motors, synchronizing the B and C motors
      • Automatically corrects for rotation errors.
      • Parameters (also see the Motor block):
        • steering, middle = straight; far left/right = spin in place (motors turn opposite directions).
        • next action, brake = provides accurate travel distance and then hold the motor in place; coast = stop the power to the motor so it rolls to a stop (Because the motor coasts to a stop, it will move a little further than the Duration setting. When a following Move or Motor block runs, it will automatically adjust for the rotation error.)
    • Reset
      • Resets the accumulated rotation error, causing the next Motor or Move block to disregard prior rotation errors. The Reset block should precede the first Motor or Move block in a program.
  • Other action blocks
    • Sound
      • Plays a sound file or a single tone
      • Parameters:
        • wait, when unchecked, the next block on the Sequence beam will start while the sound is playing.
    • Display
      • Writes a text string or shapes to the NXT display
    • Send message
      • Transmits a wireless message to another NXT assuming it has been paired before. Each NXT has 10 mailboxes each 5 messages deep. Head-drop when mailbox is full.
    • Color lamp
      • Turns a color lamp on or off.


ultrasonicMost input block read data from external sources and compare the data read to a preset value or range. The results are made available at its data hub. The data hub can be shown by clicking on the tab at the bottom of the block. Data wires connect the outputs to other blocks. Configuration parameters can also be set by incoming wires.

  • Sensor blocks
    • Ultrasonic Sensor block
      • Measures the distance to an object and compares it to a criterion.
      • Outputs:
        • yes/no, true if criterion is met, false otherwise
        • distance, scaled value from sensor [0..255 cm | 0..100 inches].
    • Touch Sensor block
      • Reads the touch sensor’s state and compares it to a criterion (pressed, released, bumped). Note that a program may not be fast enough to detect the “bumped” state.
      • Outputs:
        • yes/no, true if criterion is met, false otherwise
        • raw value, unscaled value from sensor [0..1024]
        • logic number, 0=released; 1=pressed.
    • NXT Buttons block
      • Reads a NXT button state and compares it to a criterion (pressed, released, bumped). Note that your program may not be fast enough to detect a condition as “bumped”.
      • Output:
        • yes/no, true if criterion is met, false otherwise.
    • Color Sensor block
      • Measures color or light intensity and compares it to a criterion. When the parameter “light” is checked it generates its own light and measure the reflected light.
      • Outputs:
        • yes/no, true if criterion is met, false otherwise
        • detected color, light intensity [0..100] or detected color (1=black; 2=blue; 3=green; 4=yellow; 5=red; 6=white).
    • Rotation sensor block
      • Measures the number of degrees that the motor turned and compares it to a criterion. The same block can also be used to reset the rotation counter.
      • Output:
        • yes/no, true if criterion is met, false otherwise
        • direction, true=forwards; false=backwards
        • degrees, scaled value from sensor [0..2147483647].
  • Other blocks
    • Timer block
      • Reads one of the tree timers and compares it against a criterion. Time is specified in seconds on the configuration panel, but in milliseconds when using input data wires. The block can also be used to reset a timer.
      • Output:
        • yes/no, true if criterion is met, false otherwise
    • Receive Message block
      • Receives a Bluetooth message and compare it against a criterion.
      • Outputs:
        • yes/no, true if criterion is met, false otherwise
        • message received, true when a message has been received, false otherwise
        • {text|number|logic} out, message data.
    • Random block
      • Generates a random number within a range. Can be used to make the robot a little unpredictable and thus more interesting.
      • Output:
        • number, random value between specified lower and upper bounds.

Data manipulation

Sophisticated data manipulations are supported through combining several number and text blocks.

  • Numbers
    • Math Block
      • Performs basic math operations (addition, subtraction, multiplication, division, square root, absolute value).
      • Output:
        • result, result of the operation [-2147483648 .. 2147483647]
    • Logic Block
      • Performs Boolean operations (AND, OR, XOR or NOT)
      • Output
        • result, result of the operation [true|false]
    • Compare Block
      • Performs less than (<), greater than (>) or equal (=) operations
      • Output
        • result, result of the operation [true|false]
    • Range Block
      • Determines if a value is within a range of numbers
      • Output
        • yes/no, true of the value is within range, false otherwise
  • Text strings
    • Number to Text block
      • Converts a number to a text string
      • Output
        • text, text representation of number [string]
    • Text block
      • Concatenates a maximum of three text strings
      • Output
        • text, concatenation of text strings [string]

Program Flow

Flow elements can take input from an embedded sensor or from a data wire.

  • Conditionals
    • Switch block (equiv. to switch())
      • Checks for a condition, and runs blocks on the sequence beam corresponding to that condition.
      • More then two conditions are allowed.
      • The ‘*’ button selects the default condition.
      • Floating point inputs are rounded to the nearest integer before comparing them.
      • Comments should be left outside a switch block.
  • Wait
    • Wait block
      • Busy-loop to poll an input until the specified condition is met.
  • Loops
    • Loop block (equiv. to do while())
      • Repeats a set of blocks until the end condition is met.
      • The loop count output is updated at the start of the last run through the loop, it will be one fewer than the total number of times the loop repeats.

My blocks (equiv. to user functions)

My blocks should be used to abstract program sections that perform specific functions. Dividing a program into smaller pieces, makes the program easier to read and maintain. Each My block can be tested independently and reused in the same or other programs.

  • Usage
    • Create, select the blocks; “Edit > Make a new My Block” from the menu
    • Open, double-click the My Block
    • Use, select from the Custom Palette (using the tab at the bottom of the Palettes)
    • Close, “File > Close” from the menu
    • Organize, “Edit > Manage Custom Palette” from the menu; then use the file system to organize.
  • Creating My blocks that have a data hub
    • Use compare, text or math blocks to supply input values to the blocks that will become a new My block. These additional blocks are only needed to supply the data wire, and will not become part of the My block.
    • Select the blocks for the new My Block and call “Edit > Make a new My Block” from the menu. All the data wires will remain connected. The value of the wire will also become configurable using the Configuration Panel.
    • Note that once a My block is made, you can change the name of data plugs, but you can not add more plugs. You will have to recreate the My block instead.
  • Appears broken if
    • two data plugs have the same name, or
    • there is problem with the data wire connections, or
    • the source file for the block has been moved or renamed in the computer’s file system.
  • Note
    • If you absolutely have to copy a My block, then use the file system. Don’t use “save as” from the menu.
    • When moving a program to another computer, also move the My Blocks or better yet create a package that contains all the related files (“Tools > Create Pack and Go”)


dataMost blocks have input plugs that correspond to the parameters in its configuration panel. Using the data inputs, a program can change these parameters. For example, the output of an ultrasound sensor could be used to specify the power of the motors, thereby slowing down the robot when it approaches an object.

Data wires (equiv. to mailboxes)

In the NXT-G world, data passes over so called “Data wires”. A Data wire connects one output to one or more inputs.

  • Scope
    • Local to the blocks that it connects to the wire.
  • Usage
    • draw a wire between blocks
      • expand the data hubs (click on the tab at the bottom of a block).
      • the plugs on the left are inputs; the plugs on the right are outputs.
      • click on an output terminal
      • click on the input terminal that you want to connect.
    • draw a wire into the boundary of a Switch block
      • enable tabbed view (disable flat view)
      • connect a wire to the input
      • switch back to flat view
    • draw wires from within the boundary of a Switch block
      • enable tabbed view
      • select the “true” condition and connect a wire
      • select the “false” condition and connect a wire from the output to the edge of the block where the existing wire crosses it.
      • switch back to flat view
    • delete a wire
      • click the data plug at the right of the wire.
  • Note
    • Use variables instead of passing data wires in/out of a Loop or Switch block.
    • Occasionally, a wire may be routed behind another block, making it appear as if its terminals are connected.
    • A dashed grey wire indicates a problem, such as
      • two plugs have different data types (Boolean, integer, float, string)
      • the output of a pass-through plug is not used without the input side connected
      • multiple inputs are connected to one output plug.
      • an input is connected to an output that appears later on the sequence beam.

Variable block (equiv. to variables)

Variables are expected to change over time, such as a distance to a wall. A variable can be used to connect one or more outputs to one or more inputs.

  • Scope
    • Local to the program (and its My blocks) that defines it.
  • Usage
    • create a variable, “Edit > Define Variables” from the menu.
    • use a variable, insert a Variable block.
    • delete a variable, first remove any Variable blocks that use it.
  • Notes
    • A program shares its variables with its My blocks if they have the same name and data type.
    • Perhaps not the best coding practice, but variables can be used when a My Block needs to remember a value.

Constant block (equiv. to const or #defines)

As the name implies, constant values do not change. An example is the diameter of the wheels on a robot. A constant block supplies a constant value to more or one inputs.

  • Scope
    • Global to all programs.
  • Usage
    • create, “Edit > Define Constants” from the menu. Specify the action “choose from list”.
    • use, insert a Constant block.
    • change, save any open programs that use that constant.
    • delete, “Edit > Define constants” from the menu. Note that any Constant block that uses that constant will change to Custom.
  • Note
    • When working with a program that uses custom constants, note that:
      • changing the value in one Constant block won’t affect the other programs.
      • creating a constant using the Edit Constant dialog will change all “Custom” constants with the same name.

File Access block

Files can store settings or input/output data for a program.

  • Scope
    • Global to all programs running on a NXT. Remain available after the program ends.
  • Usage
    • create, insert a File Access block; select create as the action. A list of files already on the NXT will appear (assuming it is connected using either USB or BT).
    • write, insert a File Access block; select write as the action to appends to a file.
    • read, insert a File Access block; select read as the action.
    • delete, insert a File Access block; select delete as the action.
    • close, insert a File Access block; select close. Remember to close a file after writing to it. Otherwise you can not delete or read from it.
  • Note
    • A program can write to or read from up to four files at once.
    • The Initial File Size data plug that allows you to specify how much memory to allocate for the file. If the file grows past the initial size, the NXT will move the file to larger memory space, thereby introducing a slight delay.

Sequence Beams (=threads).

Multitasking means doing more than one thing at a time. The sequence beam can fork, allowing your robot to do more than one thing at a time. But first, a short word about execution order:

Execution order

  • In general, a block will finish what it’s doing before the next block on the Sequence Beam runs. Exceptions are when “wait for completion” is unchecked, or a Move/Motor block is set to run indefinitely.
  • A block starts once all input values on the data wires are available.
  • A Loop/Switch block starts only once all the input values are available on data wires that enter the block (even though they might not be immediately used)
  • A data wire that starts inside a Loop/Switch block and connects to a block outside will only have a value after the Loop/Switch block finishes.
  • Only one copy of a particular My Block can run at the same time (non-re-entrant)
  • A program ends once it reaches the end of all the Sequence beams.

To add a task

  • Expand vertical space:
    • Add a Display block (that has a large data hub) at the end of the Loop block.
    • Open the data hub to create space within the loop.
    • Add a small comment to the bottom-left side of the Loop block to keep it open after the Display block is removed.
    • Delete the display block.
  • Add a new Sequence beam:
    • Add a new block under the existing Sequence beam.
    • Shift-click the existing Sequence Beam, and connect it to the new block.
  • To expand horizontal space:
    • Select the outer Loop block.
    • Click-and-hold the mouse on the Sequence Beam between the top-right block and the edge of the Loop block. Slowly drag the mouse to the right to widen the loop block.


  • Especially when working with multiple Sequence beams, allow the NXT-G some time to catch up with your editing.
  • Do not access the same sensor or motor from different Sequence beams.
  • Blocks on different sequence beams can communicate using variables, not pure data wires.


Often debugging a program proves to be more challenging than writing it. The NXT-G environment offers the following debug approaches:


[1] The Art of Lego Mindstorms NXT-G Programming (book)
Terry Griffin, 2010
[2] The Lego Mindstorms NXT 2.0 Discovery Book (book)
Laurens Valk, 2010
[3] Creating and using your own blocks with My Blocks
Dave Parker, 2007-2012
[4] Robots in a box (article)
New York Times, 2008
[6] NXT Tutorial (video)
Dale Yocum at Catlin Gabel School, 2012
[7] FFL Programming 101
Innovations in Science and Technology Education, 2007
[8] Example projects by complexity
Dave Parker, 2007-2012
[9] Programming solution for NXT – debugging [link dead]
Robot Magazine, 2012

Electromagnetism Inquiry

An electromagnetism inquiry inspired by Walter Lewin’ lectures Intro .. Homopolar motor

Assembling Elenco’s motor kit.

video of experiments we did



Magnetism is caused by moving charged electrical particles (Faraday, 1830s). These particles can be the current of electrons through an electric wire, or the movement of charged particles (protons and electrons) within an atom. These charged particles move much like planets in a solar system:

  • nucleus spin around its own axis, causing a very weak magnetic field.
  • electrons orbit around the nucleus, causing a weak magnetic field.
  • electrons spin around their own axis at the speed of light, causing a significant magnetic field (Goudsmit and Kronig, 1925).

Spinning electrons generate the bulk of the magnetism in an atom.

  • Within each orbit, electrons with opposite spins pair together, resulting in no net magnetic field.
  • Electrons in an orbit are filled up first by a + spin. Once all the orbitals are filled with unpaired + spins, the orbitals are then filled with the – spin. (see Spin direction)


The electron configuration in an atom determines a the magnetic characteristics:

  • In diamagnetic material, such as copper (Cu), all electrons are paired together. There is no net magnetic field from unpaired the electrons.
  • In paramagnetic material, such as magnesium (Mg), there are some unpaired electrons. The electron paths align to an external magnetic field. It becomes magnetized for as long as the external field is present.
  • In ferromagnetic material, such as iron (Fe) Co Ni, there are some unpaired electrons also. But in this case, not only the electron paths align, but also the atoms orient parallel to each other. Thus, even when the applied field is removed, the electrons maintain in a parallel orientation.
    • experiment: use a magnet to stroke a ferromagnetic bar, such as iron, several times in the same direction. The magnetic force from the north pole of the magnet causes the unpaired electrons to align themselves. The iron will stay magnetic.

own work

See also Electron spin, How atoms work, and Goudsmit’s lecture.

added challenge

  • MIT lectures 8.02,
  • NDT article,
  • Relativity tells us that what looks like a pure magnetic ¯eld in one frame of reference looks like an electric ¯eld in another frame of reference.



The magnetic field (B) is very strong at the poles and weakens as the distance to the poles increases.

A magnetic field line (Faraday) is a theoretical line that loops through the north pole of a magnet, passing through surrounding space, enter the south pole and going through the magnet back to the north pole. A higher density of nearby field lines indicates a stronger magnetic field. Field lines are a visual and conceptual aid only and are no more real than the contour lines (constant altitude) on a topographic map.

adapted work for unknown source

simulation: move compass and bar magnet using Faraday’s Lab.

experiment: visualize magnetic field using iron filings on paper/glass with bar magnet underneath.

Two magnets


Opposites attract.

Same poles repel.

The force between the two poles is directly proportional to the product of the pole strengths and inversely proportional to the square of the distance between the poles.

A compass is tiny magnet balanced on a pivot. It will rotate to point toward the opposite pole of a magnet.

Experiment: suspend a magnet from a string. It will align with the earth’s magnetic field, so that its S-pole points to the Earth’s N-pole.


A material that is attracted by a magnet becomes a magnet itself.

As an iron nail is brought close to a bar magnet, some flux lines emanating from the north pole of the magnet pass through the iron nail in completing their magnetic path. Since magnetic lines of force travel inside a magnet from the south pole to the north pole, the nail will be magnetized in such a polarity that its south pole will be adjacent to the north pole of the bar magnet. There is now an attraction between the two magnets.

experiment: move an iron nail to a bar magnet. Touch another nail to the end of the first nail. The magnetic field from the bar magnet will align the unpaired spins. First the ones closest to the bar magnet. This process can be repeated until the strength of the magnetic field weakens with the distance from the bar magnet. As soon as the first nail is pulled away from the bar magnet, all the nails will fall. Each nail had become a temporary magnet, but once the magnetizing force was removed, the unpaired spins once again assumed a random distribution

See also …..

original work



  • A moving charge (current) through a wire produces a magnetic field (Ørsted 1819, Ampère 1820).
  • The magnetic field lines form concentric circles around the wire.
  • The strength of the magnetic field: |B| = μ0.|I| /2Πr, where μ0 is the permeability of free space, I is the current, r is the distance from the wire.
  • The direction of the field follows the right-hand rule convention for vectors. In this case, the corkscrew rule, where the thumb points in the direction of the current, and the fingers point in the direction of the magnetic field lines.
  • Experiment, paper with iron filings, wire perpendicular to this paper and few seconds of strong current (100 A) through the wire.
  • See also the lecture Magnetic field and Lorentz Force, MIT.

Wire in magnetic field experiences force

A charge moving through a magnetic field experiences a force FB= q . (v × B), where v is the speed of the charge, q is the value of the charge and B is the magnetic field (Lorenz, 1892).

original work

The direction of FB is perpendicular to both the direction of the charge and the magnetic field. The direction is the cross product of v and B, and as such defined according to the right-hand rule for vectors. With the thumb, index, and middle fingers at right angles to each other (with the index finger pointed straight), the first (index) finger represents the first vector in the product (v); the second (middle) finger represents the second vector (B); and the thumb represents the product (FB).

Animation, Lorenz force, Univ. of Florida.

Experiment, current perpendicular to magnetic field. Thin wire (50 cm) suspended in between strong magnets. Connect wire to switch and two D-cell batteries.

Experiment, wire in between two poles demo as part of the lecture Magnetic field and Lorentz Force, MIT.

Experiment, Homopolar motor. (see also Homopolar)

Coil in magnetic field

make one,

Rotor in magnetic field

Simple motor, using D-cell battery, magnet, 2 clothes pins, and coil. (video, video2)

Eddy currents. Two equal masses slide down two identical aluminum tubes. Since one of the masses is magnetic it will induce eddy currents according to Lenz’ Law. This damps the motion of the mass causing the magnetic mass to take much longer to fall through the tube

Other stuff

How voltage is produced:

  • very strong at the poles and weakens as the distance to the poles increases;
  • goes from the north pole of a magnet, pass through surrounding space, enter the south pole and go through the magnet back to the north pole, thus forming a closed loop.
  • experiment: visualize magnetic field using iron filings on paper/glass with bar magnet underneath.

Flight Inquiry



  • Gather and group questions
  • For all questions in each group
    • Find the answer (see resources listed below)
    • Explain the answer on video
  • Piece the video fragments together
  • Present the video to the class. Video will be available your parents and teachers only.


  1. History
    • Did some planes crash? Did people fall out of the plane?
    • Who flew the first airplane? What was hard? How did they invent it?
    • What was the first airplane in a World War? What was the first Boeing plane?
  2. Lift
    • What keeps an airplane in the air? Why do planes fly?
    • What shape is a wing?
    • Do all planes have engines?
  3. Stability
    • Why do some paper airplanes fly longer than others?
    • Do airplanes need a tail?
    • How can I make a paper airplane fly longer?
  4. Wait, I have more questions!
    • How big is a Boeing 747?
    • What is the fattest plane? What is the longest plane?
    • Why are some people afraid of height but not of airplanes?


1. History Did some planes crash? Did people fall out of the plane? Who flew the first airplane? What was hard? How did they invent it? What was the first airplane in a World War? What was the first Boeing plane? 2. Lift What keeps an airplane in the air? Why do planes fly?
  • Balance of forces
    • Web page “Dynamics of flight” (NASA)
    • Video ” All about flight” (Schlessinger Media, Physical Science)
    • Wright Brothers reenactment, “The Four Forces” (NASA)
  • Gravity pulls the plane down
    • Animation “Gravity” (BrainPop)
    • Video “All about forces & gravity” (Schlessinger Media, Physical Science)
    • Wright Brothers reenactment “Weight” (NASA)
  • Lift pulls the plane up
    • See what happens when you change the wing using an airfoil simulator (or advanced) (NASA)
    • Wright Brothers reenactment “Lift” (NASA)
    • Animation “Flight” (BrainPOP, subscription required)
What shape is a wing?
  • See simulator; Google
Do all planes have engines?
  • Google
3. Stability Why do some paper airplanes fly longer than others? How can I make it fly longer? Do airplanes need a tail.
  • Three axis
    • Roll (lateral)
    • Pitch (longitudinal)
    • Yaw (directional)
  • Static stability, see Acrobat document “Flight stability” and “Stability and flight control” (Glenn Fisher)
    • Roll
      • Low Center of Gravity, see Web page “Keel Effect” (Peter Kunzmann)
      • Angle the wings angle slightly up, see Web page “Dihedral” (Peter Kunzmann)
    • Pitch
      • Nose heavy (Centre of Gravity in front of Pressure Center), see Wright reenactment “Center of Gravity” (NASA)
      • Elevator (horizontal tail).
    • Yaw
      • Vertical tail
How can I make a paper airplane fly longer?
  • There is no pilot to control position; design must be inherently stable
  • Examples of stable paper airplanes
4. Wait, I have more questions! How big is a Boeing 747?
  • Google is your friend
What is the fattest plane?
  • Google is your friend
Why are some people afraid of height but not of airplanes?
  • Interview teachers

More references

If you can’t explain it simply, you don’t understand it well enough. — Albert Einstein

Copyright © 2018 Coert Vonk, All Rights Reserved