Transistor Based Flip-Flop or a (not)RS NAND Latch

Been a while since I did a posting, too much time spent writing grants, and I mean a lot of time. In this blog I thought I’d describe a small project I did a month or two ago to build a sinple RS NAND latch using transitors only.The RS stands for Reset/Set. The latch itself is based on two NAND gates connected to each other in a cycle. The following diagram (borrowed from Wikipedia) shows the latch in terms of two NAND gates:

The inputs are designated bar S and bar R (bar meaning not). The outputs are Q and bar Q. Let us assume bar S is set to digital input zero and bar R to one. If you follow the logic through the two NAND gates you’ll realise that this means that Q will have a value of zero and bar Q one. This is the reset state and relative to Q, the circut stores a value of zero. If we now set bar S to one and bar R to zero, the circuit will flip to a new state where Q is now at one and bar Q at zero. Relative to Q the circuit stores a value of one. The point of the circuit is that even if bar S (or bar R) now goes back to zero the circuit remains in its last state. The only way to change the circuit is to apply a one to the reset or set input lines. The two states that the circuit exhibits are stable.

One can buy flip-flops ready made and one can also buy NAND gates ready made (7400). What I wanted to do was build a flip-flop using discrete transistors. I found the following site that describes how to build a 4 bit adder using transitors and from their circuit diagrams I came up with the following NAND circuit using transitors:

me2011_300 TransistorNANDGate

In the orgiinal circuit the input resistors were 10K but I wasn’t able to get enough forward bias with 10K so I dropped the input resistors to 4.7K. As with the adder circuit I used common NPN BC 547 tranistors. They are pretty cheap on ebay, you can get 50 for a dollar (!). I used 10 volts for the voltage supply but 9 volts willl work too. I used the following PCB boards, cut in half, to make a single NAND circuit:

pcbboard

Again you can find these cheaply on ebay for about 7 dollars for 10 boards. The image below shows a single NAND gate made using the circuit above.

NANDCircuit

 

I made two of the above NAND gates andf connected them together. I also made two LED driver circuits that would cature the outputs Q and bar Q. The final circuit looks like:

flipflop

There are two push buttons on the broad board next to the Set and Reset labels which momentarily take the inputs high (one), turning on the transitors. The circuit on the right that uses the white PC board is a simple LED driver, this also uses a BC547, with a 1K resistor on the output and a 4.7K resistor on the input. When the output from the flipflop goes to one current flows into the LED driver transistor base which in turns switches on the transitor allowing current to flow through LED which lights up. The LED circuit is shown below:

LEDriver

The following video shows the circuit in operation. For those who might be interested in taking this idea to the extreme, I suggest you check out the megaprocessor.

Posted in Electronics, General Science Interest | Leave a comment

Z80 Microcomputer

Its been a while since I wrote something for this blog, mainly due to pressures of work. However its summer now and I’ve managed to carve out some time to do other work related projects. One thing I’ve done in one of my undergraduate classes is host an honors projects which students can opt into. Part of this is to prove to me they can soldering electronic components onto a PCB board. Every engineer should be able to build electronic gadgets from scratch and solder is an essential skill to have.

In order to keep myself in hardware practice this summer I decided to go back in time and search out a Z80 microprocessor kit to build. When I was a teenager I built and designed my own Z80 system. If I remember right it had 512 bytes of RAM, switches and LED lights to enter and run programs. Once the machine was switched off however it forget any program that had been entered. I’d planned to add a hex keyboard etc but my money and spare time ran out. If you search the web you’ll find many Z80 based projects in various degrees of sophistication. There is an entire community of Z80 builders. Some specific ones that caught me eye include:

Ben Ryves Z80 Computer
Mini80 Computer
Cosam Z80 Project
Neat looking wiring
Z80 Single Board Computer

