четвртак, 12. јул 2018.

Adding byte-related instructions

Adding byte-oriented instructions

This is a follow-up of my previous post about the FPGA Computer.

When I initially commited the FPGA Computer, the CPU was 16-bit wide in both address and data bus. Also, all the instructions were word-oriented, working with 16 bits. Even the memory was word-oriented, having 64KWords, not 64KB. At first, that looked promising, having double the amount of RAM memory compared to the usual 8-bit platforms (64KW compared to 64KB).

However, all the instructions were word oriented, making byte-oriented programs complicated. For example, the UART loader receives bytes, not words, since the UART is byte-oriented. That causes a problem when the loader has to receive the code from the UART:

in r1, [64] ; get the byte from the uart into r1

ld r2, [flip]
cmp r2, 0
jz do_flip       ; we have received the even byte
; at this moment, r1 holds the received byte
neg [flip] ; we have received the odd byte - time to complete the word out of those two bytes (even and odd)
ld r0, [current_byte] ; get the even byte from the memory (stored earlier)
shl r0, 8 ; shift it 8 bits to the left
or r0, r1 ; complete the word
ld r2, [current_addr] ; r2 holds the current pointer in memory to store the received byte
st [r2], r0 ; store the completed word into the memory
inc r2 ; move to the next location in memory
st [current_addr], r2  ; save the incremented value of the current address
ld r2, [current_size]  ; increment the byte counter
inc r2
st [current_size], r2
cmp r2, [size] ; did we receive all?
jz all_arrived
j skip

do_flip:
neg [flip]
st [current_byte], r1 ; we need to receive two bytes to form the word, so we are saving this byte before receiving the other
ld r2, [current_size] 
inc r2 ; increment the byte counter
st [current_size], r2

cmp r2, [size] ; did we receive all?
jz all_arrived_even

j skip ; return and wait for the next byte

all_arrived_even:
; at this moment, r1 holds the received byte
shl r1, 8 ; the upper byte is for the odd bytes
ld r2, [current_addr] ; r2 holds the current pointer in memory to store the received byte
st [r2], r1 ; store the incomplete word into the memory
all_arrived:

As you can see, the problem is with the word-oriented instructions and memory locations. Whenever a byte comes to the computer, it must be saved, then combined with the next byte that would come, and that combination then stored in memory as a 16-bit value.

That was the reason for the redesign. I have introduced the ".b" suffix. If the instruction has the ".b" suffix, it is byte-oriented. This also caused the change in the addressing. The data bus is still 16-bit wide, and all the memory operations are 16-bit, but the address range covers 64KB now, instead of 64KW. That way, all the addresses in the assembler are byte-oriented, not word-oriented.

This means that if the instruction does not have the ".b" suffix, it will work with the word-oriented memory location, aiming at the word at the given address. If that is the case, the address must be aligned to 16-bits (even).

For example, this instruction is word-oriented:

ld r0, [1000]

It loads the 16-bit content of the address 1000 (two bytes, one byte from the 1001 and the other from 1000) and stores that 16-bit value in the r0 register. The address must be even.

If the instruction has the ".b" suffix, then it is byte-oriented. The address in byte-oriented instructions can be both even and odd. This instruction is byte-oriented:

ld.b r0, [1001]

It loads the 8-bit value (one byte) from the address 1001 into the r0 register.

It the 16-bit word is stored in the memory, it is stored as big endian, having the lower byte in odd address, and the upper byte in the even address. For example, the number 0x1234 stored at the 1000 address looks like this:

address
content
1000
0x12
1001
0x34

Now let's look at the same UART loader code, having byte-oriented instructions:

in r1, [64] ; get the byte from the uart into r1

; at this moment, r1 holds the received byte
; r2 holds the current pointer in memory to store the received byte
ld r2, [current_addr]
st.b [r2], r1 ; store the received byte into the memory
inc r2 ; move to the next location in memory
st [current_addr], r2 ; save the incremented value of the current address
ld r2, [current_size] ; increment the byte counter
inc r2
st [current_size], r2
cmp r2, [size] ; did we receive all?
jz all_arrived
j skip

all_arrived:

As you can see, the code is shorter and easier to understand.

The same idea can be applied to strings. Now that we have the byte-oriented instructions, dealing with byte-oriented strings is easy. This code prints the hello string on the screen:

VIDEO_0 = 2400 ; beginning of the text frame buffer
mov r2, 0 ; r1 is the index
mov r1, hello ; r1 holds the address of the "HELLO WORLD" string
again:
; load r0 with the content of the memory location to which r1 points
ld.b r0, [r1]          
cmp r0, 0 ; if the current character is 0 (string terminator),
jz end ; go out of this loop 
st.b [r2 + VIDEO_0], r0 ; store the character at the VIDEO_0 + r2 
inc r1 ; move to the next character
add r2, 2 ; move to the next location in the video memory
j again ; continue with the loop
end:
halt
hello:
#str "HELLO WORLD\0"

Conclusion

This change in the design of the CPU contributed to the much better assembler code. I haven't lost all the word-oriented instructions, but I have gained whole bunch of byte-oriented instructions. I did lose 64KB of memory, but my FPGA didn't have 128KB of SRAM memory anyway. 

Even if we try to make whole code word-oriented, we cannot skip 8-bit strings and protocols. That is why I have done this refactoring.

Here are github links:
- FPGAComputer
- FPGA Custom Assembler
- FPGA UART Loader (Raspbootin-like)
- FPGA Emulator

недеља, 24. јун 2018.

16-bit computer made using FPGA

16-bit computer on a FPGA

There are follow-ups of this topic:
- 32-bit FPGA computer,
- hardware sprites,
- the first game,
- PS/2 keyboard support,
- UART Loader,
- text mode,
- graphics mode,
- assembler,
- byte-oriented instructions.

I have made a 16-bit computer using my DE0-NANO FPGA board. The computer has 16-bit CPU, 64K 16-bit words, UART (115200 bps), and VGA (640x480, text-based frame buffer, 80x60 characters).

The Verilog code is on the github.


At first I used a breadboard


Then I have wired the board as a shield for the DE0-NANO

The schematics of the current version is above

The 16-bit CPU has 8 general-purpose registers (r0 – r7), pc (program counter), sp (stack pointer), ir (instruction register), mbr (memory buffer register), h (higher word when multiplying, or remainder when dividing).
The address bus is 16 bits wide, addressing 65536 memory locations (words). Data bus is also 16 bits wide, having each memory location 16 bits wide. This gives 65536 16-bits words, or 128KB.
Video output is VGA, 640x480. Text mode has 80x60 characters, each character being 8x8  pixels in dimensions. Video framebuffer in text mode has 4800 16-bit words (80x60 characters). The lower byte has the ASCII character, while the upper byte has the attributes (3 bits for the background color, 3 bits for the foreground color, inverted, and the last two bits unused).
It has two interrupts: IRQ0 and IRQ1. IRQ0 is connected to the KEY2 of the DE0-NANO, while IRQ1 is connected to the UART. Whenever a byte comes to the UART, it generates an IRQ1. Interrupt causes CPU to push flags to the stack, then to push PC to the stack and then to jump to the location designated for the CPU:
  • for the IRQ0, it is 0x0004, and
  • for the IRQ1, it is 0x0008.
It is up to the programmer to put the code in those locations. Usually, it is a JUMP instruction. To return from the interrupt routine, it is necessary to put the IRET instruction. It pops the return address, and then pops the flags register, and then goes back into the interrupted program.
KEY1 of the DE0-NANO is used as the reset key. When pressed, it forces CPU to go to the 0x0000 address. Usually there is a JUMP instruction to go to the main program.

VGA text mode

Text mode is 80x60 characters, occupying 4800 words. Lower byte is the ASCII code of a character, while the upper byte is the attributes:
7
6
5
4
3
2
1
0


Foreground color, inverted
Background color


r
g
b
r
g
b

The foreground color is inverted so zero values (default) would mean white color. That way, you don't need to set the foreground color to white, and by default (0, 0, 0), it is white. The default background color is black (0, 0, 0). This means that if the upper (Attribute) byte is zero (0x00), the background color is black, and the foreground color is white.
Attributes provide 8 foreground and 8 background colors