Those too young to know what a Z80 is, its one of the early microprocessors that came out in the 1970s, 1976 to be specific. It was basically an enhanced version of the 8080 a very early and popular Intel microprocessor. What was key about the Z80 was that is was quite easy to construct a basic computer using the Z80 chip. The chip required very few support chips, for example the clock was a simple single-phase clock (easily made from two NAND or NOT gates) and it only required a single 5v power supply. These and other features made the Z80 a very popular microprocessor at that time. Many famous and not so famous pre-IBM PC computers were build using the Z80, including the TRS-80, Nascom 1 and 2 (I had the Nascom 2), the famous Sinclair ZX80, ZX80 and ZX Spectrum, Amstrad CPC, Jupiter Ace, and many others. You can still purchase the chip new for only a few dollars.

My problem is I don’t have the time to design a new system for myself so instead, I hunted out any available kits. I found one and a nice one at that called the CPUville Z80 computer kit. This kit was developed and is sold by Donn Stewart. He has various addons to the base CPU board such as a serial interface and disk and memory expansion. What is also nice is that he adds the facility to single clock the microprocessor at very low speeds so that one can observe the operation of the computer in detail. Given my birthday is in July I decide to order one of his kits for myself. His kits are very modestly priced, the basic CPU board (I fully working Z80 computer) only costs $42 dollars. The kit comes fully complete except for the 5v power supply, but Donn can also supply this. The computer has 2K of RAM and a preprogrammed 2K ROM with various test routines included. Data is entered through a bank of 16 switches and output is via a set of 16 LEDs. To program this computer you’ll need to know binary and hex, and no you can’t browse the net using this computer.

Having obtained the kit, I assembled the various components. The kits comes with an excellent assembly and operation manual. The kits itself only supplies a few chip sockets for the CPU, RAM and ROM. I tend to be more cautious so I purchased a bunch of 20, 8 and 7 pin chip sockets. It probably took me about 6 hours to build. The board has about 500 soldered connections so you have to take your time and check the quality of your work. I took some pictures of the board during construction and a video to show the computer working. Amazingly it worked first time. Operation involves flipping a switch to halt the CPU, entering an address in ROM where a test program is lcoated and then releasing the CPU to run. The test program I ran was a simple counter than counted from zero to 65536 and output the binary number to the LED lights. If you need some fun with a very basic computer this seems to be the one to get.

Z80_A

 

 

Z80_B

 

Posted in Electronics, General Science Interest, Programming | Leave a comment

Bode Plots using Python

I needed a quick way to plot some Bode plots for a second order system. I didn’t have access to Matlab, instead I searched for a solution using Python, and I found one. Documentation is a bit sparse  so this example might be helpful.

The signals packages supports the signal.bode method which turned out to be quite easy to use. Signal is part of the scipy package and is something we bundle with our Tellurium platform.

There a more comprehensive discussion of Python and Control Theory here.

#
import numpy as np
from scipy import signal
from matplotlib import pyplot as plt

# Coefficients in numerator of transfer function
num = [1]
# Coefficients in denominator of transfer function
# High order to low order, eg 1*s^2 + 0.1*s + 1
den = [1, 0.1, 1]

# Scan over zeta, a parameter for a second-order system
zetaRange = np.arange(0.1,1.1,0.1)

f1 = plt.figure()
for i in range(0,9):
    den = [1, 2*zetaRange[i], 1]
    print den
    s1 = signal.lti(num, den)
    % Specify our own frequency range: np.arange(0.1, 5, 0.01)
    w, mag, phase = signal.bode(s1, np.arange(0.1, 5, 0.01).tolist())
    plt.semilogx (w, mag, color="blue", linewidth="1")
plt.xlabel ("Frequency")
plt.ylabel ("Magnitude")
plt.savefig ("c:\\mag.png", dpi=300, format="png")

plt.figure()

for i in range(0,9):
    den = [1, zetaRange[i], 1]
    s1 = signal.lti(num, den)
    w, mag, phase = signal.bode(s1, np.arange(0.1, 10, 0.02).tolist())
    plt.semilogx (w, phase, color="red", linewidth="1.1")