VGA female connector is connected via resistors to the GPIO-0 expansion header of the DE0-NANO board:

  • GPIO_R (pin 2, GPIO_00, PIN_A3) -> 68Ohm -> VGA_R,
  • GPIO_G (pin 4, GPIO_01, PIN_C3) -> 68Ohm -> VGA_G,
  • GPIO_B (pin 6, GPIO_03, PIN_D3) -> 68Ohm -> VGA_B,
  • GPIO_HS (pin 8, GPIO_05, PIN_B4) -> 470Ohm -> VGA_HORIZONTAL_SYNC,
  • GPIO_VS (pin 10, GPIO_07, PIN_B5) -> 470Ohm -> VGA_VERTICAL_SYNC.

UART interface

UART interface provides TTL serial communication on 115200kbps. It uses one start bit, one stop bit, and eight data bits, no parity, no handshake.
UART is connected to the GPIO-0 expansion header of the DE0-NANO board:

  • TX (pin 32, GPIO_025, PIN_D9) should be connected to the RX pin of the PC,
  • RX (pin 34, GPIO_027, PIN_E10) should be connected to the TX pin of the PC.
UART is used within the CPU via IN, and OUT instructions. RX triggers the IRQ1, which means that whenever a byte is received via UART, the IRQ1 will be triggered, forcing CPU to jump to the 0x0008 address. There you should place the JUMP instruction to your UART interrupt routine.
Inside the UART interrupt routine, you can get the received byte by using the IN instruction:

in r1, [64]; r1 holds now received byte from the UART 

To send a byte, first you need to check if the UART TX is free. You can do it by using the in instruction:
loop:
      in r5, [65]   ; tx busy in r5
      cmp r5, 0    
      jz not_busy   ; if not busy, send back the received character
      j loop
not_busy:
      out [66], r1  ; send the character to the UART

Addresses used by the UART are in the following table:
Address
Description
64
Received byte from the RX part of the UART (use the IN instruction).
65
0 if the TX part of the UART is free to send a byte, 1 if TX part is busy.
66
Byte to be sent must be placed here using the OUT instruction.

Assembler

The assembler for the CPU is again a fork of the customasm. This is a universal assembler, which can be used to generate machine code for any CPU. All you need is the instructions definition file. That file contains the list of instructions and the resulting machine code. For example, here are several instructions for my CPU:

#cpudef
{
#bits 16

#tokendef reg
{
r0 = 0
r1 = 1
r2 = 2
r3 = 3
r4 = 4
r5 = 5
r6 = 6
r7 = 7
sp = 8
h  = 9
}
nop  -> 16'0x0000
halt -> 16'0xfff0

mov {dest: reg}, {src: reg} -> src[3:0] @ dest[3:0] @ 4'0x0 @ 4'0x1
mov {dest: reg}, {value}    ->    4'0x0 @ dest[3:0] @ 4'0x1 @ 4'0x1 @ value[15:0]
...
}


The assembler is on the github.

UART loader

I have hardcoded the UART loader in the RAM memory. This means that whenever I start the computer, RAM contains the loader and after the reset, the loader is started. The loader initially sends the identification sequence to the PC, and the PC then sends the program to be executed. All this is done via serial port (UART). On my PC, I use the USB-to-serial (TTL) dongle. This way, I can develop programs on my PC and then load them on the board after the reset. The protocol for the loader is a modification of the Raspbootin protocol, which I have used for my bare metal programming.

Java client for uploading images is on the github.

Emulator

I have made an emulator for this computer. It is written in Java and it supports full-speed execution, break points, and step-by-step execution (both step-into and step-over). It has a separate window to display characters in the VGA framebuffer, and on that window, when you press a key, it will generate an IRQ1, emulating the UART reception of a byte ("received" byte is a pressed key).

Java-based emulator is on the github.

Conclusion

FPGA programming is fun, but also can be painful. Especially when you need to wait couple of minutes for the design to be compiled and placed on your board. Also, as I said earlier, the learning curve is very steep. You can run into a lot of problems at the beginning. First of all, you need to figure that all the lines in the Verilog are "executed" in parallel. You actually need to imagine the resulting hardware (or at least to have an idea what will be created) when programming in Verilog. 
Next, you need to read warnings! Some of those warnings will actually tell you what you have done wrong in your design. I have also run into problems with the operator precedence in Verilog. I had to place brackets to make an explicit order of evaluation, because it was different from my usual experience (in other programming languages).
I used my oscilloscope extensively during the VGA signal generation and UART development. Without it I would not have been able to make them work.
Horizontal sync pulses are shown on the oscilloscope

Also, I have used the Icarus Verilog to make the simulations. It is way faster than using the Altera ModelSim tool, and much easier to work with. Unfortunately, it cannot detect timing problems, which can occur, and which can make your design fail. If that is the case, read those warnings again! 
I will expand this text and write more texts about this computer and my experience with the FPGA programming.



четвртак, 10. мај 2018.

Generating VGA video signals using Raspberry Pi and then FPGA

I have recently found couple of posts (for example, this and this) on the net about generating VGA signals using just CPU. All those posts talk about generating 640x480 VGA video signals using Arduino.
I have decided to try to generate VGA signals using Raspberry PI 3. I have read that you can actually get the VGA output from the RPI without much problems, since it has that feature built in the Broadcom SoC. However, I didn't want to use the built in feature; I wanted to generate signals myself.
It proved to be quite difficult. First I tried the lowest possible level library, under the Raspbian OS:

// Set GPIO pins to output
INP_GPIO(VIDEO); // must use INP_GPIO before we can use OUT_GPIO
OUT_GPIO(VIDEO);
INP_GPIO(H_SYNC); // must use INP_GPIO before we can use OUT_GPIO
OUT_GPIO(H_SYNC);
INP_GPIO(V_SYNC); // must use INP_GPIO before we can use OUT_GPIO
OUT_GPIO(V_SYNC);

vSyncLow();
hSyncLow();
vgaOff();
nsleep(99999999);
while(1) {
line = 0;
vSyncLow();

while(line < 600){
    //2.2uS Back Porch
    delayMicroseconds(2);  
    
    //20uS Color Data
    vgaOn();  //High
    delayMicroseconds(10); // 1uS        
    //Red Color Low
    vgaOff();  //Low
    delayMicroseconds(10); // 1uS        
    
    //1uS Front Porch
    delayMicroseconds(1); // 1uS 
    line++;
    
    //3.2uS Horizontal Sync
    hSyncHigh();  //HSYNC High
    delayMicroseconds(3);
    hSyncLow();  //HSYNC Low
    
    //26.4uS Total
  }
  //Clear the counter
  line=0; 
  //VSYNC High
  vSyncHigh();
  //4 Lines Of VSYNC   
  while(line < 4){         
    //2.2uS Back Porch    
    delayMicroseconds(2);
    
    //20 uS Of Color Data
    delayMicroseconds(20);// 20uS
    
    //1uS Front Porch
    delayMicroseconds(1); // 1uS
    line++;
    
    //HSYNC for 3.2uS
    hSyncHigh();  //High
    delayMicroseconds(3);
    hSyncLow();  //Low  
    
    //26.4uS Total
  }
  
  //Clear the counter
  line = 0;
  //VSYNC Low
  vSyncLow();
  //22 Lines Of Vertical Back Porch + 1 Line Of Front Porch
  while(line < 22){
      //2.2uS Back Porch
      delayMicroseconds(2);

      //20uS Color Data
      delayMicroseconds(20);// 20uS
        
      //1uS Front Porch
      delayMicroseconds(1); // 1uS
      line++;
      
      //HSYNC for 3.2uS
      hSyncHigh();  //High
      delayMicroseconds(3);
      hSyncLow();  //Low  

      //26.4uS Total
  }     
}

The result was this:


The monitor has some physical damage, but that is not the problem. The problem is the bad synchronization. The timing is critical. Since the pixel frequency is approx. 25MHz, the time for a single pixel is 40 nanoseconds. In the picture, it is obvious that the lines do not start at the same time, which means that the horizontal sync pulses do not start at the precise time. They miss their time for couple of hundred of nano seconds.

OK, this could be due to the multitasking in the Linux OS. So, I moved to the bare metal programming. I have found a nice bare metal library on the github, here:


Author did a great job of making nice, readable examples. I have modified one of his examples and made a VGA signal generator using the built in interrupt generator, which is triggered every 3 microseconds:

// clear pending irq
*ARMTIMER_ACQ = 1;
//*TIMER_BASE = 2;
//printf("Inside dbg_main, counter: %d ", counter);
if (counter == 0) {
GPIO_SET(V_SYNC);
GPIO_SET(H_SYNC);
  GPIO_SET(VIDEO);
} else  
if (counter == 1) {
GPIO_CLR(H_SYNC);
  GPIO_CLR(VIDEO);
} else 