plt.xlabel ("Frequency")
plt.ylabel ("Amplitude")
plt.savefig ("c:\\phase.png", dpi=300, format="png")
%

Output from Python script:

Magnitude plot:mag

Phase plot:

phase

Posted in General Science Interest, Modeling, Programming, Software, Systems Theory | 1 Comment

Disappointed with Drobo 5N

I got myself a Drobo 5N to serve as a backup of my data and other work. For those who don’t know the Drobo 5N is a 5 bay network attached storage (NAS) device. What is interesting about the Drobo is that any of the drives (and more than one) in one of the 5 bays can be removed without any effect to your stored data. This is because all data is redundantly spread across all drives. Not only that but the drives you can have in the 5 bays can be any size and any make.

The problem however is that the Drobo 5N is not truly a network attached storage device because you can only access directly from your computer on your local network, ie your office. So for example if you have a Drobo drive in your office you can’t access your data from home or anywhere else in the world. Most NAS system do allow access, for example by running an ftp server. It is possible to install an ftp server on a Drobo but the installation is buggy and trashes the firmware. So all in all the Drobo 5N is a bit of a disappointment.

Posted in Electronics, General Interest | Leave a comment

Programming Language Popularity

As programmers we sometimes like to play the game of what is the most popular programming language? There are various metrics online that try to measure this, most notably TIOBEPYPL and Trendy Skills. They are all flawed in someway and often diverge considerably in their rankings. For example PYPL ranks Swift at number 9 whereas its not even in the top  24 on TIOBE. C is ranked 8th on Trendy Skills but 1st in TIOBE and 6th on PYPL. Sometimes they correspond for example, Javascript is ranked 7th place on both TIOBE and PYPL,

Another ranking system, also flawed, is the #code20XX twitter based rank. This is where people vote for what programming languages they used in the specified year. On #code2104 this year, Javascript was the winner closely followed by Python, Java then Ruby. On TIOBE Ruby is ranked 15th, and Python 8th. The other language to show itself on code2014 was Object Pascal. I get a lot of criticism for programming in Object Pascal/Delphi but I like it because its easy to read, very flexible to use and through the various GUI frameworks is ideal for writing cross platform GUI applications. On #code2014 Object Pascal/Delphi came 9th (compared to 20th on TIOBE). Object Pascal/Delphi beat a couple of mainstream languages include C and C++. I think this says more about the enthusiasm of the community than anything else which is of course an important factor when considering a language to use. The downside of Object/Pascal/Delphi is the dollar expense of buying into the platform. Embarcardero who sell the compiler and IDE charge a significant amount to be a member of this group. It effectively excludes most students and hobbyists from the community which is a great shame. On the plus side we have of course freepascal and lazarus which are also excellent cross platform tools and largely Delphi compatible. They are still perhaps a little immature in places but they are developing quickly.

code2014

 

Posted in Programming, Software | Leave a comment

Simple RK4 Code

Thought I’d start off the New Year with a simple freebie, a 4th Order Runge-Kutta class for Delphi, Windows and Mac OS. Should also work on Android and iOS mobile platforms and with Free Pascal. The code below shows how you’d use it. First declare the set of differential equations that need to be solved (TDoubleDynArray type can be found in Types):

 TMySystem = class (TObject)
    class procedure func (time : double; y, p, dydt : TDoubleDynArray);
 end;

class procedure TMySystem.func (time : double; y, p, dydt : TDoubleDynArray);
begin
  dydt[0] := p[0] - p[1]*y[0];
  dydt[1] := p[1]*y[0] - p[2]*y[1];
end;

Next, create a Runge-Kutta object:

// First argument = number of ODEs
// Second argument = number of parameters, if any
// Third argument = ODE Function
rk4 := TRK4.Create (2, 3, TMySystem.func);
rk4.p[0] := vo; rk4.p[1] := k1; rk4.p[2] := k2;

The above code include the option to declare and initialize some parameters that are part of the differential equations. To actually integrate the system by one step use the line:

// Return new time point, assign to startTime ready for next time
startTime := rk4.eval (startTime, y, stepSize);

The y argument will contain the updated solution. Run the line again to do the next step etc. Note that the eval method takes three arguments, that current value for the independent variable (time), an array that contains the current values for the dependent variable, and the step size to use.

Download the code here. RK4.zip The download include a Windows exe that you can try right away.

Posted in Delphi, Modeling, Programming | 1 Comment

My First Mac OS Application

I finished my first Mac OS application. Two screenshots are shown below, I’ll be making it available download at the end of the week. This was a test application to see how easy it would be use write a portable application using Firemonkey. The application in question is a specialist tool that allows users to load systems biology models expressed in SBML models and simulate them. It also has some limited steady state functionality. It users libRoadRunner as the backend simulator (libroadrunner.org). Most of the underling UI business code is new but the graphing component is one I resurrected from an old Windows project I had. Took me a week or two to extract the code from the old VCL Delphi application and swap in Firemonkey canvas methods. The biggest issue I had was remembering that Firemonkey now uses single precision values to represent canvas coordinates (VCL uses integer values).

I developed the application first on Windows using XE6. Once it was working on Windows I compiled it for Mac OS. Other than a few very minor issues (eg forgetting to remove Windows in the uses clause) getting it running on the Mac was surprisingly uneventful. It took me about 20 mins to get it working on the Mac, I was impressed. Pserver, which is the conduit for moving a Delphi application to the Mac makes the process child’s play. It copies over the relevant files and metadata and creates the bundle on the Mac’s hard drive ready to be distributed.

Some gotchas to watch out for:

1. Scroll bars don’t show automatically on the Mac in scrollable controls, to make them show up include the following line in your main form OnCreate event:

memo1.AniCalculations.AutoShowing:=false;

where memo1 is the name of a memo control.

2. Use the Deployment option in the Project menu to specify any Mac OS dylibs you want to distribute. pserver will handle the copying and bundling of these automatically.

3. Loading dll and dylibs. Not really a gotcha but I thought it would be tricky. This was surprisingly easy and in fact no different from Windows.

DllHandle :=LoadLibrary(PWideChar (fullpath));

Obviously the path to the libraries will change because the files extensions are different.

but I need this code to deal with any errors in the loading:

{$IFDEF POSIX}
errStr := string(dlerror());
{$ELSE}
errStr := SysErrorMessage(Winapi.Windows.GetLastError);
{$ENDIF}

Use of GetProcAddress is identical in Windows and Mac OS.

4. I couldn’t find the equivalent of GetDeviceCaps on the Mac so assumed the same size for the Mac and Windows.

5. I didn’t realize the current version of Delphi (even XE7) generates 32-bit Mac OS binaries which means it can’t load any 64-bit libraries. This posed a bit of a problem initially as we only distribute libRoadRunner as a 64 bit library and the current guardian of libRoadrunner was unable to create a 32-bit version. Luckily one of my other students, (Kyle Medley) was savvy enough to compile a 32-bit version which saved the day.

6. Bugs in XE6:

a) Don’t use a separate stylebook for each form because closing and freeing a second form will corrupt the buttons or other visual element on the calling form.

b) TextHeight returns incorrect an value for an empty string

7. The Firemonkey TStringGrid is severely limited or at least it seems that way. It’s currently a poor cousin of this VCL partner. Not sure how to get round its limitations yet.

8. The trackar is a limited control, there is no way to alter the thumb size or shape, track width, etc.

9. Various visual artifacts on some of the styles, eg Auric has problems with thumbs in tack bars.

10. The online documentation on menu handling between Mac OS and Windows appears to be completely incorrect.

Screenshots from a Mac Pro:

Screen Shot 2014-10-21 at 1.06.17 PM

 

Screen Shot 2014-10-21 at 1.07.24 PM

Posted in Delphi, Programming, SBML, Software | Leave a comment

Windows 10: Finally a better console