if ((counter % 8) == 0) {
GPIO_SET(H_SYNC);
  GPIO_SET(VIDEO);
} else 
if ((counter % 8) == 1) {
  GPIO_CLR(VIDEO);
GPIO_CLR(H_SYNC);
} 

if (counter == 17) {
GPIO_CLR(V_SYNC);
}

counter++;
if (counter == 4700) {
counter = 0;
}

However, the picture was not much better:


The timing is a bit better, but still horizontal sync pulses manage to miss the right time to fire.

I did all of this while waiting for the DE0-NANO FPGA board, which I choose to play with in order to generate VGA signals. When it finally arrived, I was able to properly generate VGA signals:


Then I have added the color and some text (top left corner):


Damage on the LCD is visible here, but it is OK for the development.

Here is the Altera DE0-NANO FPGA board:


I have purchased a female VGA connector and connected GPIO pins from the board to the connector:
  • GPIO_R -> 68Ohm -> VGA_R
  • GPIO_G -> 68Ohm -> VGA_G
  • GPIO_B -> 68Ohm -> VGA_B
  • GPIO_HS -> 470Ohm -> VGA_HORIZONTAL_SYNC
  • GPIO_VS -> 470Ohm -> VGA_VERTICAL_SYNC

I have found various values for the resistors on various sites (from direct connections, to 68 Ohms, 100Ohms, 500 Ohms, etc.), but this schematics works for me.

The Verilog code is quite simple. I have recycled the FizzBuzz example made by Ken Shirriff:

module vga(
//////////// CLOCK //////////
input CLOCK_50,  // this is 50MHz clock
//////////// KEY //////////
input KEY,             // reset key (one of two onboard keys)
//////////// GPIO //////////
output reg r,
output reg g,
output reg b,
output wire hs,
output wire vs
);

//=======================================================
//  REG/WIRE declarations
//=======================================================
reg clk25; // 25MHz signal (clk divided by 2)
reg newframe;
reg newline;

reg [9:0] x;
reg [9:0] y;
wire valid;

reg [7:0] xx;
reg [7:0] yy;

reg [7:0] framebuffer [9:0]; // 10  bytes text-based framebuffer
wire [6:0] counter;
wire [7:0] pixels; // Pixels making up one row of the character
//////////// GPIO //////////
output reg r,
output reg g,
output reg b,
output wire hs,
output wire vs
);
//=======================================================
//  REG/WIRE declarations
//=======================================================
reg clk25; // 25MHz signal (clk divided by 2)
reg newframe;
reg newline;

reg [9:0] x;
reg [9:0] y;
wire valid;

reg [7:0] xx;
reg [7:0] yy;

reg [7:0] framebuffer [9:0];
wire [6:0] counter;
wire [7:0] pixels; // Pixels making up one row of the character

//=======================================================
//  Structural coding
//=======================================================
initial begin
framebuffer[0] = "0";
framebuffer[1] = "1";
framebuffer[2] = "2";
framebuffer[3] = "3";
framebuffer[4] = "A";
framebuffer[5] = "a";
framebuffer[6] = "B";
framebuffer[7] = "b";
framebuffer[8] = "8";
framebuffer[9] = "9";
end
// Character generator

chars chars_1(
  .char(framebuffer[counter]),
  .rownum(y[2:0]),
  .pixels(pixels)
  );

assign hs = x < (640 + 16) || x >= (640 + 16 + 96);
assign vs = y < (480 + 10) || y >= (480 + 10 + 2);
assign valid = (x < 640) && (y < 480);
assign counter = (valid)?(x >> 3):0;