The windows console (accessed via cmd) is the coelacanth of software, barely unchanged though millions of years of software evolution. But finally selection pressure has final created a new species. Today Microsoft announced the start of the Windows 10 build up, release date apparently early 2015. One thing that caught many people’s attention is an update, finally, to the ‘MSDOS’ console. Compared to consoles found on other platforms or windows third-party consoles, the Windows console is something that should be retired to the Smithsonian or the London British Museum. Finally however we are getting Ctrl-V for paste and Ctrl-C for copy. At last.

For the gory details read more at New experimental console features in Windows

Posted in General Interest, Software | Leave a comment

Roman Fort at Clunderwen?

About ten years ago, a roman road was discovered tracing a path west of Carmarthen. Currently the road is known to reach as far as Wiston where a roman fort was recently found in 2013. This was the first roman fort ever found in Pembrokeshire. Excavation at Whitland as a result of road improvements also confirmed the presence of the road (and witnessed by the writer).

While looking along the route of the roman road on Google maps I recently noticed a rectangular structure very close to the roman road as it passed south of Clunderwen. The image below was taken from Google Maps. The rectangular structure is shown inside the red square (SN12311893). The red line is the rough alignment for the roman road. North is at the top of the image. The houses to the left of the enclosure mark the southern part of Clunderwen with the railway line arcing just at the top of center of the image. The Royal Commission marks this site as a generic ‘ENCLOSURE;DEFENDED ENCLOSURE;HENGE’ but the rectangular dimensions do not match the usual shape for an iron age or post roman site. The site was only recorded in 2011 and even the Royal Commission is unsure how to interpret the site and suggests a possible roman origin. Of more interest is that the distance between Wiston where there is a confirmed roman fort and the one suggested here is between 9 and 10 miles which is a common roman distance between marching camps. The forts that extend from Edinburgh to the north of Scotland are roughly 10 miles apart. The size of the enclosure is roughly 1.3 acres. (94 meters by 54 meters). This is small for a marching camp but not unheard of. For example Knockcross in Cumbria is only 1.5 acres.  The Wiston camp is a little bigger at about 130 by 160 meters. 

The circumstantial evidence is therefore suggestive that the rectangular enclosure south of clunderwen is in fact another Pembrokeshire roman fort. Only excavation can confirm this hypothesis. 

romanRoadC

Posted in General Interest | 1 Comment

Skynet Edges Closer

There is a fascinating article in science this week about the construction in hardware of a neural chip. This isn’t a new idea but scale and flexibility is novel. The chip is made by researchers from IBM and Cornell and can emulate 1,000,000 ‘neurons’. The developers claim that the approach is scalable, and efficient. Apparently chips can be cascaded to make even bigger networks.

I did a back of the envelope calculation to guestimate how many transistors it might take to emulate the brains from different organisms since we know how many transistors it took to make the chip.

This sentence was taken from Ars Technica: “The new processor, which the team is calling TrueNorth, takes a radically different approach. Its 5.4 billion transistors include over (1 million neurons) 4,000 individual cores” Assuming 100 billion neurons in a human brain that means it would take:

54 Trillion transistors to make a human brain, that is or roughly equivalent to 5,200 modern PCs, assuming 10 billion transistors per PC.

In other words not currently possible (In addition the fact that the chip only talks to 256 or neurons whereas the each brain neuron talks to about 7000). The IBM team would have to connect over 5000 chips to make a human brain, not that many it seems. Some other numbers:

Jelly Fish: ~ 4 Million transistors
Pond Snail Brain: ~ 60 Million transistors
Fruit Fly Brain: ~ 540 Million transistors
Honey Bee Brain: ~5.2 Billion transistors
Cockroach: ~5.3 Billion transistors 
Frog Brain: ~86 Billion transistors
Rat Brain: ~1 Trillion transistors
Human Brain: ~54 Trillion transistors


The single chip could just about simulate a Cockroach brain.

Brain data from http://en.wikipedia.org/wiki/List_of_an … of_neurons1 and
http://en.wikipedia.org/wiki/Neuron2

Posted in General Science Interest, Systems Theory | Leave a comment