always @(posedge CLOCK_50) begin
newframe <= 0;
newline <= 0;
if (!KEY) begin
x <= 10'b0;
y <= 10'b0;
clk25 <= 1'b0;
newframe <= 1;
newline <= 1;
end
else begin
clk25 <= ~clk25;
if (clk25 == 1'b1) begin
if (x < 10'd799) begin
x <= x + 1'b1;
end
else begin
x <= 10'b0;
newline <= 1;
if (y < 10'd524) begin
y <= y + 1'b1;
end
else begin
y <= 10'b0;
newframe <= 1;
end
end
end
end

if (valid) begin

if (x < 80 && y < 8) begin
r <= pixels[7 - (x & 7)];
g <= pixels[7 - (x & 7)];
b <= pixels[7 - (x & 7)];
end
else begin
r <= (x < 213) ? 1 : 0;
g <= (x >= 213 && x < 426) ? 1 : 0;
b <= (x >= 426) ? 1 : 0;
end
end
else begin
// blanking -> no pixels
r <= 0;
g <= 0;
b <= 0;
end
end
endmodule

Verilog programming is not simple. It has a steep learning curve. The other problem can be a long compile time in the Quartus II IDE. For a bit more complex code than this VGA project, the compile time easily exceeds couple of minutes. I have solved this problem by installing the Icarus Verilog software, which compiles the Verilog code in a fraction of a second. This is due to the fact that the Icarus Verilog is not intended to deploy the Verilog code to the actual hardware - instead, it is intended for the simulation only. This way, I am able to produce the running and correct code quickly, and then I can copy that code into the Quartus II IDE, build the project, and deploy it to the real hardware.

недеља, 26. новембар 2017.

Custom made 16-bit CPU

I have created a custom made 16-bit CPU. I have used the LogiSim tool to create it. The CPU has three registers (A, B, and C), PC, SP, and some internal registers, such as MBR (Memory Buffer Register), IR (Instruction Register), and HIGH-BYTE register (keeps the upper 16-bit word of the  32-bit multiplication result, or a remainder when doing division).
Besides CPU, the system has 2x64KB of RAM and 16 words of text-based video memory, starting from the 0xfff0 address, and going to the 0xffff. The ALU is capable of doing all important operations including hardware-implemented multiplication and division. Both multiplication and division consume 32 cycles for 16-bit operands.


All the microcode is placed in two 32-bit ROMs:

There are around 100 instructions implemented: load/store, arithmetic, logical, shifting, jumps, calls, etc.
The CPU project is placed at the github: https://github.com/milanvidakovic/16-bit-CPU
The assembler for this CPU was forked from the original custom assembler and is also on the github: https://github.com/milanvidakovic/customasm
The output of the assembler are files in a such format that the LogiSim can load them into the RAM memory component.
The emulator was written in Java and it is capable of executing the machine code instructions which are the output of the assembler. It is also on the github:
https://github.com/milanvidakovic/16-bit-CPU-emulator

I have also created a transsembler which converts x86 assembler code made by the MS C compiler into the assembler for my custom CPU. That way, I can make a program in C and make it run on my CPU. The transsembler was written in Java and is also on the github: https://github.com/milanvidakovic/16-bit-CPU-transsembler

More sensors

This is a followup of my previous post.
I have managed to integrate multiple sensors into a single system capable of sensing if the entrance door is locked/unlocked, if there is a motion inside the apartment and to record the temperature and humidity.
It all started with the status of the entrance door. I wanted a system capable of sensing the status of the lock, but to be able to work without any electrical contacts, since it may corrupt the sensor in time. So I have found an inductive (contactless) switch and I have placed it in the entrance door of my apartment. It is connected to one of my raspberry pi computers, and it sends the information about the state of the door lock to my main server.
The Pi is glued to the wall next to the door:
You may wonder why are the headphones attached to the Pi. They emit the annoying sound of sine waveform, frequency of 3000Hz when the door is unlocked for more than one minute. That way I have a reminder that I need to lock the door.
The red LED is an indicator of the door lock status. If it is red, the door is locked. However, going to the door to see if it is locked or unlocked is not too attractive. I had to invent some way to know the door status without actually going to the door. That is why I have developed the Android application for it:
The lock icon goes red when the door is locked (the time is written below the icon), and goes green when the door is unlocked. The notification comes in real time thanks to the Google Cloud Messaging.
Next came the web portal. I wanted to have the history of door locking and unlocking. That is how I made this web page:

The red cell in the table indicates that there was some motion detected after the door has been locked. This is the proper introduction for the motion detection sensors: after adding door lock and temperature sensors, I wanted to add motion detection sensors inside the apartment. I have used HC SR-501 PIR motion detector:
I have three sensors placed around the apartment and I have a web page which updates the motion information in real time (WebSockets used):

Let us not forget the temperature and humidity sensors: