module
stringlengths
21
82.9k
module image_fifo #( parameter InIS = `IS_DEFAULT, parameter OutIS = `IS_DEFAULT, parameter MemoryWidth = 8 ) ( input clock, input reset, inout [`I_w(InIS)-1:0] image_in, inout [`I_w(OutIS)-1:0] image_out ); localparam ImagePayload_w = `I_Payload_w( InIS ); // Image In Signals wire image_in_valid; wire image_in_ready; wire image_in_error; reg image_in_request; reg image_in_cancel; wire [ImagePayload_w-1:0] image_in_payload; assign `I_Ready( InIS, image_in ) = image_in_ready; assign `I_Request( InIS, image_in ) = image_in_request; assign `I_Cancel( InIS, image_in ) = image_in_cancel; assign image_in_valid = `I_Valid( InIS, image_in ); assign image_in_payload = `I_Payload( InIS, image_in ); assign image_in_error = `I_Error( InIS, image_in ); // Image Out Signals wire image_out_valid; wire image_out_ready; wire image_out_request; wire image_out_cancel; reg image_out_error; wire [ImagePayload_w-1:0] image_out_payload; assign `I_Valid( OutIS, image_out ) = image_out_valid; assign image_out_ready = `I_Ready( OutIS, image_out ); assign image_out_request = `I_Request( OutIS, image_out ); assign image_out_cancel = `I_Cancel( OutIS, image_out ); assign `I_Payload( OutIS, image_out ) = image_out_payload; assign `I_Error( OutIS, image_out ) = image_out_error; // // Main Logic // // Store the whole payload (payload is the same In and Out reg [ImagePayload_w-1:0] memory [0:(1<<MemoryWidth)-1]; // MemoryWidth + 1 (so read != write when full - nice trick!) reg [MemoryWidth:0] read_address; reg [MemoryWidth:0] write_address; // Are we ready? There's room if r != w or rX == wX assign image_in_ready = ( read_address[MemoryWidth] == write_address[MemoryWidth] ) || ( read_address[MemoryWidth-1:0] != write_address[MemoryWidth-1:0] ); // Write logic always @(posedge clock) begin if ( reset || image_in_cancel ) begin write_address <= 0; end else begin if ( image_in_ready ) begin if ( image_in_valid ) begin memory[ write_address[MemoryWidth-1:0] ] <= image_in_payload; write_address <= write_address + 1; end end end end // Are we valid? (any time the whole read and write addresses are not exactly equal) assign image_out_valid = ( read_address != write_address ); // Read logic always @(posedge clock) begin if ( reset || image_in_cancel ) begin read_address <= 0; end else begin if ( image_out_valid ) begin if ( image_out_ready ) begin read_address <= read_address + 1; end end end end assign image_out_payload = ( image_out_valid ) ? memory[ read_address[MemoryWidth-1:0] ] : 0; always @( clock ) begin if ( reset ) begin image_in_request <= 0; image_in_cancel <= 0; image_out_error <= 0; end else begin image_in_request <= image_out_request; image_in_cancel <= image_out_cancel; image_out_error <= image_in_error; end end endmodule
module image_buffer #( parameter [`IS_w-1:0 ] IS = `IS_DEFAULT, parameter ImplementAccessPort = 0 ) ( input clock, input reset, input in_request_external, input out_request_external, inout [`I_w( IS )-1:0 ] image_in, inout [`I_w( IS )-1:0 ] image_out, output in_receiving, output out_sending, input [`IS_WIDTH_WIDTH( IS )-1:0] buffer_out_x, input [`IS_HEIGHT_WIDTH( IS )-1:0] buffer_out_y, output [`IS_DATA_WIDTH( IS )-1:0] buffer_out_data ); // // Spec Info // localparam Width = `IS_WIDTH( IS ); localparam Height = `IS_HEIGHT( IS ); localparam PixelCount = `IS_PIXEL_COUNT( IS ); localparam PixelCountWidth = `IS_PIXEL_COUNT_WIDTH( IS ); localparam WidthWidth = `IS_WIDTH_WIDTH( IS ); localparam HeightWidth = `IS_HEIGHT_WIDTH( IS ); localparam DataWidth = `IS_DATA_WIDTH( IS ); reg [DataWidth-1:0] buffer[0 : Height * Width -1]; // // Buffer In // wire in_start; wire in_stop; wire [DataWidth-1:0] in_data; wire in_valid; wire in_error; reg in_ready; reg in_request; reg in_cancel; assign in_start = `I_Start( IS, image_in ); assign in_stop = `I_Stop( IS, image_in ); assign in_data = `I_Data( IS, image_in ); assign in_error = `I_Error( IS, image_in ); assign in_valid = `I_Valid( IS, image_in ); assign `I_Request( IS, image_in ) = in_request; assign `I_Cancel( IS, image_in ) = in_cancel; assign `I_Ready( IS, image_in ) = in_ready; localparam BIN_STATE_IDLE = 0, BIN_STATE_RECEIVING = 1; reg bin_state; reg [WidthWidth-1:0] bin_x; reg [HeightWidth-1:0] bin_y; reg [PixelCountWidth-1:0] bin_index; wire [PixelCountWidth-1:0] bin_index_next = bin_index + 1; always @( posedge clock ) begin if ( reset || in_error ) begin bin_state <= BIN_STATE_IDLE; bin_index <= 0; in_cancel <= 0; in_ready <= 0; in_request <= 0; end else begin case ( bin_state ) BIN_STATE_IDLE: begin if ( in_request_external ) begin in_request <= 1; bin_state <= BIN_STATE_RECEIVING; in_ready <= 1; end end BIN_STATE_RECEIVING: begin // need a valid character - first needs a start marker if ( in_valid && ( bin_index || in_start ) ) begin in_request <= 0; buffer[ bin_index ] <= in_data; if ( bin_index_next != PixelCount ) begin bin_index <= bin_index_next; end else begin bin_index <= 0; in_ready <= 0; bin_state <= BIN_STATE_IDLE; end end else begin in_request <= 0; end end endcase end end assign in_receiving = (bin_state != BIN_STATE_IDLE ); // // Buffer Out // // Grab all the signals from the image pipe reg out_start; reg out_stop; reg [DataWidth-1:0] out_data; reg out_valid; reg out_error; wire out_ready; wire out_request; wire out_cancel; assign `I_Start( IS, image_out ) = out_start; assign `I_Stop( IS, image_out ) = out_stop; assign `I_Data( IS, image_out ) = out_data; assign `I_Valid( IS, image_out ) = out_valid; assign `I_Error( IS, image_out ) = out_error; assign out_request = `I_Request( IS, image_out ); assign out_cancel = `I_Cancel( IS, image_out ); assign out_ready = `I_Ready( IS, image_out ); localparam BOUT_STATE_IDLE = 0, BOUT_STATE_SENDING = 1; reg bout_state; reg [PixelCountWidth-1:0] bout_index; wire [PixelCountWidth-1:0] bout_index_next = bout_index + 1; always @( posedge clock ) begin if ( reset || out_cancel ) begin bout_state <= BOUT_STATE_IDLE; bout_index <= 0; out_start <= 0; out_stop <= 0; out_data <= 0; out_error <= 0; out_valid <= 0; end else begin case ( bout_state ) BOUT_STATE_IDLE: begin if ( out_request || out_request_external ) begin // assume idle values - change only the necessary out_start <= 1; out_data <= buffer[ 0 ]; out_valid <= 1; bout_state <= BOUT_STATE_SENDING; end end BOUT_STATE_SENDING: begin if ( out_ready ) begin if ( bout_index_next == PixelCount ) begin bout_index <= 0; out_stop <= 0; out_data <= 0; out_valid <= 0; bout_state <= BOUT_STATE_IDLE; end else begin out_start <= 0; bout_index <= bout_index_next; out_data <= buffer[ bout_index_next ]; if ( bout_index_next == PixelCount - 1 ) out_stop <= 1; end end end endcase end end assign out_sending = ( bout_state != BOUT_STATE_IDLE ); // // Buffer Initialization Maybe // reg [WidthWidth-1:0] init_x; reg [HeightWidth-1:0] init_y; initial begin for ( init_y = 0; init_y < Height; init_y = init_y + 1 ) for ( init_x = 0; init_x < Width; init_x = init_x + 1 ) buffer[ init_y * Width + init_x ] = 0; end // // Buffer Out Port // if ( ImplementAccessPort ) begin reg [DataWidth-1:0] ib_buffer_out_data; always @(buffer_out_y or buffer_out_x) begin ib_buffer_out_data = ( buffer[ buffer_out_y * Width + buffer_out_x ] ); end assign buffer_out_data = ib_buffer_out_data; end endmodule
module image_spec_check( input [31:0] in, output [31:0] out ); localparam IS = `IS( 0, 0, 100, 100, 0, 1, 0, 8, 8, 8, 0, 0 ); localparam X_l = `IS_X_l; localparam X_m = `IS_X_m; localparam Y_l = `IS_X_l; assign out = X_l; localparam ISw = `IS_w; assign out = ISw; localparam PS = `IS_PIPE_SPEC( IS ); assign out = PS; localparam P_D_w = `P_Data_w( PS ); assign out = P_D_w; localparam P_DS_w = `P_DataSize_w( PS ); assign out = P_DS_w; localparam P_RDS_w = `P_RevDataSize_w( PS ); assign out = P_RDS_w; localparam P_w = `P_w( PS ); assign out = P_w; localparam Iw = `I_w( IS ); assign out = Iw; endmodule
module camera_image #( parameter [`IS_w-1:0] IS = `IS_CAMERA, parameter CameraWidth = 752, parameter CameraHeight = 482, parameter ImageXInitial = 0, parameter ImageYInitial = 0, parameter CameraHorizontalBlanking = 600, parameter CameraVerticalBlanking = 750, // CHECK ON THIS parameter BlankingWidth = 10, parameter CoordinateWidth = 10, parameter CameraPixelWidth = 10, parameter I2CClockCount = 200, parameter I2CGapCount = ( 1 << 8 ) ) ( input clock, input reset, // Camera Control input configure, input start, input stop, // Camera Status output configuring, output error, output idle, output running, output busy, output image_transfer, // Image Control input [CoordinateWidth-1:0] image_x, input [CoordinateWidth-1:0] image_y, input image_origin_update, // Image Out inout [`I_w( IS )-1:0 ] image_out, input out_request_external, // Camera Connections to Hardware output scl_out, input scl_in, output sda_out, input sda_in, input vs, input hs, input pclk, input [CameraPixelWidth-1:0] d, output rst, output pwdn, input led, output trigger, output [7:0] debug ); // // Spec Info // localparam ImageWidth = `IS_WIDTH( IS ); localparam ImageHeight = `IS_HEIGHT( IS ); localparam ImageWidthWidth = `IS_WIDTH_WIDTH( IS ); localparam ImageHeightWidth = `IS_HEIGHT_WIDTH( IS ); localparam ImageDataWidth = `IS_DATA_WIDTH( IS ); localparam ImageC0Width = `I_C0_w( IS ); localparam ImageC1Width = `I_C1_w( IS ); localparam ImageC2Width = `I_C2_w( IS ); // // Local Copies // reg ci_configuring; reg ci_image_transfer; reg ci_busy; assign configuring = ci_configuring; assign image_transfer = ci_image_transfer; assign busy = ci_busy || camera_busy; assign running = camera_running; assign idle = camera_idle; // // Camera Core // // camera controls reg camera_configure; reg camera_start; reg camera_stop; // camera status wire camera_idle; wire camera_running; wire camera_configuring; wire camera_busy; reg [CoordinateWidth-1:0] column_start; reg [CoordinateWidth-1:0] row_start; reg [CoordinateWidth-1:0] window_width; reg [CoordinateWidth-1:0] window_height; reg set_window; reg set_origin; reg [BlankingWidth-1:0] horizontal_blanking; reg [BlankingWidth-1:0] vertical_blanking; reg set_blanking; reg snapshot_mode; reg set_snapshot_mode; reg snapshot; wire out_vs; wire out_hs; wire out_valid; wire [CameraPixelWidth-1:0] out_d; // 7 6 5 4 3 2 1 0 assign debug = { image_out_request, busy, camera_start, start, camera_running, camera_idle, camera_configuring, camera_configure }; camera_core #( .Width( CameraWidth ), .Height( CameraHeight ), .BlankingWidth( BlankingWidth ), .CameraPixelWidth( CameraPixelWidth ), .I2CClockCount( I2CClockCount ), .I2CGapCount( I2CGapCount ) ) cam ( .clock( clock ), .reset( reset ), // Camera Control .configure( camera_configure ), .start( camera_start ), .stop( camera_stop ), // Camera Status .configuring( camera_configuring ), .idle( camera_idle ), .running( camera_running ), .busy( camera_busy ), .error( error ), // Set Window / Origin .column_start( column_start ), .row_start( row_start), .window_width( window_width ), .window_height( window_height ), .set_origin( set_origin ), .set_window( set_window ), // Set Blanking .horizontal_blanking( horizontal_blanking ), .vertical_blanking( vertical_blanking ), .set_blanking( set_blanking ), // Set Snapshot .snapshot_mode( snapshot_mode ), .set_snapshot_mode( set_snapshot_mode ), .snapshot( snapshot ), // Camera Data .out_vs( out_vs ), .out_hs( out_hs ), .out_valid( out_valid ), .out_d( out_d ), // Connections to the hardware .scl_in( scl_in ), .scl_out( scl_out ), .sda_in( sda_in ), .sda_out( sda_out ), .vs( vs ), .hs( hs ), .pclk( pclk ), .d( d ), .rst( rst ), .pwdn( pwdn ), .led( led ), .trigger( trigger ) ); // // Image Out // // Grab all the signals from the image pipe reg image_out_start; reg image_out_stop; reg [ImageDataWidth-1:0] image_out_data; reg image_out_valid; reg image_out_error; wire image_out_request; wire image_out_cancel; wire image_out_ready; // Assign the outgoing signals assign `I_Start( IS, image_out ) = image_out_start; assign `I_Stop( IS, image_out ) = image_out_stop; assign `I_Data( IS, image_out ) = image_out_data; assign `I_Valid( IS, image_out ) = image_out_valid; assign `I_Error( IS, image_out ) = image_out_error; // Assign the incoming signals assign image_out_request = `I_Request( IS, image_out ); assign image_out_cancel = `I_Cancel( IS, image_out ); assign image_out_ready = `I_Ready( IS, image_out ); localparam CIM_STATE_POWERUP = 0, CIM_STATE_CONFIGURING = 1, CIM_STATE_WAIT_CONFIGURING = 2, CIM_STATE_CONFIGURE_WINDOW = 3, CIM_STATE_CONFIGURE_BLANKING = 4, CIM_STATE_RUNNABLE = 5, CIM_STATE_FRAME_IDLE = 6, CIM_STATE_FRAME_START = 7, CIM_STATE_FRAME_DATA = 8, CIM_STATE_FRAME_END = 9; reg [3:0] cim_state; reg [ImageWidthWidth+ImageHeightWidth:0] image_pixel_counter; localparam CommandTimerWidth = 4; localparam CommandTimerShortCount = 10; reg [ CommandTimerWidth:0 ] command_timer; wire command_timer_expired = command_timer[ CommandTimerWidth ]; always @( posedge clock ) begin if ( reset ) begin cim_state <= CIM_STATE_POWERUP; camera_start <= 0; camera_stop <= 0; command_timer <= -1; // local copies of camera status ci_configuring <= 0; ci_image_transfer <= 0; // camera control signals column_start <= 0; row_start <= 0; window_width <= 0; window_height <= 0; set_window <= 0; set_origin <= 0; horizontal_blanking <= 0; vertical_blanking <= 0; set_blanking <= 0; snapshot_mode <= 0; set_snapshot_mode <= 0; snapshot <= 0; // image output image_out_start <= 0; image_out_stop <= 0; image_out_data <= 0; image_out_valid <= 0; image_out_error <= 0; image_pixel_counter <= 0; end else begin case ( cim_state ) CIM_STATE_POWERUP: begin // 0 if ( configure ) begin camera_configure <= 1; ci_busy <= 1; cim_state <= CIM_STATE_WAIT_CONFIGURING; ci_configuring <= 1; command_timer <= CommandTimerShortCount; end end CIM_STATE_WAIT_CONFIGURING: begin // 1 if ( command_timer_expired ) begin if ( camera_configuring ) begin cim_state <= CIM_STATE_CONFIGURING; command_timer <= CommandTimerShortCount; end end else begin command_timer <= command_timer - 1; end end CIM_STATE_CONFIGURING: begin // 2 camera_configure <= 0; if ( command_timer_expired ) begin if ( camera_idle && ~camera_busy ) begin column_start <= ImageXInitial; row_start <= ImageYInitial; window_width <= ImageWidth; window_height <= ImageHeight; set_window <= 1; command_timer <= CommandTimerShortCount; cim_state <= CIM_STATE_CONFIGURE_WINDOW; end end else begin command_timer <= command_timer - 1; end end CIM_STATE_CONFIGURE_WINDOW: begin // 3 set_window <= 0; if ( command_timer_expired ) begin column_start <= 0; row_start <= 0; window_width <= 0; window_height <= 0; if ( camera_idle && ~camera_busy ) begin horizontal_blanking <= CameraHorizontalBlanking; vertical_blanking <= CameraVerticalBlanking; set_blanking <= 1; command_timer <= CommandTimerShortCount; cim_state <= CIM_STATE_CONFIGURE_BLANKING; end end else begin command_timer <= command_timer - 1; end end CIM_STATE_CONFIGURE_BLANKING: begin // 4 set_blanking <= 0; horizontal_blanking <= 0; vertical_blanking <= 0; if ( command_timer_expired ) begin if ( camera_idle && ~camera_busy ) begin ci_configuring <= 0; command_timer <= CommandTimerShortCount; ci_busy <= 0; cim_state <= CIM_STATE_RUNNABLE; end end else begin command_timer <= command_timer - 1; end end CIM_STATE_RUNNABLE: begin // 5 // if ( stored origin change ) // change origin if ( start ) camera_start <= 1; else camera_start <= 0; if ( stop ) camera_stop <= 1; else camera_stop <= 0; if ( camera_running && ( out_request_external || image_out_request ) ) begin ci_busy <= 1; cim_state <= CIM_STATE_FRAME_IDLE; image_pixel_counter <= 0; end end CIM_STATE_FRAME_IDLE: begin // 6 if ( image_out_cancel ) begin ci_busy <= 0; cim_state <= CIM_STATE_RUNNABLE; end else begin if ( ~out_vs ) begin cim_state <= CIM_STATE_FRAME_START; end end end CIM_STATE_FRAME_START: begin // 7 if ( image_out_cancel ) begin ci_busy <= 0; cim_state <= CIM_STATE_RUNNABLE; end else begin if ( out_vs ) begin cim_state <= CIM_STATE_FRAME_DATA; end end end CIM_STATE_FRAME_DATA: begin // 8 if ( image_out_cancel ) begin cim_state <= CIM_STATE_FRAME_END; end else begin if ( out_valid ) begin image_out_valid <= 1; image_out_data <= out_d; image_out_start <= ( image_pixel_counter == 0 ); if ( image_pixel_counter == 0 ) ci_image_transfer <= 1; if ( ( image_pixel_counter == ( ( ImageWidth * ImageHeight ) - 1 ) ) ) begin image_out_stop <= 1; cim_state <= CIM_STATE_FRAME_END; ci_image_transfer <= 0; end image_pixel_counter <= image_pixel_counter + 1; // if ( ~out_ready ) // abort! end else begin image_out_valid <= 0; image_out_data <= 0; image_out_start <= 0; image_out_stop <= 0; end end end CIM_STATE_FRAME_END: begin // 9 image_pixel_counter <= 0; image_out_valid <= 0; image_out_data <= 0; image_out_start <= 0; image_out_stop <= 0; ci_busy <= 0; if ( !out_vs ) begin cim_state <= CIM_STATE_RUNNABLE; end end endcase end end endmodule
module lcd_proxy #( parameter Width = 480, parameter Height = 320, parameter CoordinateWidth = 9, parameter DataWidth = 18, parameter PixelWidth = 16, parameter PixelRedWidth = 5, parameter PixelGreenWidth = 6, parameter PixelBlueWidth = 5 ) ( input clock, input reset, //LCD interface input [DataWidth-1:0] lcd_db, input lcd_rd, input lcd_wr, input lcd_rs, input lcd_cs, input lcd_rst, input lcd_blen, output lcd_fmark, output lcd_id, // Debug output output [DataWidth-1:0] lcd_out_data, output lcd_out_dc, output lcd_out_valid, output lcd_out_error, // Debug Access Port input [CoordinateWidth-1:0] lcd_out_x, input [CoordinateWidth-1:0] lcd_out_y, output[PixelWidth-1:0] lcd_out_p, output [7:0] debug ); localparam LCD_COMMAND = 0; localparam LCD_DATA = 1; localparam LCD_COMMAND_CODE_START = 8'H11; localparam LCD_COMMAND_CODE_SET_COLUMN_ADDRESS = 8'H2A; localparam LCD_COMMAND_CODE_SET_PAGE_ADDRESS = 8'H2B; localparam LCD_COMMAND_CODE_WRITE_MEMORY_START = 8'H2C; // we watch for this, then have a LONG snooze localparam LCD_COMMAND_START = 8'H11; localparam LCD_STATE_IDLE = 0, LCD_STATE_COMMAND = 1, LCD_STATE_SET_COLUMN_ADDRESS_X0_M = 2, LCD_STATE_SET_COLUMN_ADDRESS_X0_L = 3, LCD_STATE_SET_COLUMN_ADDRESS_X1_M = 4, LCD_STATE_SET_COLUMN_ADDRESS_X1_L = 5, LCD_STATE_SET_COLUMN_ADDRESS_Y0_M = 6, LCD_STATE_SET_COLUMN_ADDRESS_Y0_L = 7, LCD_STATE_SET_COLUMN_ADDRESS_Y1_M = 8, LCD_STATE_SET_COLUMN_ADDRESS_Y1_L = 9, LCD_STATE_WRITE_MEMORY_DATA = 10; reg [3:0] lcd_proxy_state; reg [PixelWidth-1:0] buffer[0 : Height * Width -1]; // reg [PixelWidth-1:0] buffer[Height-1:0][Width-1:0]; reg lcd_proxy_wr_prev; reg [DataWidth-1:0] lcd_proxy_out_data; reg lcd_proxy_out_dc; reg lcd_proxy_out_valid; reg lcd_proxy_fmark; reg lcd_proxy_id; reg lcd_proxy_out_error; wire lcd_proxy_write_operation = ~lcd_proxy_wr_prev && lcd_wr; wire lcd_proxy_write_data_operation = lcd_proxy_write_operation && ( lcd_rs == LCD_DATA); reg [CoordinateWidth-1:0] rect_x0; reg [CoordinateWidth-1:0] rect_y0; reg [CoordinateWidth-1:0] rect_x1; reg [CoordinateWidth-1:0] rect_y1; reg [CoordinateWidth-1:0] lcd_proxy_x; reg [CoordinateWidth-1:0] lcd_proxy_y; always @( posedge clock ) begin if ( reset ) begin lcd_proxy_wr_prev <= 0; lcd_proxy_state <= LCD_STATE_IDLE; lcd_proxy_fmark <= 0; lcd_proxy_id <= 0; lcd_proxy_out_error <= 0; rect_x0 <= -1; rect_y0 <= -1; rect_x1 <= -1; rect_y1 <= -1; lcd_proxy_x <= 0; lcd_proxy_y <= 0; end else begin lcd_proxy_wr_prev <= lcd_wr; case ( lcd_proxy_state ) LCD_STATE_IDLE: begin if ( lcd_proxy_write_operation ) begin if ( ~lcd_cs && ( lcd_rs == LCD_COMMAND ) && ( lcd_db == LCD_COMMAND_CODE_START ) ) begin lcd_proxy_state <= LCD_STATE_COMMAND; end end end LCD_STATE_COMMAND: begin lcd_proxy_out_error <= 0; if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_COMMAND ) begin case ( lcd_db ) LCD_COMMAND_CODE_SET_COLUMN_ADDRESS: begin lcd_proxy_state <= LCD_STATE_SET_COLUMN_ADDRESS_X0_M; end LCD_COMMAND_CODE_SET_PAGE_ADDRESS: begin lcd_proxy_state <= LCD_STATE_SET_COLUMN_ADDRESS_Y0_M; end LCD_COMMAND_CODE_WRITE_MEMORY_START: begin lcd_proxy_state <= LCD_STATE_WRITE_MEMORY_DATA; lcd_proxy_x <= rect_x0; lcd_proxy_y <= rect_y0; end endcase end end end LCD_STATE_SET_COLUMN_ADDRESS_X0_M: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin rect_x0[CoordinateWidth-1:8] = lcd_db; lcd_proxy_state <= LCD_STATE_SET_COLUMN_ADDRESS_X0_L; end else begin lcd_proxy_state <= LCD_STATE_COMMAND; lcd_proxy_out_error <= 1; end end end LCD_STATE_SET_COLUMN_ADDRESS_X0_L: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin rect_x0[7:0] = lcd_db; lcd_proxy_state <= LCD_STATE_SET_COLUMN_ADDRESS_X1_M; end else begin lcd_proxy_state <= LCD_STATE_COMMAND; lcd_proxy_out_error <= 1; end end end LCD_STATE_SET_COLUMN_ADDRESS_X1_M: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin rect_x1[CoordinateWidth-1:8] = lcd_db; lcd_proxy_state <= LCD_STATE_SET_COLUMN_ADDRESS_X1_L; end else begin lcd_proxy_state <= LCD_STATE_COMMAND; lcd_proxy_out_error <= 1; end end end LCD_STATE_SET_COLUMN_ADDRESS_X1_L: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin rect_x1[7:0] = lcd_db; end else begin lcd_proxy_out_error <= 1; end lcd_proxy_state <= LCD_STATE_COMMAND; end end LCD_STATE_SET_COLUMN_ADDRESS_Y0_M: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin rect_y0[CoordinateWidth-1:8] = lcd_db; lcd_proxy_state <= LCD_STATE_SET_COLUMN_ADDRESS_Y0_L; end else begin lcd_proxy_state <= LCD_STATE_COMMAND; lcd_proxy_out_error <= 1; end end end LCD_STATE_SET_COLUMN_ADDRESS_Y0_L: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin rect_y0[7:0] = lcd_db; lcd_proxy_state <= LCD_STATE_SET_COLUMN_ADDRESS_Y1_M; end else begin lcd_proxy_state <= LCD_STATE_COMMAND; lcd_proxy_out_error <= 1; end end end LCD_STATE_SET_COLUMN_ADDRESS_Y1_M: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin rect_y1[CoordinateWidth-1:8] = lcd_db; lcd_proxy_state <= LCD_STATE_SET_COLUMN_ADDRESS_Y1_L; end else begin lcd_proxy_state <= LCD_STATE_COMMAND; lcd_proxy_out_error <= 1; end end end LCD_STATE_SET_COLUMN_ADDRESS_Y1_L: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin rect_y1[7:0] = lcd_db; end else begin lcd_proxy_out_error <= 1; end lcd_proxy_state <= LCD_STATE_COMMAND; end end LCD_STATE_WRITE_MEMORY_DATA: begin if ( lcd_proxy_write_operation ) begin if ( lcd_rs == LCD_DATA ) begin // if ( ( lcd_proxy_x >= rect_x0 ) && ( lcd_proxy_x <= rect_x1 ) && // ( lcd_proxy_y >= rect_y0 ) && ( lcd_proxy_y <= rect_y1 ) ) begin buffer[ lcd_proxy_y * Width + lcd_proxy_x ] <= lcd_db; //$display( " Proxy Write [%3d,%3d] <= %x", lcd_proxy_x, lcd_proxy_y, lcd_db ); //end lcd_proxy_x <= lcd_proxy_x + 1; if ( lcd_proxy_x == rect_x1 ) begin lcd_proxy_x <= rect_x0; lcd_proxy_y <= lcd_proxy_y + 1; if ( lcd_proxy_y == rect_y1 ) begin lcd_proxy_state <= LCD_STATE_COMMAND; end end end else begin lcd_proxy_state <= LCD_STATE_COMMAND; lcd_proxy_out_error <= 1; end end end endcase end end assign lcd_out_data = lcd_proxy_out_data; assign lcd_out_dc = lcd_proxy_out_dc; assign lcd_out_valid = lcd_proxy_out_valid; assign lcd_out_error = lcd_proxy_out_error; // // Command & Data Echo // always @( posedge clock ) begin if ( reset ) begin lcd_proxy_out_valid <= 0; lcd_proxy_out_dc <= 0; lcd_proxy_out_data <= 0; end else begin if ( ~lcd_proxy_wr_prev && lcd_wr ) begin lcd_proxy_out_dc <= lcd_rs; lcd_proxy_out_data <= lcd_db; lcd_proxy_out_valid <= 1; end else begin lcd_proxy_out_valid <= 0; lcd_proxy_out_dc <= 0; lcd_proxy_out_data <= 0; end end end // // Pixel Reader (combinatorial for easy sim read out) // initial begin for ( lcd_proxy_y = 0; lcd_proxy_y < Height; lcd_proxy_y = lcd_proxy_y + 1 ) for ( lcd_proxy_x = 0; lcd_proxy_x < Width; lcd_proxy_x = lcd_proxy_x + 1 ) buffer[ lcd_proxy_y * Width + lcd_proxy_x ] = 0; end reg [PixelWidth-1:0] lcd_proxy_out_p; // ... added the lcd_out_valid term because lcd_out_y and lcd_out_x == 0 didn't trigger it. always @(lcd_out_valid or lcd_out_y or lcd_out_x) begin lcd_proxy_out_p = ( lcd_blen) ? ( buffer[ lcd_out_y * Width + lcd_out_x ] ) : 0; end assign lcd_out_p = lcd_proxy_out_p; endmodule
module camera_proxy #( parameter Width = 752, parameter Height = 482 ) ( input clock, input reset, // Camera Connections output scl_out, input scl_in, output sda_out, input sda_in, output vs, output hs, output pclk, input xclk, output [9:0] d, input pwdn, input rst, output led, input trigger ); // // Camera Registers // `include "../../drivers/rtl/camera_defs.vh" // // Defines // localparam PipeSpec = `PS_d8s; localparam PipeWidth = `P_w( PipeSpec ); localparam PipeDataWidth = `P_Data_w( PipeSpec ); localparam AddressWidth = PipeDataWidth - 1; localparam SlaveAddress = 7'H48; localparam RegisterWidth = 16; localparam FrameEndBlanking = 23; // // Camera State // reg cp_snapshot_mode; reg [RegisterWidth-1:0] cp_window_height; reg [RegisterWidth-1:0] cp_window_width; reg [RegisterWidth-1:0] cp_column_start; reg [RegisterWidth-1:0] cp_row_start; reg [RegisterWidth-1:0] cp_horizontal_blanking; reg [RegisterWidth-1:0] cp_vertical_blanking; reg [RegisterWidth-1:0] cp_exposure; // // I2C Slave // // The I2C Slave has a pipe in and a pipe out. An I2C write operation results in data coming out of the out port. // In this case it will be a register index coming out, then either data in the case of a write, or the register // value will be expected on the in port in the case of a read. wire [PipeWidth-1:0] pipe_in; wire [PipeWidth-1:0] pipe_out; reg pipe_in_start; reg pipe_in_stop; reg [PipeDataWidth-1:0] pipe_in_data; reg pipe_in_valid; wire pipe_in_ready; wire pipe_out_start; wire pipe_out_stop; wire [PipeDataWidth-1:0] pipe_out_data; wire pipe_out_valid; reg pipe_out_ready; p_pack_ssdvrp #( PipeSpec ) in_pack( pipe_in_start, pipe_in_stop, pipe_in_data, pipe_in_valid, pipe_in_ready, pipe_in ); p_unpack_pssdvr #( PipeSpec ) out_unpack( pipe_out, pipe_out_start, pipe_out_stop, pipe_out_data, pipe_out_valid, pipe_out_ready ); i2c_slave_core #( .Address( SlaveAddress ), .PipeSpec( PipeSpec ) ) i2c_s( .clock( clock ), .reset( reset ), .pipe_in( pipe_in ), .pipe_out( pipe_out ), .scl_in( scl_in ), .scl_out( scl_out ), .sda_in( sda_in ), .sda_out( sda_out ) // .debug( debug ) ); // // Communication Logic // // Listen for register updates, and provide register values in response to I2C queries. localparam CP_STATE_INITIALIZE_A = 0, CP_STATE_INITIALIZE_B = 1, CP_STATE_IDLE = 2, CP_STATE_DATA_M = 3, CP_STATE_DATA_L = 4, CP_STATE_DATA_STORE = 5; reg [2:0] cp_state = CP_STATE_IDLE; reg [7:0] register_index; reg [RegisterWidth-1:0] register_value; reg [RegisterWidth-1:0] registers [0:255]; // fixed length! reg [4:0] cp_configuration_index; reg running; reg register_index_set; always @( posedge clock ) begin if ( reset ) begin cp_state <= CP_STATE_INITIALIZE_A; pipe_out_ready <= 0; running <= 0; register_index_set <= 0; register_index <= 0; // load the internal variables with the correct default values cp_snapshot_mode <= ( Register_ChipControl_SensorOperatingMode_Default == Register_ChipControl_SensorOperatingMode_Snapshot); cp_column_start <= Register_ColumnStart_Default; cp_row_start <= Register_RowStart_Default; cp_window_height <= Register_WindowHeight_Default; cp_window_width <= Register_WindowWidth_Default; // Going to do some minumums here, rather than the defualts cp_horizontal_blanking <= Register_HorizontalBlanking_Min; cp_vertical_blanking <= Register_VerticalBlanking_Min; cp_exposure <= Register_CoarseShutterWidth_Min + 100; // get the config logic ready cp_configuration_index <= 0; end else begin case ( cp_state ) CP_STATE_INITIALIZE_A: begin // 0 if ( cp_configuration_done ) begin pipe_out_ready <= 1; cp_state <= CP_STATE_IDLE; end else begin register_index <= cp_configuration_register; cp_state <= CP_STATE_INITIALIZE_B; end end CP_STATE_INITIALIZE_B: begin // 1 registers[ register_index ] <= cp_configuration_data; cp_configuration_index <= cp_configuration_index + 1; cp_state <= CP_STATE_INITIALIZE_A; end CP_STATE_IDLE: begin // 2 if ( pipe_out_valid && pipe_out_start ) begin register_index <= pipe_out_data; if ( !pipe_out_stop ) begin cp_state <= CP_STATE_DATA_M; end end end CP_STATE_DATA_M: begin // 3 if ( pipe_out_valid ) begin // might have been the terminating byte if ( pipe_out_stop ) begin cp_state <= CP_STATE_IDLE; end else begin register_value[ 15:8 ] <= pipe_out_data; cp_state <= CP_STATE_DATA_L; end end end CP_STATE_DATA_L: begin // 4 if ( pipe_out_valid ) begin // might have been the terminating byte - although at this place it would be bad if ( pipe_out_stop ) begin cp_state <= CP_STATE_IDLE; end else begin register_value[ 7:0 ] <= pipe_out_data; pipe_out_ready <= 0; cp_state <= CP_STATE_DATA_STORE; end end end CP_STATE_DATA_STORE: begin // 5 // interpret register loads (selectively) case ( register_index ) Register_Reset: if ( register_value[ Register_Reset_LogicReset_l ] == 1 ) running <= 1; Register_ChipControl: cp_snapshot_mode <= ((( register_value >> Register_ChipControl_SensorOperatingMode_l ) & Register_ChipControl_SensorOperatingMode_mask ) == Register_ChipControl_SensorOperatingMode_Snapshot ); Register_ColumnStart: cp_column_start <= ( register_value > Register_ColumnStart_Max ) ? Register_ColumnStart_Max : (( register_value < Register_ColumnStart_Min ) ? Register_ColumnStart_Min : register_value ); Register_RowStart: cp_row_start <= ( register_value > Register_ColumnStart_Max ) ? Register_ColumnStart_Max : (( register_value < Register_ColumnStart_Min ) ? Register_ColumnStart_Min : register_value ); Register_WindowHeight: cp_window_height <= ( register_value > Register_RowStart_Max ) ? Register_RowStart_Max : (( register_value < Register_RowStart_Min ) ? Register_RowStart_Min : (( register_value > Height ) ? Height : register_value ) ); Register_WindowWidth: cp_window_width <= ( register_value > Register_WindowWidth_Max ) ? Register_WindowWidth_Max : (( register_value < Register_WindowWidth_Min ) ? Register_WindowWidth_Min : (( register_value > Width ) ? Width : register_value ) ); Register_HorizontalBlanking: cp_horizontal_blanking <= ( register_value > Register_HorizontalBlanking_Max ) ? Register_HorizontalBlanking_Max : (( register_value < Register_HorizontalBlanking_Min ) ? Register_HorizontalBlanking_Min : register_value ); Register_VerticalBlanking: cp_vertical_blanking <= ( register_value > Register_VerticalBlanking_Max ) ? Register_VerticalBlanking_Max : (( register_value < Register_VerticalBlanking_Min ) ? Register_VerticalBlanking_Min : register_value ); endcase register_index <= register_index + 1; cp_state <= CP_STATE_DATA_M; pipe_out_ready <= 1; end endcase end end // // CONFIGURATION TABLE // // List of registers and values to stick in them // Combinatorial - you set the index and it snaps to the right value // Last one sets the done flag reg cp_configuration_done; reg [7:0] cp_configuration_register; reg [15:0] cp_configuration_data; always @(*) begin cp_configuration_register = 8'H00; cp_configuration_data = 16'H0000; case ( cp_configuration_index ) // make sure this register is wide enough 0: { cp_configuration_done, cp_configuration_register, cp_configuration_data } = { 1'H0, Register_ChipVersion, Register_ChipVersion_MT9V022 }; 1: { cp_configuration_done, cp_configuration_register, cp_configuration_data } = { 1'H0, Register_WindowHeight, Register_WindowHeight_Default }; 2: { cp_configuration_done, cp_configuration_register, cp_configuration_data } = { 1'H0, Register_WindowWidth, Register_WindowWidth_Default }; 3: { cp_configuration_done, cp_configuration_register, cp_configuration_data } = { 1'H0, Register_HorizontalBlanking, Register_HorizontalBlanking_Default }; 4: { cp_configuration_done, cp_configuration_register, cp_configuration_data } = { 1'H0, Register_VerticalBlanking, Register_VerticalBlanking_Default }; 5: { cp_configuration_done, cp_configuration_register, cp_configuration_data } = { 1'H0, Register_ChipControl, Register_ChipControl_Default }; 6: { cp_configuration_done, cp_configuration_register, cp_configuration_data } = { 1'H0, Register_ReadMode, Register_ReadMode_Default }; default: { cp_configuration_done, cp_configuration_register, cp_configuration_data } = { 1'H1, 8'H00, 16'H0000 }; endcase end // Register Read reg reading_msb; always @( posedge clock ) begin if ( reset ) begin reading_msb <= 0; pipe_in_start <= 0; pipe_in_stop <= 0; pipe_in_data <= 0; pipe_in_valid <= 0; end else begin // allow the controller to reset the reading_msb flag if ( register_index_set ) begin reading_msb <= 0; end else begin // data coming out of the pipe is sent to the specified register, either msb or lsb if ( pipe_in_ready ) begin pipe_in_valid <= 1; if ( !reading_msb ) begin pipe_in_start <= 1; pipe_in_stop <= 0; pipe_in_data <= registers[ register_index ][15:8]; reading_msb <= 1; end else begin pipe_in_start <= 0; pipe_in_stop <= 1; pipe_in_data <= registers[ register_index ][7:0]; reading_msb <= 0; end end end end end // // Pixel Data // // // Deliver pixels roughly as the sensor would // 2D State Machines // VerticalState // HorizontalState // // create the output regs reg cp_vs; reg cp_hs; reg [9:0] cp_d; //reg cp_trigger; reg cp_led; // connect them assign vs = cp_vs; assign hs = cp_hs; assign d = cp_d; // assign trigger = cp_trigger; assign led = cp_led; // pixel clock is inverted system clock assign pclk = !xclk; localparam HorizontalMaxValue = ( Register_HorizontalBlanking_Max > Register_WindowWidth_Max ) ? Register_HorizontalBlanking_Max : Register_WindowWidth_Max; localparam VerticalMaxValue = ( Register_VerticalBlanking_Max > Register_WindowHeight_Max ) ? Register_VerticalBlanking_Max : Register_WindowHeight_Max; localparam HorizontalWidth = $clog2( HorizontalMaxValue + 1 ); localparam VerticalWidth = $clog2( VerticalMaxValue + 1 ); // Horizontal counter - expired when = -1, hence load with Count - 2 when initializing. Extra bit for rollover reg [HorizontalWidth:0] cp_horizontal_counter; wire cp_horizontal_counter_expired = cp_horizontal_counter[ HorizontalWidth ]; // Horizontal counter - expired when = -1, hence load with Count - 2 when initializing. Extra bit for rollover reg [VerticalWidth:0] cp_vertical_counter; wire cp_vertical_counter_expired = cp_vertical_counter[ VerticalWidth ]; localparam XWidth = $clog2( Register_WindowWidth_Max + 1 ); localparam YWidth = $clog2( Register_WindowHeight_Max + 1 ); reg [XWidth-1:0] window_x; reg [YWidth-1:0] window_y; reg [XWidth-1:0] image_x; reg [YWidth-1:0] image_y; localparam CP_VERTICAL_IDLE = 0, CP_VERTICAL_WAIT_FOR_SNAPSHOT = 1, CP_VERTICAL_EXPOSURE = 2, CP_VERTICAL_FRAME_START_BLANKING = 3, CP_VERTICAL_ACTIVE = 4, CP_VERTICAL_FRAME_END_BLANKING = 5, CP_VERTICAL_BLANKING = 6, CP_VERTICAL_BLANKING_4 = 7; reg [ 3:0 ] cp_vertical_state; localparam CP_HORIZONTAL_ACTIVE = 0, CP_HORIZONTAL_BLANKING = 1; reg cp_horizontal_state; reg pclk_previous; function [15:0] pixel_grid( input [XWidth-1:0] x, input [YWidth-1:0] y ); pixel_grid = (( x == 0 ) || ( y == 0 ) || (x == cp_window_width - 1 ) || ( y == cp_window_height - 1 ) || ( x[2:0] == 0 ) || ( y[2:0] == 0 ) ) ? { 5'H1F, 6'H3F, 5'H1F } : { 5'H03, 6'H07, 5'H03 }; endfunction localparam HorizontalCounterInit = Width - 1; always @( posedge clock ) begin if ( reset ) begin cp_vs <= 0; cp_hs <= 0; cp_d <= 0; // cp_trigger <= 0; cp_led <= 0; window_x <= 0; window_y <= 0; image_x <= 0; image_y <= 0; cp_vertical_state <= CP_VERTICAL_IDLE; cp_horizontal_state <= CP_HORIZONTAL_ACTIVE; cp_horizontal_counter <= 0; cp_vertical_counter <= 0; end else begin // keep track of pclk pclk_previous <= pclk; // falling edge of pclk if ( pclk_previous && !pclk ) begin case ( cp_vertical_state ) CP_VERTICAL_IDLE: begin if ( running ) begin if ( cp_snapshot_mode ) begin cp_vertical_state <= CP_VERTICAL_WAIT_FOR_SNAPSHOT; end else begin cp_vertical_counter <= cp_exposure - 2; cp_vertical_state <= CP_VERTICAL_EXPOSURE; cp_led <= 1; end end end CP_VERTICAL_WAIT_FOR_SNAPSHOT: if ( trigger ) begin cp_vertical_counter <= cp_exposure - 2; cp_vertical_state <= CP_VERTICAL_EXPOSURE; cp_led <= 1; end CP_VERTICAL_EXPOSURE: if ( cp_vertical_counter_expired ) begin cp_led <= 0; window_x <= 0; window_y <= 0; image_x <= 0; image_y <= 0; cp_vs <= ( cp_row_start == 0 ); cp_horizontal_counter <= cp_horizontal_blanking - FrameEndBlanking - 2; cp_vertical_state <= CP_VERTICAL_FRAME_START_BLANKING; cp_d <= 0; end else begin cp_vertical_counter <= cp_vertical_counter - 1; end CP_VERTICAL_FRAME_START_BLANKING: begin if ( cp_horizontal_counter_expired ) begin cp_horizontal_counter <= HorizontalCounterInit; cp_horizontal_state <= CP_HORIZONTAL_ACTIVE; cp_vertical_state <= CP_VERTICAL_ACTIVE; cp_vertical_counter <= Height - 2; if ( cp_vs && ( cp_column_start == 0 ) ) begin cp_d <= pixel_grid( image_x, image_y ); cp_hs <= 1; end else begin cp_d <= 0; end end else begin cp_horizontal_counter <= cp_horizontal_counter - 1; end end CP_VERTICAL_ACTIVE: // 4 case ( cp_horizontal_state ) CP_HORIZONTAL_ACTIVE: begin if ( cp_horizontal_counter_expired ) begin cp_d <= 0; window_x <= 0; image_x <= 0; cp_hs <= 0; cp_horizontal_state <= CP_HORIZONTAL_BLANKING; cp_horizontal_counter <= cp_horizontal_blanking - 2; end else begin if ( cp_hs ) begin if ( image_x == cp_window_width - 1 ) begin cp_hs <= 0; cp_d <= 0; end else begin cp_d <= pixel_grid( image_x + 1, image_y ); end image_x <= image_x + 1; end else begin cp_d <= 0; if ( cp_vs && ( window_x == cp_column_start ) ) begin cp_hs <= 1; cp_d <= pixel_grid( image_x + 1, image_y ); image_x <= 0; end end window_x <= window_x + 1; cp_horizontal_counter <= cp_horizontal_counter - 1; end end CP_HORIZONTAL_BLANKING: begin if ( cp_horizontal_counter_expired ) begin cp_horizontal_counter <= HorizontalCounterInit; cp_horizontal_state <= CP_HORIZONTAL_ACTIVE; if ( cp_vertical_counter_expired ) begin cp_d <= 0; cp_vs <= 0; image_y <= 0; window_x <= 0; window_y <= 0; cp_vertical_state <= CP_VERTICAL_FRAME_END_BLANKING; cp_horizontal_counter <= FrameEndBlanking; end else begin // prepare for the next row if ( cp_vs ) begin image_y <= image_y + 1; if ( image_y == cp_window_height - 1 ) begin cp_vs <= 0; end else begin if ( ( cp_column_start == 0 ) ) begin cp_d <= pixel_grid( image_x, image_y ); cp_hs <= 1; end else begin cp_d <= 0; end end end else begin cp_d <= 0; if ( window_y == cp_row_start - 1 ) begin cp_vs <= 1; end end window_y <= window_y + 1; cp_vertical_counter <= cp_vertical_counter - 1; end end else begin cp_horizontal_counter <= cp_horizontal_counter - 1; end end endcase CP_VERTICAL_FRAME_END_BLANKING: begin if ( cp_horizontal_counter_expired ) begin cp_vs <= 0; cp_hs <= 0; cp_horizontal_state <= CP_HORIZONTAL_ACTIVE; cp_horizontal_counter <= HorizontalCounterInit; cp_vertical_state <= CP_VERTICAL_BLANKING; cp_vertical_counter <= cp_vertical_blanking; end else begin cp_horizontal_counter <= cp_horizontal_counter - 1; end end CP_VERTICAL_BLANKING: // 6 case ( cp_horizontal_state ) CP_HORIZONTAL_ACTIVE: begin if ( cp_horizontal_counter_expired ) begin cp_horizontal_state <= CP_HORIZONTAL_BLANKING; cp_horizontal_counter <= cp_horizontal_blanking - 2; end else begin cp_horizontal_counter <= cp_horizontal_counter - 1; end end CP_HORIZONTAL_BLANKING: begin if ( cp_horizontal_counter_expired ) begin cp_horizontal_counter <= HorizontalCounterInit; cp_horizontal_state <= CP_HORIZONTAL_ACTIVE; if ( cp_vertical_counter_expired ) begin cp_vertical_counter <= 4 - 2; cp_vertical_state <= CP_VERTICAL_BLANKING_4; end else begin if ( cp_row_start == 0 ) cp_vs <= 1; cp_vertical_counter <= cp_vertical_counter - 1; end end else begin cp_horizontal_counter <= cp_horizontal_counter - 1; end end endcase CP_VERTICAL_BLANKING_4: begin if ( cp_vertical_counter_expired ) begin if ( cp_snapshot_mode ) begin cp_vertical_state <= CP_VERTICAL_WAIT_FOR_SNAPSHOT; end else begin cp_vs <= 1; cp_vertical_counter <= cp_horizontal_blanking - FrameEndBlanking - 2; cp_horizontal_counter <= HorizontalCounterInit; cp_horizontal_state <= CP_HORIZONTAL_ACTIVE; cp_vertical_state <= CP_VERTICAL_FRAME_START_BLANKING; // cp_state <= CP_VERTICAL_FRAME_START_BLANKING; // that can't be good end end else begin cp_vertical_counter <= cp_vertical_counter - 1; end end endcase // vertical state end end end endmodule
module uart_out #( parameter PipeSpec = `PS_DATA( 8 ), parameter ClockFrequency = 12000000, parameter BaudRate = 9600 ) ( input clock, input reset, inout [`P_w(PipeSpec)-1:0] pipe_in, output pin_tx ); wire [`P_Data_w(PipeSpec)-1:0] in_data; wire in_valid; wire in_ready; p_unpack_data #( .PipeSpec( PipeSpec ) ) in_unpack_d ( pipe_in, in_data); p_unpack_valid_ready #( .PipeSpec( PipeSpec ) ) in_unpack_vr( pipe_in, in_valid, in_ready ); // start and stop signals are ignored - packetization has to be escaped uart_out_np #( .ClockFrequency( ClockFrequency ), .BaudRate( BaudRate ) ) u_o_np ( clock, reset, in_data, in_valid, in_ready, pin_tx ); endmodule
module uart_out_np #( parameter ClockFrequency = 12000000, parameter BaudRate = 9600 )( input clock, input reset, input [7:0] out_data, input out_valid, output out_ready, output uart_tx ); // Assert out_valid for (at least) one clock cycle to start transmission of out_data // out_data is latched so that it doesn't have to stay valid while it is being sent generate if( ClockFrequency < BaudRate * 8 && ( ClockFrequency % BaudRate != 0 ) ) ASSERTION_ERROR PARAMETER_OUT_OF_RANGE("Frequency incompatible with requested BaudRate rate"); endgenerate `ifdef SIMULATION wire BitTick = 1'b1; // output one bit per clock cycle `else wire BitTick; uart_out_baudrate_gen #( ClockFrequency, BaudRate ) tickgen( .clock( clock ), .enable( ~out_ready ), .tick( BitTick ) ); `endif reg [3:0] uart_state = 0; wire uart_ready = (uart_state==0); assign out_ready = uart_ready; reg [7:0] uart_shift = 0; always @(posedge clock) begin if ( reset ) begin uart_state <= 0; end else begin if( uart_ready & out_valid ) uart_shift <= out_data; else if(uart_state[3] & BitTick) uart_shift <= (uart_shift >> 1); case(uart_state) 4'b0000: if(out_valid) uart_state <= 4'b0100; 4'b0100: if(BitTick) uart_state <= 4'b1000; // start bit 4'b1000: if(BitTick) uart_state <= 4'b1001; // bit 0 4'b1001: if(BitTick) uart_state <= 4'b1010; // bit 1 4'b1010: if(BitTick) uart_state <= 4'b1011; // bit 2 4'b1011: if(BitTick) uart_state <= 4'b1100; // bit 3 4'b1100: if(BitTick) uart_state <= 4'b1101; // bit 4 4'b1101: if(BitTick) uart_state <= 4'b1110; // bit 5 4'b1110: if(BitTick) uart_state <= 4'b1111; // bit 6 4'b1111: if(BitTick) uart_state <= 4'b0010; // bit 7 4'b0010: if(BitTick) uart_state <= 4'b0000; // stop1 - state<=4'b0011 for stop2 4'b0011: if(BitTick) uart_state <= 4'b0000; // stop2 default: if(BitTick) uart_state <= 4'b0000; endcase end end assign uart_tx = (uart_state<4) | (uart_state[3] & uart_shift[0]); // put together the start, data and stop bits endmodule
module uart_out_baudrate_gen #( parameter ClockFrequency = 12000000, parameter BaudRate = 9600, parameter Oversampling = 1 )( input clock, enable, output tick // generate a tick at the specified baud rate * oversampling ); // A quicky for an int log2 function integer log2(input integer v); begin log2=0; while(v>>log2) log2=log2+1; end endfunction localparam Count = (ClockFrequency/BaudRate); // for the oversampling = 1. Um... I don't know for what. localparam CountWidth = log2(Count) + 2; // don't want to accidentally fill it with a load! reg [CountWidth-1:0] Counter = 0; always @(posedge clock) if( !enable ) Counter <= Count - Oversampling - Oversampling - 1; else if ( Counter[CountWidth-1] ) Counter <= Counter + Count - Oversampling; else Counter <= Counter - Oversampling; assign tick = Counter[CountWidth-1]; endmodule
module uart_baudrate_gen_Orig( input clock, enable, output tick // generate a tick at the specified baud rate * oversampling ); parameter ClockFrequency = 25000000; parameter BaudRate = 115200; parameter Oversampling = 1; // A quicky for an int log2 function integer log2(input integer v); begin log2=0; while(v>>log2) log2=log2+1; end endfunction localparam AccWidth = log2(ClockFrequency/BaudRate)+8; // +/- 2% max timing error over a byte reg [AccWidth:0] Acc = 0; localparam ShiftLimiter = log2(BaudRate*Oversampling >> (31-AccWidth)); // this makes sure Inc calculation doesn't overflow localparam Inc = ((BaudRate*Oversampling << (AccWidth-ShiftLimiter))+(ClockFrequency>>(ShiftLimiter+1)))/(ClockFrequency>>ShiftLimiter); localparam ActualCounter = (1<<AccWidth); localparam ActualDivider = ActualCounter/Inc; localparam ActualErrorCounts = Inc*ActualDivider-ActualCounter; localparam ActualErrorPercentage = 100 * ActualErrorCounts / ActualCounter; always @(posedge clock) if(enable) Acc <= Acc[AccWidth-1:0] + Inc[AccWidth:0]; else Acc <= Inc[AccWidth:0]; assign tick = Acc[AccWidth]; endmodule
module uart_in #( parameter PipeSpec = `PS_DATA( 8 ), parameter ClockFrequency = 12000000, parameter BaudRate = 9600 ) ( input clock, input reset, inout [`P_m(PipeSpec):0] pipe_out, input pin_rx ); wire [`P_Data_w(PipeSpec)-1:0] out_data; wire out_valid; wire out_ready; uart_in_np #( .ClockFrequency( ClockFrequency ), .BaudRate( BaudRate ) ) u_i_np ( .clock( clock ), .reset( reset ), .in_data( out_data ), .in_valid( out_valid ), .in_ready( out_ready ), .uart_rx( pin_rx ) ); p_pack_data #( .PipeSpec( PipeSpec ) ) out_pack_d ( out_data, pipe_out ); p_pack_valid_ready #( .PipeSpec( PipeSpec ) ) out_pack_vr( out_valid, out_ready, pipe_out ); endmodule
module uart_in_np #( parameter ClockFrequency = 12000000, parameter BaudRate = 9600, parameter Oversampling = 8 )( input clock, input reset, output reg [7:0] in_data = 0, // data received, valid only (for one clock cycle) when in_ready is asserted output reg in_valid = 0, input in_ready, // We also detect if a gap occurs in the received stream of characters // That can be useful if multiple characters are sent in burst // so that multiple characters can be treated as a "packet" output uart_idle, // asserted when no data has been received for a while output reg uart_endofpacket = 0, // asserted for one clock cycle when a packet has been detected (i.e. uart_idle is going high) input uart_rx ); reg [7:0] in_data_build; // we oversample the uart_rx line at a fixed rate to capture each uart_rx data bit at the "right" time // 8 times oversampling by default, use 16 for higher quality reception generate if( ClockFrequency < BaudRate * Oversampling ) ASSERTION_ERROR PARAMETER_OUT_OF_RANGE("Frequency too low for current BaudRate rate and oversampling"); if( Oversampling < 8 || ((Oversampling & (Oversampling-1))!=0)) ASSERTION_ERROR PARAMETER_OUT_OF_RANGE("Invalid oversampling value"); endgenerate //////////////////////////////// reg [3:0] uart_state = 0; `ifdef SIMULATION wire uart_bit = uart_rx; wire sampleNow = 1'b1; // receive one bit per clock cycle `else wire OversamplingTick; uart_in_baudrate_gen #(ClockFrequency, BaudRate, Oversampling) tickgen(.clock(clock), .enable(1'b1), .tick(OversamplingTick)); // synchronize uart_rx to our clock domain reg [1:0] uart_sync = 2'b11; always @(posedge clock) if(OversamplingTick) uart_sync <= {uart_sync[0], uart_rx}; // and filter it reg [1:0] Filter_cnt = 2'b11; reg uart_bit = 1'b1; always @(posedge clock) if(OversamplingTick) begin if(uart_sync[1]==1'b1 && Filter_cnt!=2'b11) Filter_cnt <= Filter_cnt + 1'd1; else if(uart_sync[1]==1'b0 && Filter_cnt!=2'b00) Filter_cnt <= Filter_cnt - 1'd1; if(Filter_cnt==2'b11) uart_bit <= 1'b1; else if(Filter_cnt==2'b00) uart_bit <= 1'b0; end // and decide when is the good time to sample the uart_rx line function integer log2(input integer v); begin log2=0; while(v>>log2) log2=log2+1; end endfunction localparam l2o = log2(Oversampling); reg [l2o-2:0] OversamplingCnt = 0; always @(posedge clock) if(OversamplingTick) OversamplingCnt <= (uart_state==0) ? 1'd0 : OversamplingCnt + 1'd1; wire sampleNow = OversamplingTick && (OversamplingCnt==Oversampling/2-1); `endif // now we can accumulate the uart_rx bits in a shift-register always @(posedge clock) if ( reset ) begin uart_state <= 0; end else begin case(uart_state) 4'b0000: if(~uart_bit) uart_state <= `ifdef SIMULATION 4'b1000 `else 4'b0001 `endif; // start bit found? 4'b0001: if(sampleNow) uart_state <= 4'b1000; // sync start bit to sampleNow 4'b1000: if(sampleNow) uart_state <= 4'b1001; // bit 0 4'b1001: if(sampleNow) uart_state <= 4'b1010; // bit 1 4'b1010: if(sampleNow) uart_state <= 4'b1011; // bit 2 4'b1011: if(sampleNow) uart_state <= 4'b1100; // bit 3 4'b1100: if(sampleNow) uart_state <= 4'b1101; // bit 4 4'b1101: if(sampleNow) uart_state <= 4'b1110; // bit 5 4'b1110: if(sampleNow) uart_state <= 4'b1111; // bit 6 4'b1111: if(sampleNow) uart_state <= 4'b0010; // bit 7 4'b0010: if(sampleNow) uart_state <= 4'b0000; // stop bit default: uart_state <= 4'b0000; endcase end always @(posedge clock) if(sampleNow && uart_state[3]) in_data_build <= {uart_bit, in_data_build[7:1]}; //reg in_data_error = 0; always @(posedge clock) begin if ( sampleNow && uart_state==4'b0010 && uart_bit ) begin in_valid <= 1; in_data <= in_data_build; end else begin if ( in_ready ) begin in_valid <= 0; in_data <= 0; end end //in_data_error <= (sampleNow && uart_state==4'b0010 && ~uart_bit); // error if a stop bit is not received end `ifdef SIMULATION assign uart_idle = 0; `else reg [l2o+1:0] GapCnt = 0; always @(posedge clock) if (uart_state!=0) GapCnt<=0; else if(OversamplingTick & ~GapCnt[log2(Oversampling)+1]) GapCnt <= GapCnt + 1'h1; assign uart_idle = GapCnt[l2o+1]; always @(posedge clock) uart_endofpacket <= OversamplingTick & ~GapCnt[l2o+1] & &GapCnt[l2o:0]; `endif endmodule
module i2c_master_core #( parameter PipeSpec = `PS_d8, parameter ClockCount = 200 ) ( input clock, input reset, input [`P_Data_w(PipeSpec)-1:0] slave_address, // slave address, or -1 for in pipe (extra bit for the -1) input [`P_Data_w(PipeSpec):0] read_count, // read count, or -1 for in pipe (extra bit for the -1) input [2:0] operation, // 0 write, 1 read, 2 write read, -1 in pipe (extra bit for the -1) input send_address, // send the address out of the pipe_out input send_operation, // send the operation out of the pipe_out input send_write_count, // send the write count out of the pipe_out input start_operation, // start read operation (needed if everything else is spec'ed by port) output complete, // operation is complete output error, // operation error occurred output [`P_Data_w(PipeSpec)-1:0] write_count, // write count inout [`P_w(PipeSpec)-1:0] pipe_in, inout [`P_w(PipeSpec)-1:0] pipe_out, output reg [0:0] scl_out, input scl_in, output reg [0:0] sda_out, input sda_in, output [7:0] debug ); // `PS_MustHaveStartStop( PipeSpec ); // Weird error here means the supplied pipe doesn't have Start and Stop. Sorry. // `PS_MustHaveData( PipeSpec ); // Weird error here means the supplied pipe doesn't have Data. Sorry. localparam OperationWrite = 0; localparam OperationRead = 1; localparam OperationWriteRead = 2; localparam OperationInPipe = -1; localparam ClockCountWidth = $clog2( ClockCount + 1 ) + 1; reg [ClockCountWidth:0] clock_counter; wire clock_counter_expired = clock_counter[ ClockCountWidth ]; localparam DataWidth = `P_Data_w( PipeSpec ); localparam AddressWidth = DataWidth - 1; localparam BitCounterWidth = $clog2( DataWidth + 1 ) + 1; reg [BitCounterWidth-1:0] bit_counter; wire bit_counter_expired = bit_counter[ BitCounterWidth -1 ]; // slave address in pipe (-1) wire slave_address_in_pipe = slave_address[ AddressWidth ]; // operation in pipe (-1) wire operation_in_pipe = operation[ 2 ]; // operation in pipe (-1) wire read_count_in_pipe = read_count[ DataWidth ]; // // Pipes // wire in_start; wire in_stop; wire [DataWidth-1:0] in_data; wire in_valid; wire in_ready; p_unpack_start_stop #( .PipeSpec( PipeSpec ) ) p_up_ss( .pipe(pipe_in), .start( in_start), .stop( in_stop) ); p_unpack_data #( .PipeSpec( PipeSpec ) ) p_up_d( .pipe(pipe_in), .data( in_data) ); p_unpack_valid_ready #( .PipeSpec( PipeSpec ) ) p_up_vr( .pipe(pipe_in), .valid( in_valid), .ready( in_ready) ); wire out_start; wire out_stop; wire [DataWidth-1:0] out_data; wire out_valid; wire out_ready; p_pack_ssdvrp #( .PipeSpec( PipeSpec ) ) out_pack( .start(out_start), .stop(out_stop), .data(out_data), .valid(out_valid), .ready(out_ready), .pipe(pipe_out) ); // // Internals // reg scl_in_1; reg sda_in_1; always @(posedge clock) begin scl_in_1 <= scl_in; sda_in_1 <= sda_in; end reg [DataWidth-1:0] transfer_word; // reg [OutCountWidth:0] out_count; localparam I2CM_IDLE = 0, I2CM_ADDRESS = 1, I2CM_OPERATION = 2, I2CM_COUNT = 3, I2CM_START_TRIGGER = 4, I2CM_START = 5, I2CM_BITS = 6, I2CM_CLOCK_UP = 7, I2CM_CLOCK_DOWN = 8, I2CM_ACK_BIT = 9, I2CM_ACK_CLOCK_UP = 10, I2CM_ACK_CLOCK_DOWN = 11, I2CM_NEXT = 12, I2CM_REPORT_A = 13, I2CM_REPORT_B = 14, I2CM_DRAIN = 15, I2CM_ENDING1 = 16, I2CM_ENDING2 = 17, I2CM_STOP = 18; reg [4:0] i2cm_state; localparam I2CM_FUNCTION_IDLE = 0, I2CM_FUNCTION_ADDRESS = 1, I2CM_FUNCTION_COUNT = 2, I2CM_FUNCTION_READING = 3, I2CM_FUNCTION_WRITING = 4; reg [2:0] i2cm_function; // For the frontend, states in which the module will consume incoming pipe data assign in_ready = ( i2cm_state == I2CM_ADDRESS ) || ( i2cm_state == I2CM_OPERATION ) || ( i2cm_state == I2CM_COUNT ) || ( ( i2cm_state == I2CM_NEXT ) && !in_start ) || ( i2cm_state == I2CM_DRAIN ); reg i2cm_ack; reg i2cm_start_required; reg i2cm_stop; reg [DataWidth-1:0] i2cm_address; reg [DataWidth-1:0] i2cm_word_counter; reg [DataWidth-1:0] i2cm_read_count; reg [DataWidth-1:0] i2cm_write_count; reg i2cm_complete; reg i2cm_error; reg i2cm_out_start; reg i2cm_out_stop; reg [DataWidth-1:0] i2cm_out_data; reg i2cm_out_valid; wire i2cm_out_ready; reg i2cm_read; // Is the backend ready? wire out_be_ready; always @(posedge clock) begin if ( reset ) begin clock_counter <= 0; scl_out <= 1; sda_out <= 1; i2cm_ack <= 0; i2cm_start_required <= 0; i2cm_stop <= 0; i2cm_state <= I2CM_IDLE; i2cm_function <= I2CM_FUNCTION_IDLE; i2cm_out_start <= 0; i2cm_out_stop <= 0; i2cm_out_data <= 0; i2cm_out_valid <= 0; i2cm_word_counter <= 0; i2cm_read_count <= 0; i2cm_read <= 0; i2cm_write_count <= 0; i2cm_complete <= 0; i2cm_error <= 0; end else begin case ( i2cm_state ) I2CM_IDLE: begin // 0 - ouch these first few states could be more compact if ( ( in_valid && in_start ) || start_operation ) begin i2cm_complete <= 0; i2cm_error <= 0; clock_counter <= ( ClockCount >> 2 ) - 'H2; i2cm_start_required <= 1; i2cm_function <= I2CM_FUNCTION_ADDRESS; if ( slave_address_in_pipe ) begin // address will come from the pipe i2cm_state <= I2CM_ADDRESS; end else begin i2cm_address <= slave_address[ DataWidth-2:0]; if ( operation_in_pipe ) begin // operation will come from the the pipe i2cm_state <= I2CM_OPERATION; end else begin // operation is specified by port // Now we're in the slightly odd place that it must have // been some data or start operation that caused this operation if ( operation == OperationRead ) begin // the triggering data was a count. Build the address with the operation transfer_word <= { slave_address[ DataWidth-2:0 ], 1'H1 }; // we need a count before we can start i2cm_read <= 1; if ( read_count_in_pipe ) begin i2cm_state <= I2CM_COUNT; end else begin sda_out <= 0; i2cm_read_count <= read_count; i2cm_state <= I2CM_START; i2cm_stop <= 1; end end else begin // Write (or Write/Read) // the data will be the data that needs to be written // build the address byte transfer_word <= { slave_address[ DataWidth-2:0 ], 1'H0 }; i2cm_state <= I2CM_START; i2cm_read <= 0; // this is it - start sda_out <= 0; end end end end end I2CM_ADDRESS: begin // 1 if ( in_valid && ( in_start == i2cm_start_required ) ) begin // grab the data if ( operation_in_pipe ) begin // operation is in-pipe, address needs to move over i2cm_address <= in_data[ DataWidth-1:1]; i2cm_read <= in_data[ 0 ]; transfer_word <= in_data; end else begin // operation is specified by port, address is not shifted i2cm_address <= in_data[ DataWidth-2:0]; transfer_word <= { in_data[ DataWidth-2:0 ], (operation == OperationRead) }; i2cm_read <= (operation == OperationRead); end // signal START sda_out <= 0; i2cm_ack <= 0; i2cm_start_required <= 0; // READ = 1, WRITE = 0 if ( ( (operation_in_pipe) && in_data[ 0 ] ) || ( operation == OperationRead ) ) begin // we need a count before we can start if ( read_count_in_pipe ) begin i2cm_state <= I2CM_COUNT; end else begin i2cm_read_count <= read_count; i2cm_state <= I2CM_START; i2cm_stop <= 1; end end else begin // just start i2cm_stop <= in_stop; i2cm_state <= I2CM_START; end end end I2CM_OPERATION: begin // 2 if ( in_valid && ( in_start == i2cm_start_required ) ) begin i2cm_read <= in_data[ 0 ]; // signal START sda_out <= 0; i2cm_ack <= 0; transfer_word <= { i2cm_address[ DataWidth-2:0 ], in_data[ 0 ] }; i2cm_start_required <= 0; // READ = 1, WRITE = 0 if ( in_data[ 0 ] ) begin if ( read_count_in_pipe ) begin i2cm_state <= I2CM_COUNT; end else begin i2cm_read_count <= read_count; i2cm_state <= I2CM_START; i2cm_stop <= 1; end end else begin // just start i2cm_stop <= in_stop; i2cm_state <= I2CM_START; end end end I2CM_COUNT: begin // 3 if ( in_valid && ( in_start == i2cm_start_required ) ) begin // grab the count - and store it -2 since we terminate when the count is -1 sda_out <= 0; i2cm_read_count <= in_data; i2cm_state <= I2CM_START; i2cm_stop <= 1; end end // Not used. I2CM_START_TRIGGER: begin // 4 if ( start_operation ) i2cm_state <= I2CM_START; end I2CM_START: begin // 5 // Sitting with clock untouched & data lowered until if ( clock_counter_expired ) begin if ( ~i2cm_read ) i2cm_write_count <= 0; // end of start scl_out <= 0; i2cm_state <= I2CM_BITS; bit_counter <= DataWidth - 2; // DataWidth - 2 + 2; clock_counter <= ( ClockCount >> 2 ) - 'H2; end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_BITS: begin // 6 // make sure we're not sending if ( i2cm_out_valid ) begin i2cm_out_start <= 0; i2cm_out_stop <= 0; i2cm_out_data <= 0; i2cm_out_valid <= 0; end // Sitting with the clock lowered waiting to set data up if ( clock_counter_expired ) begin // new data // scl_out <= 0; // If we're writing, we'll want to set the outgoing data up if ( i2cm_function != I2CM_FUNCTION_READING ) begin sda_out <= transfer_word[ DataWidth -1 ]; transfer_word <= { transfer_word, 1'H0 }; end else begin sda_out <= 1; end i2cm_state <= I2CM_CLOCK_UP; clock_counter <= ( ClockCount >> 2 ) - 'H2; end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_CLOCK_UP: begin // 7 // sitting with the clock low and the data being set up if ( clock_counter_expired ) begin // clock the data in scl_out <= 1; // detect the stretch - will need a timeout here if ( scl_in_1 == 1 ) begin // Clock is definitely high again if ( i2cm_function == I2CM_FUNCTION_READING ) begin // transfer_word <= { transfer_word[ DataWidth-2:0], bit_counter[ 0 ] }; transfer_word <= { transfer_word[ DataWidth-2:0], sda_in_1 }; end // This stretch detecter takes ONE clock clock_counter <= ( ClockCount >> 1 ) - 'H3; i2cm_state <= I2CM_CLOCK_DOWN; end end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_CLOCK_DOWN: begin // 8 // sitting with the clock high and the data being valid if ( clock_counter_expired ) begin clock_counter <= ( ClockCount >> 2 ) - 'H2; scl_out <= 0; if ( bit_counter_expired ) begin i2cm_state <= I2CM_ACK_BIT; end else begin i2cm_state <= I2CM_BITS; bit_counter <= bit_counter - 1; end end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_ACK_BIT: begin // 9 // sitting with clock down until time passes // Prepare to read or write the ACK if ( clock_counter_expired ) begin clock_counter <= ( ClockCount >> 2 ) - 'H2; if ( i2cm_function != I2CM_FUNCTION_READING ) begin sda_out <= 1; end else begin // about to WRITE an ACK.. unless it's the last byte if ( i2cm_word_counter == ( i2cm_read_count - 1'H1 ) ) sda_out <= 1; else sda_out <= 0; end i2cm_state <= I2CM_ACK_CLOCK_UP; end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_ACK_CLOCK_UP: begin // 10 // sitting with the clock low and the data being set up // read the ACK if appropriate if ( clock_counter_expired ) begin clock_counter <= ( ClockCount >> 2 ) - 'H2; // clock the data in scl_out <= 1; // detect the stretch if ( scl_in_1 == 1 ) begin // Clock is definitely high again if ( i2cm_function != I2CM_FUNCTION_READING ) begin // read the ack if we're writing or doing an address i2cm_ack <= ~sda_in_1; end else begin // no line assertion //sda_out <= 1; end // don't hold data low it creates a STOP here // sda_out <= 0; // This stretch detecter takes ONE clock clock_counter <= ( ClockCount >> 1 ) - 'H3; i2cm_state <= I2CM_ACK_CLOCK_DOWN; end end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_ACK_CLOCK_DOWN: begin // 11 // sitting with the clock high and the data being valid if ( clock_counter_expired ) begin // what to do case ( i2cm_function ) I2CM_FUNCTION_ADDRESS: begin // drop the clock scl_out <= 0; i2cm_word_counter <= 0; clock_counter <= ( ClockCount >> 2 ) - 'H2; bit_counter <= DataWidth - 2; // DataWidth - 2 + 1; if ( i2cm_ack ) begin // got an ACK if ( i2cm_read ) begin if ( out_be_ready ) begin // got an ACK - a slave responded if ( send_address || send_operation ) begin i2cm_out_start <= 1; i2cm_out_stop <= 0; if ( send_address && send_operation ) i2cm_out_data <= { i2cm_address, 1'H1 }; else begin if ( send_address ) i2cm_out_data <= { 1'H0, i2cm_address }; else i2cm_out_data <= 1'H1; end i2cm_out_valid <= 1; end i2cm_state <= I2CM_BITS; // don't change this until we're out of here since we're using it to "case" above i2cm_function <= ( i2cm_read ) ? I2CM_FUNCTION_READING : I2CM_FUNCTION_WRITING; end end else begin // don't change this until we're out of here since we're using it to "case" above i2cm_function <= ( i2cm_read ) ? I2CM_FUNCTION_READING : I2CM_FUNCTION_WRITING; i2cm_state <= I2CM_NEXT; end end else begin // no ACK... need to abort // don't change this until we're out of here since we're using it to "case" above i2cm_function <= ( i2cm_read ) ? I2CM_FUNCTION_READING : I2CM_FUNCTION_WRITING; i2cm_error <= 1; if ( i2cm_stop ) begin // was no other word - write status i2cm_state <= I2CM_REPORT_A; end else begin // more words - drain them i2cm_state <= I2CM_DRAIN; end end end I2CM_FUNCTION_READING: begin // drop the clock scl_out <= 0; //if ( i2cm_ack ) begin if ( out_be_ready ) begin i2cm_out_start <= ( i2cm_word_counter == 0 ) && ~send_address && ~send_operation; i2cm_out_data <= transfer_word; i2cm_out_valid <= 1; i2cm_word_counter <= i2cm_word_counter + 1'H1; if ( i2cm_word_counter == ( i2cm_read_count - 1'H1 ) ) begin i2cm_out_stop <= 1; i2cm_complete <= 1; i2cm_state <= I2CM_ENDING1; end else begin i2cm_out_stop <= 0; transfer_word <= 0; i2cm_state <= I2CM_BITS; end clock_counter <= ( ClockCount >> 2 ) - 'H2; bit_counter <= DataWidth - 2; // DataWidth - 2 + 1; end //end else begin // i2cm_state <= I2CM_DRAIN; //end end I2CM_FUNCTION_WRITING: begin bit_counter <= DataWidth - 2; // DataWidth - 2 + 1; clock_counter <= ( ClockCount >> 2 ) - 'H2; scl_out <= 0; if ( i2cm_ack ) i2cm_word_counter <= i2cm_word_counter + 1; else i2cm_error <= 1; // This is critical... no stop and the module just waits for the next character if ( i2cm_stop ) begin // the last word had a "stop" - the write is complete i2cm_state <= I2CM_REPORT_A; i2cm_complete <= 1; end else begin if ( ~i2cm_ack ) begin i2cm_error <= 1; i2cm_state <= I2CM_DRAIN; end else begin i2cm_state <= I2CM_NEXT; end end end endcase end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_NEXT: begin // 12 // here is where we might detect a new operation... // but this is ill conceived and really needs support from the operation field (WriteRead) // So I'm removing the repeated start logic and the test cases that need it if ( in_valid ) begin // || start_operation) begin if ( in_start ) begin // || start_operation ) begin // famous repeated start // the front end doesn't grab the character if start is selected // BUT may need to write out the write report // sda_out <= 1; i2cm_state <= I2CM_REPORT_A; clock_counter <= ( ClockCount >> 2 ) - 'H3; end else begin scl_out <= 0; transfer_word <= in_data; i2cm_stop <= in_stop; i2cm_state <= I2CM_BITS; clock_counter <= ( ClockCount >> 2 ) - 'H3; // (one fewer clocks) end end end I2CM_REPORT_A: begin // 13 // output the word count i2cm_write_count <= i2cm_word_counter; if ( out_be_ready ) begin // We may need to send other stuff - like address, etc. if ( send_address ) begin if ( send_operation ) begin i2cm_out_data <= { i2cm_address, i2cm_read }; end else begin i2cm_out_data <= { 1'H0, i2cm_address }; end i2cm_out_start <= 1; i2cm_out_valid <= 1; end else begin if ( send_operation ) begin i2cm_out_start <= 1; i2cm_out_data <= i2cm_read; i2cm_out_valid <= 1; end end // only flag stop if we are not reading, or we are writing, but not sending a count i2cm_out_stop = ( i2cm_read && i2cm_error ) || ( ~i2cm_read && ~send_write_count ); if ( i2cm_function == I2CM_FUNCTION_READING ) begin // i2cm_out_stop <= 1; i2cm_state <= I2CM_ENDING1; end else begin // i2cm_out_stop <= 0; i2cm_state <= I2CM_REPORT_B; end end end I2CM_REPORT_B: begin // 14 // complete the word count if ( i2cm_out_valid ) begin i2cm_out_start <= 0; i2cm_out_stop <= 0; i2cm_out_data <= 0; i2cm_out_valid <= 0; end else begin if ( !send_write_count ) begin i2cm_state <= I2CM_ENDING1; end else begin if ( out_be_ready ) begin i2cm_out_start <= ( ~send_address && ~send_operation ); i2cm_out_data <= i2cm_word_counter; i2cm_out_valid <= 1; i2cm_out_stop <= 1; i2cm_state <= I2CM_ENDING1; end end end end I2CM_DRAIN: begin // 15 // grab any incoming characters until the stop. if ( ~in_valid || ( in_valid && in_stop ) || i2cm_stop ) begin i2cm_state <= I2CM_REPORT_A; end end I2CM_ENDING1: begin // 16 i2cm_function <= I2CM_FUNCTION_IDLE; if ( i2cm_out_valid ) begin i2cm_out_start <= 0; i2cm_out_stop <= 0; i2cm_out_data <= 0; i2cm_out_valid <= 0; end // sitting with the clock low (?) and NO data begin set up if ( clock_counter_expired ) begin if ( ( in_valid && in_start ) ) // || start_operation ) sda_out <= 1; else sda_out <= 0; i2cm_state <= I2CM_ENDING2; clock_counter <= ( ClockCount >> 2 ) - 'H2; end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_ENDING2: begin // 17 // sitting with the clock low and NO data begin set up if ( clock_counter_expired ) begin scl_out <= 1; if ( scl_in_1 ) begin i2cm_state <= I2CM_STOP; clock_counter <= ( ClockCount >> 2 ) - 'H2; end end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end I2CM_STOP: begin // 18 if ( clock_counter_expired ) begin sda_out <= 1; i2cm_state <= I2CM_IDLE; end else begin clock_counter <= clock_counter - (clock_counter_expired ? 0 : 1 ); end end default: begin i2cm_state <= I2CM_IDLE; end endcase // case ( master_state ) // endcase end end localparam I2CM_BE_IDLE = 0, I2CM_BE_BUSY = 1; reg i2cm_be_state; reg i2cm_out_start_store; reg i2cm_out_stop_store; reg [DataWidth-1:0] i2cm_out_data_store; reg i2cm_out_valid_store; always @( posedge clock ) begin if ( reset ) begin i2cm_be_state <= I2CM_BE_IDLE; i2cm_out_start_store <= 0; i2cm_out_stop_store <= 0; i2cm_out_data_store <= 0; i2cm_out_valid_store <= 0; end else begin case ( i2cm_be_state ) I2CM_BE_IDLE: begin if ( i2cm_out_valid ) begin i2cm_out_start_store <= i2cm_out_start; i2cm_out_stop_store <= i2cm_out_stop; i2cm_out_data_store <= i2cm_out_data; i2cm_out_valid_store <= 1; i2cm_be_state <= I2CM_BE_BUSY; end end I2CM_BE_BUSY: begin if ( out_ready ) begin i2cm_out_start_store <= 0; i2cm_out_stop_store <= 0; i2cm_out_data_store <= 0; i2cm_out_valid_store <= 0; i2cm_be_state <= I2CM_BE_IDLE; end end endcase end end assign out_start = i2cm_out_start_store; assign out_stop = i2cm_out_stop_store; assign out_data = i2cm_out_data_store; assign out_valid = i2cm_out_valid_store; assign out_be_ready = ( i2cm_be_state == I2CM_BE_IDLE ); assign write_count = i2cm_write_count; assign complete = i2cm_complete; assign error = i2cm_error; assign debug[3:0] = i2cm_state; endmodule
module i2c_slave_core #( parameter Address = 7'H50, parameter PipeSpec = `PS_d8 ) ( input clock, input reset, inout [`P_w(PipeSpec)-1:0] pipe_in, inout [`P_w(PipeSpec)-1:0] pipe_out, output reg [0:0] scl_out, output scl_in, output reg [0:0] sda_out, input sda_in, output [7:0] debug ); // `PS_MustHaveStartStop( PipeSpec ); // `PS_MustHaveData( PipeSpec ); localparam DataWidth = `P_Data_w( PipeSpec ); localparam AddressWidth = DataWidth - 1; wire in_start; wire in_stop; wire [DataWidth-1:0] in_data; wire in_valid; wire in_ready; p_unpack_start_stop #( .PipeSpec( PipeSpec ) ) p_up_ss( .pipe(pipe_in), .start( in_start), .stop( in_stop) ); p_unpack_data #( .PipeSpec( PipeSpec ) ) p_up_d( .pipe(pipe_in), .data( in_data) ); p_unpack_valid_ready #( .PipeSpec( PipeSpec ) ) p_up_vr( .pipe(pipe_in), .valid( in_valid), .ready( in_ready) ); wire out_start; wire out_stop; wire [DataWidth-1:0] out_data; wire out_valid; wire out_ready; p_pack_ssdvrp #( .PipeSpec( PipeSpec ) ) out_pack( .start(out_start), .stop(out_stop), .data(out_data), .valid(out_valid), .ready(out_ready), .pipe(pipe_out) ); integer i; localparam I2CS_IDLE = 0, I2CS_START = 1, I2CS_TRANSFER_A = 2, I2CS_TRANSFER_B = 3, I2CS_TRANSFER_ACK_A = 4, I2CS_TRANSFER_ACK_B = 5, I2CS_NEXT = 6, I2CS_FINAL_OUT = 7, I2CS_FINAL_OUT_DONE = 8, I2CS_STOP = 9; reg [3:0] i2cs_state; localparam I2CS_FUNCTION_IDLE = 0, I2CS_FUNCTION_ADDRESS = 1, I2CS_FUNCTION_READING = 2, I2CS_FUNCTION_WRITING = 3; reg [1:0] i2cs_function; reg i2cs_address_match; reg [DataWidth-1:0] transfer_register; localparam BitCounterWidth = $clog2( DataWidth + 1 ) + 1; reg [BitCounterWidth-1:0] bit_counter; wire bit_counter_expired = bit_counter[ BitCounterWidth -1 ]; reg [DataWidth-1:0] transfer; // reg [OutCountWidth:0] out_count; // assign in_ready = ( i2cs_state == IDLE ); reg i2cs_scl_in_prev; reg i2cs_sda_in_prev; // Output registers reg i2cs_out_start; reg i2cs_out_stop; reg [DataWidth-1:0] i2cs_out_data; reg i2cs_out_valid; wire i2cs_out_ready; reg i2cs_ack; reg i2cs_started; wire out_be_ready; reg i2cs_out_first; assign in_ready = ( i2cs_state == I2CS_NEXT ); always @(posedge clock) begin if ( reset ) begin i2cs_out_start <= 0; i2cs_out_stop <= 0; i2cs_out_data <= 0; i2cs_out_valid <= 0; scl_out <= 1; sda_out <= 1; i2cs_scl_in_prev <= 1; i2cs_sda_in_prev <= 1; i2cs_state <= I2CS_IDLE; i2cs_function <= I2CS_FUNCTION_IDLE; i2cs_address_match <= 0; i2cs_out_first <= 1; i2cs_ack <= 0; i2cs_started <= 0; end else begin i2cs_sda_in_prev <= sda_in; i2cs_scl_in_prev <= scl_in; case ( i2cs_state ) I2CS_IDLE: begin // start is when data drops while clock is high if ( ~sda_in && i2cs_sda_in_prev && scl_in && i2cs_scl_in_prev ) begin i2cs_state <= I2CS_START; end end I2CS_START: begin if ( ~sda_in && ~scl_in ) begin i2cs_state <= I2CS_TRANSFER_A; bit_counter <= DataWidth - 2; transfer <= 0; i2cs_out_first <= 1; i2cs_function <= I2CS_FUNCTION_ADDRESS; end end I2CS_TRANSFER_A: begin // 2 if ( i2cs_out_valid ) begin i2cs_out_start <= 0; i2cs_out_start <= 0; i2cs_out_data <= 0; i2cs_out_valid <= 0; end // if ( scl_in && i2cs_scl_in_prev ) begin // // stop is when data goes up when clock is high // if ( sda_in && ~i2cs_sda_in_prev ) begin // i2cs_state <= I2CS_IDLE; // end // end if ( scl_in ) begin if ( i2cs_function != I2CS_FUNCTION_READING ) transfer <= { transfer[DataWidth-2:0], sda_in }; i2cs_state <= I2CS_TRANSFER_B; end end I2CS_TRANSFER_B: begin // 3 // here's where a STOP OR REPEATED START could happen if ( scl_in && i2cs_scl_in_prev ) begin // check for start - might be another start if ( ~sda_in && i2cs_sda_in_prev ) begin i2cs_started <= 1; if ( i2cs_function == I2CS_FUNCTION_WRITING ) begin i2cs_state <= I2CS_FINAL_OUT; end else begin // i2cs_state <= I2CS_START; i2cs_state <= I2CS_TRANSFER_A; bit_counter <= DataWidth - 2; transfer <= 0; i2cs_out_first <= 1; i2cs_function <= I2CS_FUNCTION_ADDRESS; end end else begin // stop is when data goes up when clock is high if ( ( sda_in && ~i2cs_sda_in_prev ) ) begin i2cs_started <= 0; if ( i2cs_function == I2CS_FUNCTION_WRITING ) begin i2cs_state <= I2CS_FINAL_OUT; end else begin i2cs_state <= I2CS_IDLE; end end end end else begin if ( ~scl_in ) begin if ( bit_counter_expired ) begin case ( i2cs_function ) I2CS_FUNCTION_ADDRESS: begin if ( transfer[ DataWidth-1:1] == Address ) begin i2cs_address_match <= 1; sda_out <= 0; end else begin i2cs_address_match <= 0; sda_out <= 1; end end I2CS_FUNCTION_WRITING: begin sda_out <= 0; end I2CS_FUNCTION_READING: begin sda_out <= 1; end endcase i2cs_state <= I2CS_TRANSFER_ACK_A; end else begin bit_counter <= bit_counter - 1; i2cs_state <= I2CS_TRANSFER_A; if ( i2cs_function == I2CS_FUNCTION_READING ) begin sda_out <= transfer_register[ DataWidth-1 ]; transfer_register <= { transfer_register[ DataWidth-2:0 ], 1'H0 }; end end end end end I2CS_TRANSFER_ACK_A: begin // 4 // wait for clock UP if ( scl_in ) begin i2cs_state <= I2CS_TRANSFER_ACK_B; if ( i2cs_function == I2CS_FUNCTION_READING ) i2cs_ack = ~sda_in; end end I2CS_TRANSFER_ACK_B: begin // 5 // wait for clock DOWN if ( ~scl_in ) begin // release the ack pulse on data sda_out <= 1; case ( i2cs_function ) I2CS_FUNCTION_ADDRESS: begin if ( i2cs_address_match ) begin i2cs_function <= ( transfer[ 0 ] ? I2CS_FUNCTION_READING : I2CS_FUNCTION_WRITING ); if ( transfer[ 0 ] ) begin // stomp on the clock in case there's no data ready //scl_out <= 0; i2cs_state <= I2CS_NEXT; end else begin bit_counter <= DataWidth - 2; i2cs_state <= I2CS_TRANSFER_A; end end else begin // no match - wait for the bus to be idle i2cs_state <= I2CS_STOP; end end I2CS_FUNCTION_READING: begin if ( i2cs_ack ) begin i2cs_state <= I2CS_NEXT; // drop that clock! We might not have data yet //scl_out <= 0; end else begin i2cs_state <= I2CS_IDLE; end end I2CS_FUNCTION_WRITING: begin if ( out_be_ready ) begin bit_counter <= DataWidth - 2; // write out... hold clock down if not ready // scl_out <= 0; i2cs_state <= I2CS_TRANSFER_A; scl_out <= 1; // release the ACK line sda_out <= 1; i2cs_out_start <= i2cs_out_first; i2cs_out_stop <= 0; i2cs_out_data <= transfer; i2cs_out_valid <= 1; i2cs_out_first <= 0; end else begin // hold the clock. This is a big deal. It could block the whole system. // Obviously there should be a timeout. scl_out <= 0; end end endcase end end I2CS_NEXT: begin // 6 if ( scl_in && i2cs_scl_in_prev ) begin // stop is when data goes up when clock is high if ( sda_in && ~i2cs_sda_in_prev ) begin i2cs_state <= I2CS_IDLE; end end else begin // check for start first time around if ( in_valid && ( in_start || ~i2cs_out_first ) ) begin scl_out <= 1; transfer_register <= { in_data[ DataWidth-2:0 ], 1'H0 }; sda_out <= in_data[ DataWidth-1 ]; i2cs_out_first <= 0; bit_counter <= DataWidth - 2; i2cs_state <= I2CS_TRANSFER_A; end end end I2CS_FINAL_OUT: begin // 7 if ( out_be_ready ) begin i2cs_out_start <= i2cs_out_first; i2cs_out_stop <= 1; i2cs_out_data <= 0; i2cs_out_valid <= 1; i2cs_state <= I2CS_FINAL_OUT_DONE; end end I2CS_FINAL_OUT_DONE: begin // 8 i2cs_out_start <= 0; i2cs_out_stop <= 0; i2cs_out_data <= 0; i2cs_out_valid <= 0; if ( i2cs_started ) begin i2cs_started <= 0; if ( scl_in ) i2cs_state <= I2CS_START; else begin i2cs_state <= I2CS_TRANSFER_A; bit_counter <= DataWidth - 2; transfer <= 0; i2cs_out_first <= 1; i2cs_function <= I2CS_FUNCTION_ADDRESS; end end else i2cs_state <= I2CS_IDLE; end I2CS_STOP: begin // confirm clock is high for either stop or repeated start if ( scl_in && i2cs_scl_in_prev ) begin // stop is when data goes up when clock is high if ( sda_in && ~i2cs_sda_in_prev ) begin i2cs_state <= I2CS_IDLE; end // repeated start is when data drops while clock is high if ( ~sda_in && i2cs_sda_in_prev ) begin i2cs_state <= I2CS_START; end end end endcase end end localparam I2CS_BE_IDLE = 0, I2CS_BE_BUSY = 1; reg i2cs_be_state; reg i2cs_out_start_store; reg i2cs_out_stop_store; reg [DataWidth-1:0] i2cs_out_data_store; reg i2cs_out_valid_store; always @( posedge clock ) begin if ( reset ) begin i2cs_be_state <= I2CS_BE_IDLE; i2cs_out_start_store <= 0; i2cs_out_stop_store <= 0; i2cs_out_data_store <= 0; i2cs_out_valid_store <= 0; end else begin case ( i2cs_be_state ) I2CS_BE_IDLE: begin if ( i2cs_out_valid ) begin i2cs_out_start_store <= i2cs_out_start; i2cs_out_stop_store <= i2cs_out_stop; i2cs_out_data_store <= i2cs_out_data; i2cs_out_valid_store <= 1; i2cs_be_state <= I2CS_BE_BUSY; end end I2CS_BE_BUSY: begin if ( out_ready ) begin i2cs_out_start_store <= 0; i2cs_out_stop_store <= 0; i2cs_out_data_store <= 0; i2cs_out_valid_store <= 0; i2cs_be_state <= I2CS_BE_IDLE; end end endcase end end assign out_start = i2cs_out_start_store; assign out_stop = i2cs_out_stop_store; assign out_data = i2cs_out_data_store; assign out_valid = i2cs_out_valid_store; assign out_be_ready = ( i2cs_be_state == I2CS_BE_IDLE ); assign debug[7:4] = i2cs_state; endmodule
module usb_fs_tx ( // A 48MHz clock is required to receive USB data at 12MHz // it's simpler to juse use 48MHz everywhere input clk_48mhz, input reset, // bit strobe from rx to align with senders clock input bit_strobe, // output enable to take ownership of bus and data out output reg oe = 0, output reg dp = 0, output reg dn = 0, // pulse to initiate new packet transmission input pkt_start, output pkt_end, // pid to send input [3:0] pid, // tx logic pulls data until there is nothing available input tx_data_avail, output reg tx_data_get = 0, input [7:0] tx_data ); wire clk = clk_48mhz; // save packet parameters at pkt_start reg [3:0] pidq = 0; always @(posedge clk) begin if (pkt_start) begin pidq <= pid; end end reg [7:0] data_shift_reg = 0; reg [7:0] oe_shift_reg = 0; reg [7:0] se0_shift_reg = 0; wire serial_tx_data = data_shift_reg[0]; wire serial_tx_oe = oe_shift_reg[0]; wire serial_tx_se0 = se0_shift_reg[0]; // serialize sync, pid, data payload, and crc16 reg byte_strobe = 0; reg [2:0] bit_count = 0; reg [4:0] bit_history_q = 0; wire [5:0] bit_history = {serial_tx_data, bit_history_q}; wire bitstuff = bit_history == 6'b111111; reg bitstuff_q = 0; reg bitstuff_qq = 0; reg bitstuff_qqq = 0; reg bitstuff_qqqq = 0; always @(posedge clk) begin bitstuff_q <= bitstuff; bitstuff_qq <= bitstuff_q; bitstuff_qqq <= bitstuff_qq; bitstuff_qqqq <= bitstuff_qqq; end assign pkt_end = bit_strobe && se0_shift_reg[1:0] == 2'b01; reg data_payload = 0; reg [31:0] pkt_state = 0; localparam IDLE = 0; localparam SYNC = 1; localparam PID = 2; localparam DATA_OR_CRC16_0 = 3; localparam CRC16_1 = 4; localparam EOP = 5; reg [15:0] crc16 = 0; always @(posedge clk) begin case (pkt_state) IDLE : begin if (pkt_start) begin pkt_state <= SYNC; end end SYNC : begin if (byte_strobe) begin pkt_state <= PID; data_shift_reg <= 8'b10000000; oe_shift_reg <= 8'b11111111; se0_shift_reg <= 8'b00000000; end end PID : begin if (byte_strobe) begin if (pidq[1:0] == 2'b11) begin pkt_state <= DATA_OR_CRC16_0; end else begin pkt_state <= EOP; end data_shift_reg <= {~pidq, pidq}; oe_shift_reg <= 8'b11111111; se0_shift_reg <= 8'b00000000; end end DATA_OR_CRC16_0 : begin if (byte_strobe) begin if (tx_data_avail) begin pkt_state <= DATA_OR_CRC16_0; data_payload <= 1; tx_data_get <= 1; data_shift_reg <= tx_data; oe_shift_reg <= 8'b11111111; se0_shift_reg <= 8'b00000000; end else begin pkt_state <= CRC16_1; data_payload <= 0; tx_data_get <= 0; data_shift_reg <= ~{crc16[8], crc16[9], crc16[10], crc16[11], crc16[12], crc16[13], crc16[14], crc16[15]}; oe_shift_reg <= 8'b11111111; se0_shift_reg <= 8'b00000000; end end else begin tx_data_get <= 0; end end CRC16_1 : begin if (byte_strobe) begin pkt_state <= EOP; data_shift_reg <= ~{crc16[0], crc16[1], crc16[2], crc16[3], crc16[4], crc16[5], crc16[6], crc16[7]}; oe_shift_reg <= 8'b11111111; se0_shift_reg <= 8'b00000000; end end EOP : begin if (byte_strobe) begin pkt_state <= IDLE; oe_shift_reg <= 8'b00000111; se0_shift_reg <= 8'b00000111; end end endcase if (bit_strobe && !bitstuff) begin byte_strobe <= (bit_count == 3'b000); end else begin byte_strobe <= 0; end if (pkt_start) begin bit_count <= 1; bit_history_q <= 0; end else if (bit_strobe) begin // bitstuff if (bitstuff /* && !serial_tx_se0*/) begin bit_history_q <= bit_history[5:1]; data_shift_reg[0] <= 0; // normal deserialize end else begin bit_count <= bit_count + 1; data_shift_reg <= (data_shift_reg >> 1); oe_shift_reg <= (oe_shift_reg >> 1); se0_shift_reg <= (se0_shift_reg >> 1); bit_history_q <= bit_history[5:1]; end end end // calculate crc16 wire crc16_invert = serial_tx_data ^ crc16[15]; always @(posedge clk) begin if (pkt_start) begin crc16 <= 16'b1111111111111111; end if (bit_strobe && data_payload && !bitstuff_qqqq && !pkt_start) begin crc16[15] <= crc16[14] ^ crc16_invert; crc16[14] <= crc16[13]; crc16[13] <= crc16[12]; crc16[12] <= crc16[11]; crc16[11] <= crc16[10]; crc16[10] <= crc16[9]; crc16[9] <= crc16[8]; crc16[8] <= crc16[7]; crc16[7] <= crc16[6]; crc16[6] <= crc16[5]; crc16[5] <= crc16[4]; crc16[4] <= crc16[3]; crc16[3] <= crc16[2]; crc16[2] <= crc16[1] ^ crc16_invert; crc16[1] <= crc16[0]; crc16[0] <= crc16_invert; end end reg [2:0] dp_eop = 0; // nrzi and differential driving always @(posedge clk) begin if (pkt_start) begin // J dp <= 1; dn <= 0; dp_eop <= 3'b100; end else if (bit_strobe) begin oe <= serial_tx_oe; if (serial_tx_se0) begin dp <= dp_eop[0]; dn <= 0; dp_eop <= dp_eop >> 1; end else if (serial_tx_data) begin // value should stay the same, do nothing end else begin dp <= !dp; dn <= !dn; end end end endmodule
module usb_fs_in_pe #( parameter NUM_IN_EPS = 11, parameter MAX_IN_PACKET_SIZE = 32 ) ( input clk, input reset, input [NUM_IN_EPS-1:0] reset_ep, input [6:0] dev_addr, //////////////////// // endpoint interface //////////////////// output reg [NUM_IN_EPS-1:0] in_ep_data_free = 0, input [NUM_IN_EPS-1:0] in_ep_data_put, input [7:0] in_ep_data, input [NUM_IN_EPS-1:0] in_ep_data_done, input [NUM_IN_EPS-1:0] in_ep_stall, output reg [NUM_IN_EPS-1:0] in_ep_acked = 0, //////////////////// // rx path //////////////////// // Strobed on reception of packet. input rx_pkt_start, input rx_pkt_end, input rx_pkt_valid, // Most recent packet received. input [3:0] rx_pid, input [6:0] rx_addr, input [3:0] rx_endp, input [10:0] rx_frame_num, //////////////////// // tx path //////////////////// // Strobe to send new packet. output reg tx_pkt_start = 0, input tx_pkt_end, // Packet type to send output reg [3:0] tx_pid = 0, // Data payload to send if any output tx_data_avail, input tx_data_get, output reg [7:0] tx_data, output [7:0] debug ); //////////////////////////////////////////////////////////////////////////////// // endpoint state machine //////////////////////////////////////////////////////////////////////////////// reg [1:0] ep_state [NUM_IN_EPS - 1:0]; reg [1:0] ep_state_next [NUM_IN_EPS - 1:0]; // latched on valid IN token reg [3:0] current_endp = 0; wire [1:0] current_ep_state = ep_state[current_endp][1:0]; localparam READY_FOR_PKT = 0; localparam PUTTING_PKT = 1; localparam GETTING_PKT = 2; localparam STALL = 3; assign debug[1:0] = ( current_endp == 1 ) ? current_ep_state : 0; //////////////////////////////////////////////////////////////////////////////// // in transfer state machine //////////////////////////////////////////////////////////////////////////////// localparam IDLE = 0; localparam RCVD_IN = 1; localparam SEND_DATA = 2; localparam WAIT_ACK = 3; reg [1:0] in_xfr_state = IDLE; reg [1:0] in_xfr_state_next; assign debug[3:2] = ( current_endp == 1 ) ? in_xfr_state : 0; reg in_xfr_start = 0; reg in_xfr_end = 0; assign debug[4] = tx_data_avail; assign debug[5] = tx_data_get; // data toggle state reg [NUM_IN_EPS - 1:0] data_toggle = 0; // endpoint data buffer reg [7:0] in_data_buffer [(MAX_IN_PACKET_SIZE * NUM_IN_EPS) - 1:0]; // Address registers - one bit longer (6) than required (5) to permit fullness != emptyness reg [5:0] ep_put_addr [NUM_IN_EPS - 1:0]; reg [5:0] ep_get_addr [NUM_IN_EPS - 1:0]; integer i = 0; initial begin for (i = 0; i < NUM_IN_EPS; i = i + 1) begin ep_put_addr[i] = 0; ep_get_addr[i] = 0; ep_state[i] = 0; end end reg [3:0] in_ep_num = 0; // the actual address (note using only the real 5 bits of the incoming address + the high order buffer select) wire [8:0] buffer_put_addr = {in_ep_num[3:0], ep_put_addr[in_ep_num][4:0]}; wire [8:0] buffer_get_addr = {current_endp[3:0], ep_get_addr[current_endp][4:0]}; // endpoint data packet buffer has a data packet ready to send reg [NUM_IN_EPS - 1:0] endp_ready_to_send = 0; // endpoint has some space free in its buffer reg [NUM_IN_EPS - 1:0] endp_free = 0; wire token_received = rx_pkt_end && rx_pkt_valid && rx_pid[1:0] == 2'b01 && rx_addr == dev_addr && rx_endp < NUM_IN_EPS; wire setup_token_received = token_received && rx_pid[3:2] == 2'b11; wire in_token_received = token_received && rx_pid[3:2] == 2'b10; wire ack_received = rx_pkt_end && rx_pkt_valid && rx_pid == 4'b0010; assign debug[ 6 ] = rx_pkt_start; assign debug[ 7 ] = rx_pkt_end; wire more_data_to_send = ep_get_addr[current_endp][5:0] < ep_put_addr[current_endp][5:0]; wire [5:0] current_ep_get_addr = ep_get_addr[current_endp][5:0]; wire [5:0] current_ep_put_addr = ep_put_addr[current_endp][5:0]; wire tx_data_avail_i = in_xfr_state == SEND_DATA && more_data_to_send; assign tx_data_avail = tx_data_avail_i; //////////////////////////////////////////////////////////////////////////////// // endpoint state machine //////////////////////////////////////////////////////////////////////////////// genvar ep_num; generate for (ep_num = 0; ep_num < NUM_IN_EPS; ep_num = ep_num + 1) begin // Manage next state always @* begin in_ep_acked[ep_num] <= 0; ep_state_next[ep_num] <= ep_state[ep_num]; if (in_ep_stall[ep_num]) begin ep_state_next[ep_num] <= STALL; end else begin case (ep_state[ep_num]) READY_FOR_PKT : begin ep_state_next[ep_num] <= PUTTING_PKT; end PUTTING_PKT : begin // if either the user says they're done or the buffer is full, move on to GETTING_PKT if ( ( in_ep_data_done[ep_num] ) || ( ep_put_addr[ep_num][5] ) ) begin ep_state_next[ep_num] <= GETTING_PKT; end else begin ep_state_next[ep_num] <= PUTTING_PKT; end end GETTING_PKT : begin // here we're waiting to send the data out, and receive an ACK token back // No token, and we're here for a while. if (in_xfr_end && current_endp == ep_num) begin ep_state_next[ep_num] <= READY_FOR_PKT; in_ep_acked[ep_num] <= 1; end else begin ep_state_next[ep_num] <= GETTING_PKT; end end STALL : begin if (setup_token_received && rx_endp == ep_num) begin ep_state_next[ep_num] <= READY_FOR_PKT; end else begin ep_state_next[ep_num] <= STALL; end end default begin ep_state_next[ep_num] <= READY_FOR_PKT; end endcase end endp_free[ep_num] = !ep_put_addr[ep_num][5]; in_ep_data_free[ep_num] = endp_free[ep_num] && ep_state[ep_num] == PUTTING_PKT; end // Handle the data pointer (advancing and clearing) always @(posedge clk) begin if (reset || reset_ep[ep_num]) begin ep_state[ep_num] <= READY_FOR_PKT; end else begin ep_state[ep_num] <= ep_state_next[ep_num]; case (ep_state[ep_num]) READY_FOR_PKT : begin // make sure we start with a clear buffer (and the extra bit!) ep_put_addr[ep_num][5:0] <= 0; end PUTTING_PKT : begin // each time we are putting, and there's a data_put signal, increment the address if (in_ep_data_put[ep_num] && ( ~ep_put_addr[ep_num][5] ) ) begin ep_put_addr[ep_num][5:0] <= ep_put_addr[ep_num][5:0] + 1; end end GETTING_PKT : begin end STALL : begin end endcase end end end endgenerate // Decide which in_ep_num we're talking to // Using the data put register is OK here integer ep_num_decoder; always @* begin in_ep_num <= 0; for (ep_num_decoder = 0; ep_num_decoder < NUM_IN_EPS; ep_num_decoder = ep_num_decoder + 1) begin if (in_ep_data_put[ep_num_decoder]) begin in_ep_num <= ep_num_decoder; end end end // Handle putting the new data into the buffer always @(posedge clk) begin case (ep_state[in_ep_num]) PUTTING_PKT : begin if (in_ep_data_put[in_ep_num] && !ep_put_addr[in_ep_num][5]) begin in_data_buffer[buffer_put_addr] <= in_ep_data; end end endcase end //////////////////////////////////////////////////////////////////////////////// // in transfer state machine //////////////////////////////////////////////////////////////////////////////// reg rollback_in_xfr; always @* begin in_xfr_state_next <= in_xfr_state; in_xfr_start <= 0; in_xfr_end <= 0; tx_pkt_start <= 0; tx_pid <= 4'b0000; rollback_in_xfr <= 0; case (in_xfr_state) IDLE : begin rollback_in_xfr <= 1; if (in_token_received) begin in_xfr_state_next <= RCVD_IN; end else begin in_xfr_state_next <= IDLE; end end // Got an IN token RCVD_IN : begin tx_pkt_start <= 1; if (ep_state[current_endp] == STALL) begin in_xfr_state_next <= IDLE; tx_pid <= 4'b1110; // STALL end else if (ep_state[current_endp] == GETTING_PKT) begin // if we were in GETTING_PKT (done getting data from the device), Send it! in_xfr_state_next <= SEND_DATA; tx_pid <= {data_toggle[current_endp], 3'b011}; // DATA0/1 in_xfr_start <= 1; end else begin in_xfr_state_next <= IDLE; tx_pid <= 4'b1010; // NAK end end SEND_DATA : begin // Send the data from the buffer now (until the out (get) address = the in (put) address) if (!more_data_to_send) begin in_xfr_state_next <= WAIT_ACK; end else begin in_xfr_state_next <= SEND_DATA; end end WAIT_ACK : begin // FIXME: need to handle smash/timeout // Could wait here forever (although another token will come along) if (ack_received) begin in_xfr_state_next <= IDLE; in_xfr_end <= 1; end else if (in_token_received) begin in_xfr_state_next <= RCVD_IN; rollback_in_xfr <= 1; end else if (rx_pkt_end) begin in_xfr_state_next <= IDLE; rollback_in_xfr <= 1; end else begin in_xfr_state_next <= WAIT_ACK; end end endcase end always @(posedge clk) tx_data <= in_data_buffer[buffer_get_addr]; integer j; always @(posedge clk) begin if (reset) begin in_xfr_state <= IDLE; end else begin in_xfr_state <= in_xfr_state_next; // tx_data <= in_data_buffer[buffer_get_addr]; if (setup_token_received) begin data_toggle[rx_endp] <= 1; end if (in_token_received) begin current_endp <= rx_endp; end if (rollback_in_xfr) begin ep_get_addr[current_endp][5:0] <= 0; end case (in_xfr_state) IDLE : begin end RCVD_IN : begin end SEND_DATA : begin if (tx_data_get && tx_data_avail_i) begin ep_get_addr[current_endp][5:0] <= ep_get_addr[current_endp][5:0] + 1; end end WAIT_ACK : begin if (ack_received) begin data_toggle[current_endp] <= !data_toggle[current_endp]; end end endcase end for (j = 0; j < NUM_IN_EPS; j = j + 1) begin if (reset || reset_ep[j]) begin data_toggle[j] <= 0; ep_get_addr[j][5:0] <= 0; end end end endmodule
module usb_serial_ctrl_ep #( parameter MAX_IN_PACKET_SIZE = 32, parameter MAX_OUT_PACKET_SIZE = 32 ) ( input clk, input reset, output [6:0] dev_addr, //////////////////// // out endpoint interface //////////////////// output out_ep_req, input out_ep_grant, input out_ep_data_avail, input out_ep_setup, output out_ep_data_get, input [7:0] out_ep_data, output out_ep_stall, input out_ep_acked, //////////////////// // in endpoint interface //////////////////// output in_ep_req, input in_ep_grant, input in_ep_data_free, output in_ep_data_put, output reg [7:0] in_ep_data = 0, output in_ep_data_done, output reg in_ep_stall, input in_ep_acked ); localparam IDLE = 0; localparam SETUP = 1; localparam DATA_IN = 2; localparam DATA_OUT = 3; localparam STATUS_IN = 4; localparam STATUS_OUT = 5; reg [5:0] ctrl_xfr_state = IDLE; reg [5:0] ctrl_xfr_state_next; reg setup_stage_end = 0; reg data_stage_end = 0; reg status_stage_end = 0; reg send_zero_length_data_pkt = 0; // the default control endpoint gets assigned the device address reg [6:0] dev_addr_i = 0; assign dev_addr = dev_addr_i; assign out_ep_req = out_ep_data_avail; assign out_ep_data_get = out_ep_data_avail; reg out_ep_data_valid = 0; always @(posedge clk) out_ep_data_valid <= out_ep_data_avail && out_ep_grant; // need to record the setup data reg [3:0] setup_data_addr = 0; reg [9:0] raw_setup_data [7:0]; wire [7:0] bmRequestType = raw_setup_data[0]; wire [7:0] bRequest = raw_setup_data[1]; wire [15:0] wValue = {raw_setup_data[3][7:0], raw_setup_data[2][7:0]}; wire [15:0] wIndex = {raw_setup_data[5][7:0], raw_setup_data[4][7:0]}; wire [15:0] wLength = {raw_setup_data[7][7:0], raw_setup_data[6][7:0]}; // keep track of new out data start and end wire pkt_start; wire pkt_end; rising_edge_detector detect_pkt_start ( .clk(clk), .in(out_ep_data_avail), .out(pkt_start) ); falling_edge_detector detect_pkt_end ( .clk(clk), .in(out_ep_data_avail), .out(pkt_end) ); assign out_ep_stall = 1'b0; wire setup_pkt_start = pkt_start && out_ep_setup; // wire has_data_stage = wLength != 16'b0000000000000000; // this version for some reason causes a 16b carry which is slow wire has_data_stage = |wLength; wire out_data_stage; assign out_data_stage = has_data_stage && !bmRequestType[7]; wire in_data_stage; assign in_data_stage = has_data_stage && bmRequestType[7]; reg [7:0] bytes_sent = 0; reg [6:0] rom_length = 0; wire all_data_sent = (bytes_sent >= rom_length) || (bytes_sent >= wLength[7:0]); // save it from the full 16b wire more_data_to_send = !all_data_sent; wire in_data_transfer_done; rising_edge_detector detect_in_data_transfer_done ( .clk(clk), .in(all_data_sent), .out(in_data_transfer_done) ); assign in_ep_data_done = (in_data_transfer_done && ctrl_xfr_state == DATA_IN) || send_zero_length_data_pkt; assign in_ep_req = ctrl_xfr_state == DATA_IN && more_data_to_send; assign in_ep_data_put = ctrl_xfr_state == DATA_IN && more_data_to_send && in_ep_data_free; reg [6:0] rom_addr = 0; reg save_dev_addr = 0; reg [6:0] new_dev_addr = 0; //////////////////////////////////////////////////////////////////////////////// // control transfer state machine //////////////////////////////////////////////////////////////////////////////// always @* begin setup_stage_end <= 0; data_stage_end <= 0; status_stage_end <= 0; send_zero_length_data_pkt <= 0; case (ctrl_xfr_state) IDLE : begin if (setup_pkt_start) begin ctrl_xfr_state_next <= SETUP; end else begin ctrl_xfr_state_next <= IDLE; end end SETUP : begin if (pkt_end) begin setup_stage_end <= 1; if (in_data_stage) begin ctrl_xfr_state_next <= DATA_IN; end else if (out_data_stage) begin ctrl_xfr_state_next <= DATA_OUT; end else begin ctrl_xfr_state_next <= STATUS_IN; send_zero_length_data_pkt <= 1; end end else begin ctrl_xfr_state_next <= SETUP; end end DATA_IN : begin if (in_ep_stall) begin ctrl_xfr_state_next <= IDLE; data_stage_end <= 1; status_stage_end <= 1; end else if (in_ep_acked && all_data_sent) begin ctrl_xfr_state_next <= STATUS_OUT; data_stage_end <= 1; end else begin ctrl_xfr_state_next <= DATA_IN; end end DATA_OUT : begin if (out_ep_acked) begin ctrl_xfr_state_next <= STATUS_IN; send_zero_length_data_pkt <= 1; data_stage_end <= 1; end else begin ctrl_xfr_state_next <= DATA_OUT; end end STATUS_IN : begin if (in_ep_acked) begin ctrl_xfr_state_next <= IDLE; status_stage_end <= 1; end else begin ctrl_xfr_state_next <= STATUS_IN; end end STATUS_OUT: begin if (out_ep_acked) begin ctrl_xfr_state_next <= IDLE; status_stage_end <= 1; end else begin ctrl_xfr_state_next <= STATUS_OUT; end end default begin ctrl_xfr_state_next <= IDLE; end endcase end always @(posedge clk) begin if (reset) begin ctrl_xfr_state <= IDLE; end else begin ctrl_xfr_state <= ctrl_xfr_state_next; end end always @(posedge clk) begin in_ep_stall <= 0; if (out_ep_setup && out_ep_data_valid) begin raw_setup_data[setup_data_addr] <= out_ep_data; setup_data_addr <= setup_data_addr + 1; end if (setup_stage_end) begin case (bRequest) 'h06 : begin // GET_DESCRIPTOR case (wValue[15:8]) 1 : begin // DEVICE rom_addr <= 'h00; rom_length <= 'h12; end 2 : begin // CONFIGURATION rom_addr <= 'h12; rom_length <= 'h43; end 6 : begin // DEVICE_QUALIFIER in_ep_stall <= 1; rom_addr <= 'h00; rom_length <= 'h00; end endcase end 'h05 : begin // SET_ADDRESS rom_addr <= 'h00; rom_length <= 'h00; // we need to save the address after the status stage ends // this is because the status stage token will still be using // the old device address save_dev_addr <= 1; new_dev_addr <= wValue[6:0]; end 'h09 : begin // SET_CONFIGURATION rom_addr <= 'h00; rom_length <= 'h00; end 'h20 : begin // SET_LINE_CODING rom_addr <= 'h00; rom_length <= 'h00; end 'h21 : begin // GET_LINE_CODING rom_addr <= 'h55; rom_length <= 'h07; end 'h22 : begin // SET_CONTROL_LINE_STATE rom_addr <= 'h00; rom_length <= 'h00; end 'h23 : begin // SEND_BREAK rom_addr <= 'h00; rom_length <= 'h00; end default begin rom_addr <= 'h00; rom_length <= 'h00; end endcase end if (ctrl_xfr_state == DATA_IN && more_data_to_send && in_ep_grant && in_ep_data_free) begin rom_addr <= rom_addr + 1; bytes_sent <= bytes_sent + 1; end if (status_stage_end) begin setup_data_addr <= 0; bytes_sent <= 0; rom_addr <= 0; rom_length <= 0; if (save_dev_addr) begin save_dev_addr <= 0; dev_addr_i <= new_dev_addr; end end if (reset) begin dev_addr_i <= 0; setup_data_addr <= 0; save_dev_addr <= 0; end end `define CDC_ACM_ENDPOINT 2 `define CDC_RX_ENDPOINT 1 `define CDC_TX_ENDPOINT 1 always @* begin case (rom_addr) // device descriptor 'h000 : in_ep_data <= 18; // bLength 'h001 : in_ep_data <= 1; // bDescriptorType 'h002 : in_ep_data <= 'h00; // bcdUSB[0] 'h003 : in_ep_data <= 'h02; // bcdUSB[1] 'h004 : in_ep_data <= 'h02; // bDeviceClass (Communications Device Class) 'h005 : in_ep_data <= 'h00; // bDeviceSubClass (Abstract Control Model) 'h006 : in_ep_data <= 'h00; // bDeviceProtocol (No class specific protocol required) 'h007 : in_ep_data <= MAX_IN_PACKET_SIZE; // bMaxPacketSize0 'h008 : in_ep_data <= 'h50; // idVendor[0] http://wiki.openmoko.org/wiki/USB_Product_IDs 'h009 : in_ep_data <= 'h1d; // idVendor[1] 'h00A : in_ep_data <= 'h30; // idProduct[0] 'h00B : in_ep_data <= 'h61; // idProduct[1] 'h00C : in_ep_data <= 0; // bcdDevice[0] 'h00D : in_ep_data <= 0; // bcdDevice[1] 'h00E : in_ep_data <= 0; // iManufacturer 'h00F : in_ep_data <= 0; // iProduct 'h010 : in_ep_data <= 0; // iSerialNumber 'h011 : in_ep_data <= 1; // bNumConfigurations // configuration descriptor 'h012 : in_ep_data <= 9; // bLength 'h013 : in_ep_data <= 2; // bDescriptorType 'h014 : in_ep_data <= (9+9+5+5+4+5+7+9+7+7); // wTotalLength[0] 'h015 : in_ep_data <= 0; // wTotalLength[1] 'h016 : in_ep_data <= 2; // bNumInterfaces 'h017 : in_ep_data <= 1; // bConfigurationValue 'h018 : in_ep_data <= 0; // iConfiguration 'h019 : in_ep_data <= 'hC0; // bmAttributes 'h01A : in_ep_data <= 50; // bMaxPower // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12 'h01B : in_ep_data <= 9; // bLength 'h01C : in_ep_data <= 4; // bDescriptorType 'h01D : in_ep_data <= 0; // bInterfaceNumber 'h01E : in_ep_data <= 0; // bAlternateSetting 'h01F : in_ep_data <= 1; // bNumEndpoints 'h020 : in_ep_data <= 2; // bInterfaceClass (Communications Device Class) 'h021 : in_ep_data <= 2; // bInterfaceSubClass (Abstract Control Model) 'h022 : in_ep_data <= 0; // bInterfaceProtocol (0 = ?, 1 = AT Commands: V.250 etc) 'h023 : in_ep_data <= 0; // iInterface // CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26 'h024 : in_ep_data <= 5; // bFunctionLength 'h025 : in_ep_data <= 'h24; // bDescriptorType 'h026 : in_ep_data <= 'h00; // bDescriptorSubtype 'h027 : in_ep_data <= 'h10; 'h028 : in_ep_data <= 'h01; // bcdCDC // Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27 'h029 : in_ep_data <= 5; // bFunctionLength 'h02A : in_ep_data <= 'h24; // bDescriptorType 'h02B : in_ep_data <= 'h01; // bDescriptorSubtype 'h02C : in_ep_data <= 'h00; // bmCapabilities 'h02D : in_ep_data <= 1; // bDataInterface // Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28 'h02E : in_ep_data <= 4; // bFunctionLength 'h02F : in_ep_data <= 'h24; // bDescriptorType 'h030 : in_ep_data <= 'h02; // bDescriptorSubtype 'h031 : in_ep_data <= 'h06; // bmCapabilities // Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33 'h032 : in_ep_data <= 5; // bFunctionLength 'h033 : in_ep_data <= 'h24; // bDescriptorType 'h034 : in_ep_data <= 'h06; // bDescriptorSubtype 'h035 : in_ep_data <= 0; // bMasterInterface 'h036 : in_ep_data <= 1; // bSlaveInterface0 // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13 'h037 : in_ep_data <= 7; // bLength 'h038 : in_ep_data <= 5; // bDescriptorType 'h039 : in_ep_data <= `CDC_ACM_ENDPOINT | 'h80; // bEndpointAddress 'h03A : in_ep_data <= 'h03; // bmAttributes (0x03=intr) 'h03B : in_ep_data <= 8; // wMaxPacketSize[0] 'h03C : in_ep_data <= 0; // wMaxPacketSize[1] 'h03D : in_ep_data <= 64; // bInterval // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12 'h03E : in_ep_data <= 9; // bLength 'h03F : in_ep_data <= 4; // bDescriptorType 'h040 : in_ep_data <= 1; // bInterfaceNumber 'h041 : in_ep_data <= 0; // bAlternateSetting 'h042 : in_ep_data <= 2; // bNumEndpoints 'h043 : in_ep_data <= 'h0A; // bInterfaceClass 'h044 : in_ep_data <= 'h00; // bInterfaceSubClass 'h045 : in_ep_data <= 'h00; // bInterfaceProtocol 'h046 : in_ep_data <= 0; // iInterface // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13 'h047 : in_ep_data <= 7; // bLength 'h048 : in_ep_data <= 5; // bDescriptorType 'h049 : in_ep_data <= `CDC_RX_ENDPOINT; // bEndpointAddress 'h04A : in_ep_data <= 'h02; // bmAttributes (0x02=bulk) 'h04B : in_ep_data <= MAX_IN_PACKET_SIZE; // wMaxPacketSize[0] 'h04C : in_ep_data <= 0; // wMaxPacketSize[1] 'h04D : in_ep_data <= 0; // bInterval // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13 'h04E : in_ep_data <= 7; // bLength 'h04F : in_ep_data <= 5; // bDescriptorType 'h050 : in_ep_data <= `CDC_TX_ENDPOINT | 'h80; // bEndpointAddress 'h051 : in_ep_data <= 'h02; // bmAttributes (0x02=bulk) 'h052 : in_ep_data <= MAX_OUT_PACKET_SIZE; // wMaxPacketSize[0] 'h053 : in_ep_data <= 0; // wMaxPacketSize[1] 'h054 : in_ep_data <= 0; // bInterval // LINE_CODING 'h055 : in_ep_data <= 'h80; // dwDTERate[0] 'h056 : in_ep_data <= 'h25; // dwDTERate[1] 'h057 : in_ep_data <= 'h00; // dwDTERate[2] 'h058 : in_ep_data <= 'h00; // dwDTERate[3] 'h059 : in_ep_data <= 1; // bCharFormat (1 stop bit) 'h05A : in_ep_data <= 0; // bParityType (None) 'h05B : in_ep_data <= 8; // bDataBits (8 bits) default begin in_ep_data <= 0; end endcase end endmodule
module usb_uart #( parameter PipeSpec = `PS_d8 ) ( input clk_48mhz, input reset, // USB pins inout pin_usb_p, inout pin_usb_n, inout [`P_m(PipeSpec):0] pipe_in, inout [`P_m(PipeSpec):0] pipe_out, output [11:0] debug ); wire [`P_Data_m(PipeSpec):0] in_data; wire in_valid; wire in_ready; wire [`P_Data_m(PipeSpec):0] out_data; wire out_valid; wire out_ready; p_unpack_data #( .PipeSpec( PipeSpec ) ) in_unpack_data( .pipe(pipe_in), .data(in_data) ); p_unpack_valid_ready #( .PipeSpec( PipeSpec ) ) in_unpack_valid_ready( .pipe(pipe_in), .valid(in_valid), .ready(in_ready) ); // start and stop signals are ignored - packetization has to be escaped usb_uart_np u_u_np( clk_48mhz, reset, pin_usb_p, pin_usb_n, in_data, in_valid, in_ready, out_data, out_valid, out_ready, debug ); p_pack_data #( .PipeSpec( PipeSpec ) ) out_pack_d( .data(out_data), .pipe(pipe_out) ); p_pack_valid_ready #( .PipeSpec( PipeSpec ) ) out_pack_vr( .valid(out_valid), .ready(out_ready), .pipe(pipe_out) ); endmodule
module usb_uart_np ( input clk_48mhz, input reset, // USB pins inout pin_usb_p, inout pin_usb_n, // uart pipeline in (out of the device, into the host) input [7:0] uart_in_data, input uart_in_valid, output uart_in_ready, // uart pipeline out (into the device, out of the host) output [7:0] uart_out_data, output uart_out_valid, input uart_out_ready, output [11:0] debug ); wire usb_p_tx; wire usb_n_tx; wire usb_p_rx; wire usb_n_rx; wire usb_tx_en; // wire [11:0] debug_dum; usb_uart_core_np u_u_c_np ( .clk_48mhz (clk_48mhz), .reset (reset), // pins - these must be connected properly to the outside world. See below. .usb_p_tx(usb_p_tx), .usb_n_tx(usb_n_tx), .usb_p_rx(usb_p_rx), .usb_n_rx(usb_n_rx), .usb_tx_en(usb_tx_en), // uart pipeline in .uart_in_data( uart_in_data ), .uart_in_valid( uart_in_valid ), .uart_in_ready( uart_in_ready ), // uart pipeline out .uart_out_data( uart_out_data ), .uart_out_valid( uart_out_valid ), .uart_out_ready( uart_out_ready ), .debug( debug ) ); wire usb_p_in; wire usb_n_in; assign usb_p_rx = usb_tx_en ? 1'b1 : usb_p_in; assign usb_n_rx = usb_tx_en ? 1'b0 : usb_n_in; // T = TRISTATE (not transmit) BB io_p( .I( usb_p_tx ), .T( !usb_tx_en ), .O( usb_p_in ), .B( pin_usb_p ) ); BB io_n( .I( usb_n_tx ), .T( !usb_tx_en ), .O( usb_n_in ), .B( pin_usb_n ) ); endmodule
module usb_reset_det ( input clk, input reset, input usb_p_rx, input usb_n_rx, output usb_reset ); localparam RESET_COUNT = 16'HFFFF; // reset detection (1 bit extra for overflow) reg [17:0] reset_timer = 0; // keep counting? wire timer_expired = reset_timer[ 17 ]; // one time event when reset_timer = 0; // assign usb_reset = !(|reset_timer); assign usb_reset = timer_expired; always @(posedge clk) begin if ( reset ) begin reset_timer <= RESET_COUNT; end else begin // reset is both inputs low for 10ms if (usb_p_rx || usb_n_rx) begin reset_timer <= RESET_COUNT; end else begin reset_timer <= reset_timer - ((timer_expired)? 0 : 1); end end end endmodule
module usb_fs_in_arb #( parameter NUM_IN_EPS = 1 ) ( //////////////////// // endpoint interface //////////////////// input [NUM_IN_EPS-1:0] in_ep_req, output reg [NUM_IN_EPS-1:0] in_ep_grant, input [(NUM_IN_EPS*8)-1:0] in_ep_data, //////////////////// // protocol engine interface //////////////////// output reg [7:0] arb_in_ep_data ); integer i; reg grant; always @* begin grant = 0; arb_in_ep_data <= 0; for (i = 0; i < NUM_IN_EPS; i = i + 1) begin in_ep_grant[i] <= 0; if (in_ep_req[i] && !grant) begin in_ep_grant[i] <= 1; arb_in_ep_data <= in_ep_data[i * 8 +: 8]; grant = 1; end end // if (!grant) begin // arb_in_ep_data <= 0; // end end endmodule
module rising_edge_detector ( input clk, input in, output out ); reg in_q; always @(posedge clk) begin in_q <= in; end assign out = !in_q && in; endmodule
module usb_fs_rx ( // A 48MHz clock is required to recover the clock from the incoming data. input clk_48mhz, input reset, // USB data+ and data- lines. input dp, input dn, // pulse on every bit transition. output bit_strobe, // Pulse on beginning of new packet. output pkt_start, // Pulse on end of current packet. output pkt_end, // Most recent packet decoded. output [3:0] pid, output reg [6:0] addr = 0, output reg [3:0] endp = 0, output reg [10:0] frame_num = 0, // Pulse on valid data on rx_data. output rx_data_put, output [7:0] rx_data, // Most recent packet passes PID and CRC checks output valid_packet ); wire clk = clk_48mhz; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////// //////// usb receive path //////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // double flop for metastability /* all asynchronous inputs into the RTL need to be double-flopped to protect against metastable scenarios. if the RTL clock samples an asynchronous signal at the same time the signal is transitioning the result is undefined. flopping the signal twice ensures it will be either 1 or 0 and nothing in between. */ reg [3:0] dpair_q = 0; always @(posedge clk) begin dpair_q[3:0] <= {dpair_q[1:0], dp, dn}; end //////////////////////////////////////////////////////////////////////////////// // line state recovery state machine /* the recieve path doesn't currently use a differential reciever. because of this there is a chance that one of the differential pairs will appear to have changed to the new state while the other is still in the old state. the following state machine detects transitions and waits an extra sampling clock before decoding the state on the differential pair. this transition period will only ever last for one clock as long as there is no noise on the line. if there is enough noise on the line then the data may be corrupted and the packet will fail the data integrity checks. */ reg [2:0] line_state = 0; localparam DT = 3'b100; localparam DJ = 3'b010; localparam DK = 3'b001; localparam SE0 = 3'b000; localparam SE1 = 3'b011; wire [1:0] dpair = dpair_q[3:2]; always @(posedge clk) begin case (line_state) // if we are in a transition state, then we can sample the pair and // move to the next corresponding line state DT : begin case (dpair) 2'b10 : line_state <= DJ; 2'b01 : line_state <= DK; 2'b00 : line_state <= SE0; 2'b11 : line_state <= SE1; endcase end // if we are in a valid line state and the value of the pair changes, // then we need to move to the transition state DJ : if (dpair != 2'b10) line_state <= DT; DK : if (dpair != 2'b01) line_state <= DT; SE0 : if (dpair != 2'b00) line_state <= DT; SE1 : if (dpair != 2'b11) line_state <= DT; // if we are in an invalid state we should move to the transition state default : line_state <= DT; endcase end //////////////////////////////////////////////////////////////////////////////// // clock recovery /* the DT state from the line state recovery state machine is used to align to transmit clock. the line state is sampled in the middle of the bit time. example of signal relationships ------------------------------- line_state DT DJ DJ DJ DT DK DK DK DK DK DK DT DJ DJ DJ line_state_valid ________----____________----____________----________----____ bit_phase 0 0 1 2 3 0 1 2 3 0 1 2 0 1 2 */ reg [1:0] bit_phase = 0; wire line_state_valid = (bit_phase == 1); assign bit_strobe = (bit_phase == 2); always @(posedge clk) begin // keep track of phase within each bit if (line_state == DT) begin bit_phase <= 0; end else begin bit_phase <= bit_phase + 1; end end //////////////////////////////////////////////////////////////////////////////// // packet detection /* usb uses a sync to denote the beginning of a packet and two single-ended-0 to denote the end of a packet. this state machine recognizes the beginning and end of packets for subsequent layers to process. */ reg [5:0] line_history = 0; reg packet_valid = 0; reg next_packet_valid; wire packet_start = next_packet_valid && !packet_valid; wire packet_end = !next_packet_valid && packet_valid; always @* begin if (line_state_valid) begin // check for packet start: KJKJKK if (!packet_valid && line_history[5:0] == 6'b100101) begin next_packet_valid <= 1; end // check for packet end: SE0 SE0 else if (packet_valid && line_history[3:0] == 4'b0000) begin next_packet_valid <= 0; end else begin next_packet_valid <= packet_valid; end end else begin next_packet_valid <= packet_valid; end end always @(posedge clk) begin if (reset) begin line_history <= 6'b101010; packet_valid <= 0; end else begin // keep a history of the last two states on the line if (line_state_valid) begin line_history[5:0] <= {line_history[3:0], line_state[1:0]}; end end packet_valid <= next_packet_valid; end //////////////////////////////////////////////////////////////////////////////// // NRZI decode /* in order to ensure there are enough bit transitions for a receiver to recover the clock usb uses NRZI encoding. https://en.wikipedia.org/wiki/Non-return-to-zero */ reg dvalid_raw; reg din; always @* begin case (line_history[3:0]) 4'b0101 : din <= 1; 4'b0110 : din <= 0; 4'b1001 : din <= 0; 4'b1010 : din <= 1; default : din <= 0; endcase if (packet_valid && line_state_valid) begin case (line_history[3:0]) 4'b0101 : dvalid_raw <= 1; 4'b0110 : dvalid_raw <= 1; 4'b1001 : dvalid_raw <= 1; 4'b1010 : dvalid_raw <= 1; default : dvalid_raw <= 0; endcase end else begin dvalid_raw <= 0; end end reg [5:0] bitstuff_history = 0; always @(posedge clk) begin if (reset || packet_end) begin bitstuff_history <= 6'b000000; end else begin if (dvalid_raw) begin bitstuff_history <= {bitstuff_history[4:0], din}; end end end wire dvalid = dvalid_raw && !(bitstuff_history == 6'b111111); //////////////////////////////////////////////////////////////////////////////// // save and check pid /* shift in the entire 8-bit pid with an additional 9th bit used as a sentinal. */ reg [8:0] full_pid = 0; wire pid_valid = full_pid[4:1] == ~full_pid[8:5]; wire pid_complete = full_pid[0]; always @(posedge clk) begin if (packet_start) begin full_pid <= 9'b100000000; end if (dvalid && !pid_complete) begin full_pid <= {din, full_pid[8:1]}; end end //////////////////////////////////////////////////////////////////////////////// // check crc5 reg [4:0] crc5 = 0; wire crc5_valid = crc5 == 5'b01100; wire crc5_invert = din ^ crc5[4]; always @(posedge clk) begin if (packet_start) begin crc5 <= 5'b11111; end if (dvalid && pid_complete) begin crc5[4] <= crc5[3]; crc5[3] <= crc5[2]; crc5[2] <= crc5[1] ^ crc5_invert; crc5[1] <= crc5[0]; crc5[0] <= crc5_invert; end end //////////////////////////////////////////////////////////////////////////////// // check crc16 reg [15:0] crc16 = 0; wire crc16_valid = crc16 == 16'b1000000000001101; wire crc16_invert = din ^ crc16[15]; always @(posedge clk) begin if (packet_start) begin crc16 <= 16'b1111111111111111; end if (dvalid && pid_complete) begin crc16[15] <= crc16[14] ^ crc16_invert; crc16[14] <= crc16[13]; crc16[13] <= crc16[12]; crc16[12] <= crc16[11]; crc16[11] <= crc16[10]; crc16[10] <= crc16[9]; crc16[9] <= crc16[8]; crc16[8] <= crc16[7]; crc16[7] <= crc16[6]; crc16[6] <= crc16[5]; crc16[5] <= crc16[4]; crc16[4] <= crc16[3]; crc16[3] <= crc16[2]; crc16[2] <= crc16[1] ^ crc16_invert; crc16[1] <= crc16[0]; crc16[0] <= crc16_invert; end end //////////////////////////////////////////////////////////////////////////////// // output control signals wire pkt_is_token = full_pid[2:1] == 2'b01; wire pkt_is_data = full_pid[2:1] == 2'b11; wire pkt_is_handshake = full_pid[2:1] == 2'b10; // TODO: need to check for data packet babble // TODO: do i need to check for bitstuff error? assign valid_packet = pid_valid && ( (pkt_is_handshake) || (pkt_is_data && crc16_valid) || (pkt_is_token && crc5_valid) ); reg [11:0] token_payload = 0; wire token_payload_done = token_payload[0]; always @(posedge clk) begin if (packet_start) begin token_payload <= 12'b100000000000; end if (dvalid && pid_complete && pkt_is_token && !token_payload_done) begin token_payload <= {din, token_payload[11:1]}; end end always @(posedge clk) begin if (token_payload_done && pkt_is_token) begin addr <= token_payload[7:1]; endp <= token_payload[11:8]; frame_num <= token_payload[11:1]; end end assign pkt_start = packet_start; assign pkt_end = packet_end; assign pid = full_pid[4:1]; //assign addr = token_payload[7:1]; //assign endp = token_payload[11:8]; //assign frame_num = token_payload[11:1]; //////////////////////////////////////////////////////////////////////////////// // deserialize and output data //assign rx_data_put = dvalid && pid_complete && pkt_is_data; reg [8:0] rx_data_buffer = 0; wire rx_data_buffer_full = rx_data_buffer[0]; assign rx_data_put = rx_data_buffer_full; assign rx_data = rx_data_buffer[8:1]; always @(posedge clk) begin if (packet_start || rx_data_buffer_full) begin rx_data_buffer <= 9'b100000000; end if (dvalid && pid_complete && pkt_is_data) begin rx_data_buffer <= {din, rx_data_buffer[8:1]}; end end endmodule // usb_fs_rx
module width_adapter #( parameter [31:0] INPUT_WIDTH = 8, parameter [31:0] OUTPUT_WIDTH = 1 ) ( input clk, input reset, input data_in_put, output data_in_free, input [INPUT_WIDTH-1:0] data_in, output data_out_put, input data_out_free, output [OUTPUT_WIDTH-1:0] data_out ); generate if (INPUT_WIDTH > OUTPUT_WIDTH) begin // wide to narrow conversion reg [INPUT_WIDTH:0] data_in_q; reg has_data; always @(posedge clk) begin if (!has_data && data_in_put) begin data_in_q <= {1'b1, data_in}; has_data <= 1; end if (has_data && data_out_free) begin data_in_q <= data_in_q >> OUTPUT_WIDTH; end if (data_in_q == 1'b1) begin has_data <= 0; end end assign data_out = data_in_q[OUTPUT_WIDTH:1]; assign data_out_put = has_data; end else if (INPUT_WIDTH < OUTPUT_WIDTH) begin // narrow to wide conversion end else begin assign data_in_free = data_out_free; assign data_out_put = data_in_put; assign data_out = data_in; end endgenerate endmodule
module usb_fs_out_arb #( parameter NUM_OUT_EPS = 1 ) ( //////////////////// // endpoint interface //////////////////// input [NUM_OUT_EPS-1:0] out_ep_req, output reg [NUM_OUT_EPS-1:0] out_ep_grant ); integer i; reg grant; always @* begin grant = 0; for (i = 0; i < NUM_OUT_EPS; i = i + 1) begin out_ep_grant[i] <= 0; if (out_ep_req[i] && !grant) begin out_ep_grant[i] <= 1; grant = 1; end end end endmodule
module usb_fs_pe #( parameter [4:0] NUM_OUT_EPS = 1, parameter [4:0] NUM_IN_EPS = 1 ) ( input clk, input [6:0] dev_addr, //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// USB Endpoint Interface //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////// // global endpoint interface //////////////////// input reset, //////////////////// // out endpoint interfaces //////////////////// input [NUM_OUT_EPS-1:0] out_ep_req, output [NUM_OUT_EPS-1:0] out_ep_grant, output [NUM_OUT_EPS-1:0] out_ep_data_avail, output [NUM_OUT_EPS-1:0] out_ep_setup, input [NUM_OUT_EPS-1:0] out_ep_data_get, output [7:0] out_ep_data, input [NUM_OUT_EPS-1:0] out_ep_stall, output [NUM_OUT_EPS-1:0] out_ep_acked, //////////////////// // in endpoint interfaces //////////////////// input [NUM_IN_EPS-1:0] in_ep_req, output [NUM_IN_EPS-1:0] in_ep_grant, output [NUM_IN_EPS-1:0] in_ep_data_free, input [NUM_IN_EPS-1:0] in_ep_data_put, input [(NUM_IN_EPS*8)-1:0] in_ep_data, input [NUM_IN_EPS-1:0] in_ep_data_done, input [NUM_IN_EPS-1:0] in_ep_stall, output [NUM_IN_EPS-1:0] in_ep_acked, //////////////////// // sof interface //////////////////// output sof_valid, output [10:0] frame_index, //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// USB TX/RX Interface //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// output usb_p_tx, output usb_n_tx, input usb_p_rx, input usb_n_rx, output usb_tx_en, output [7:0] debug ); // in pe interface wire [7:0] arb_in_ep_data; // rx interface wire bit_strobe; wire rx_pkt_start; wire rx_pkt_end; wire [3:0] rx_pid; wire [6:0] rx_addr; wire [3:0] rx_endp; wire [10:0] rx_frame_num; wire rx_data_put; wire [7:0] rx_data; wire rx_pkt_valid; // tx mux wire in_tx_pkt_start; wire [3:0] in_tx_pid; wire out_tx_pkt_start; wire [3:0] out_tx_pid; // tx interface wire tx_pkt_start; wire tx_pkt_end; wire [3:0] tx_pid; wire tx_data_avail; wire tx_data_get; wire [7:0] tx_data; // sof interface assign sof_valid = rx_pkt_end && rx_pkt_valid && ( rx_pid == 4'b0101 ); assign frame_index = rx_frame_num; usb_fs_in_arb #( .NUM_IN_EPS(NUM_IN_EPS) ) usb_fs_in_arb_inst ( // endpoint interface .in_ep_req(in_ep_req), .in_ep_grant(in_ep_grant), .in_ep_data(in_ep_data), // protocol engine interface .arb_in_ep_data(arb_in_ep_data) ); usb_fs_out_arb #( .NUM_OUT_EPS(NUM_OUT_EPS) ) usb_fs_out_arb_inst ( // endpoint interface .out_ep_req(out_ep_req), .out_ep_grant(out_ep_grant) ); usb_fs_in_pe #( .NUM_IN_EPS(NUM_IN_EPS) ) usb_fs_in_pe_inst ( .clk(clk), .reset(reset), .reset_ep({NUM_IN_EPS{1'b0}}), .dev_addr(dev_addr), // endpoint interface .in_ep_data_free(in_ep_data_free), .in_ep_data_put(in_ep_data_put), .in_ep_data(arb_in_ep_data), .in_ep_data_done(in_ep_data_done), .in_ep_stall(in_ep_stall), .in_ep_acked(in_ep_acked), // rx path .rx_pkt_start(rx_pkt_start), .rx_pkt_end(rx_pkt_end), .rx_pkt_valid(rx_pkt_valid), .rx_pid(rx_pid), .rx_addr(rx_addr), .rx_endp(rx_endp), .rx_frame_num(rx_frame_num), // tx path .tx_pkt_start(in_tx_pkt_start), .tx_pkt_end(tx_pkt_end), .tx_pid(in_tx_pid), .tx_data_avail(tx_data_avail), .tx_data_get(tx_data_get), .tx_data(tx_data), .debug(debug) ); usb_fs_out_pe #( .NUM_OUT_EPS(NUM_OUT_EPS) ) usb_fs_out_pe_inst ( .clk(clk), .reset(reset), .reset_ep({NUM_OUT_EPS{1'b0}}), .dev_addr(dev_addr), // endpoint interface .out_ep_data_avail(out_ep_data_avail), .out_ep_data_get(out_ep_data_get), .out_ep_data(out_ep_data), .out_ep_setup(out_ep_setup), .out_ep_stall(out_ep_stall), .out_ep_acked(out_ep_acked), .out_ep_grant(out_ep_grant), // rx path .rx_pkt_start(rx_pkt_start), .rx_pkt_end(rx_pkt_end), .rx_pkt_valid(rx_pkt_valid), .rx_pid(rx_pid), .rx_addr(rx_addr), .rx_endp(rx_endp), .rx_frame_num(rx_frame_num), .rx_data_put(rx_data_put), .rx_data(rx_data), // tx path .tx_pkt_start(out_tx_pkt_start), .tx_pkt_end(tx_pkt_end), .tx_pid(out_tx_pid) ); usb_fs_rx usb_fs_rx_inst ( .clk_48mhz(clk), .reset(reset), .dp(usb_p_rx), .dn(usb_n_rx), .bit_strobe(bit_strobe), .pkt_start(rx_pkt_start), .pkt_end(rx_pkt_end), .pid(rx_pid), .addr(rx_addr), .endp(rx_endp), .frame_num(rx_frame_num), .rx_data_put(rx_data_put), .rx_data(rx_data), .valid_packet(rx_pkt_valid) ); usb_fs_tx_mux usb_fs_tx_mux_inst ( // interface to IN Protocol Engine .in_tx_pkt_start(in_tx_pkt_start), .in_tx_pid(in_tx_pid), // interface to OUT Protocol Engine .out_tx_pkt_start(out_tx_pkt_start), .out_tx_pid(out_tx_pid), // interface to tx module .tx_pkt_start(tx_pkt_start), .tx_pid(tx_pid) ); usb_fs_tx usb_fs_tx_inst ( .clk_48mhz(clk), .reset(reset), .bit_strobe(bit_strobe), .oe(usb_tx_en), .dp(usb_p_tx), .dn(usb_n_tx), .pkt_start(tx_pkt_start), .pkt_end(tx_pkt_end), .pid(tx_pid), .tx_data_avail(tx_data_avail), .tx_data_get(tx_data_get), .tx_data(tx_data) ); endmodule
module usb_fs_tx_mux ( // interface to IN Protocol Engine input in_tx_pkt_start, input [3:0] in_tx_pid, // interface to OUT Protocol Engine input out_tx_pkt_start, input [3:0] out_tx_pid, // interface to tx module output tx_pkt_start, output [3:0] tx_pid ); assign tx_pkt_start = in_tx_pkt_start | out_tx_pkt_start; assign tx_pid = out_tx_pkt_start ? out_tx_pid : in_tx_pid; endmodule
module usb_fs_out_pe #( parameter NUM_OUT_EPS = 1, parameter MAX_OUT_PACKET_SIZE = 32 ) ( input clk, input reset, input [NUM_OUT_EPS-1:0] reset_ep, input [6:0] dev_addr, //////////////////// // endpoint interface //////////////////// output [NUM_OUT_EPS-1:0] out_ep_data_avail, output reg [NUM_OUT_EPS-1:0] out_ep_setup = 0, input [NUM_OUT_EPS-1:0] out_ep_data_get, output reg [7:0] out_ep_data, input [NUM_OUT_EPS-1:0] out_ep_stall, output reg [NUM_OUT_EPS-1:0] out_ep_acked = 0, // Added to provide a more constant way of detecting the current OUT EP than data get input [NUM_OUT_EPS-1:0] out_ep_grant, //////////////////// // rx path //////////////////// // Strobed on reception of packet. input rx_pkt_start, input rx_pkt_end, input rx_pkt_valid, // Most recent packet received. input [3:0] rx_pid, input [6:0] rx_addr, input [3:0] rx_endp, input [10:0] rx_frame_num, // rx_data is pushed into endpoint controller. input rx_data_put, input [7:0] rx_data, //////////////////// // tx path //////////////////// // Strobe to send new packet. output reg tx_pkt_start = 0, input tx_pkt_end, output reg [3:0] tx_pid = 0 ); //////////////////////////////////////////////////////////////////////////////// // endpoint state machine //////////////////////////////////////////////////////////////////////////////// localparam READY_FOR_PKT = 0; localparam PUTTING_PKT = 1; localparam GETTING_PKT = 2; localparam STALL = 3; reg [1:0] ep_state [NUM_OUT_EPS - 1:0]; reg [1:0] ep_state_next [NUM_OUT_EPS - 1:0]; //////////////////////////////////////////////////////////////////////////////// // out transfer state machine //////////////////////////////////////////////////////////////////////////////// localparam IDLE = 0; localparam RCVD_OUT = 1; localparam RCVD_DATA_START = 2; localparam RCVD_DATA_END = 3; reg [1:0] out_xfr_state = IDLE; reg [1:0] out_xfr_state_next; reg out_xfr_start = 0; reg new_pkt_end = 0; reg rollback_data = 0; reg [3:0] out_ep_num = 0; reg [NUM_OUT_EPS - 1:0] out_ep_data_avail_i = 0; reg [NUM_OUT_EPS - 1:0] out_ep_data_avail_j = 0; // set when the endpoint buffer is unable to receive the out transfer reg nak_out_transfer = 0; // data toggle state reg [NUM_OUT_EPS - 1:0] data_toggle = 0; // latched on valid OUT/SETUP token reg [3:0] current_endp = 0; wire [1:0] current_ep_state = ep_state[current_endp]; // endpoint data buffer reg [7:0] out_data_buffer [(MAX_OUT_PACKET_SIZE * NUM_OUT_EPS) - 1:0]; // current get_addr when outputting a packet from the buffer reg [5:0] ep_get_addr [NUM_OUT_EPS - 1:0]; reg [5:0] ep_get_addr_next [NUM_OUT_EPS - 1:0]; // endpoint put_addrs when inputting a packet into the buffer reg [5:0] ep_put_addr [NUM_OUT_EPS - 1:0]; // total buffer put addr, uses endpoint number and that endpoints current // put address wire [8:0] buffer_put_addr = {current_endp[3:0], ep_put_addr[current_endp][4:0]}; wire [8:0] buffer_get_addr = {out_ep_num[3:0], ep_get_addr[out_ep_num][4:0]}; wire token_received = rx_pkt_end && rx_pkt_valid && rx_pid[1:0] == 2'b01 && rx_addr == dev_addr && rx_endp < NUM_OUT_EPS; wire out_token_received = token_received && rx_pid[3:2] == 2'b00; wire setup_token_received = token_received && rx_pid[3:2] == 2'b11; wire invalid_packet_received = rx_pkt_end && !rx_pkt_valid; wire data_packet_received = rx_pkt_end && rx_pkt_valid && rx_pid[2:0] == 3'b011; wire non_data_packet_received = rx_pkt_end && rx_pkt_valid && rx_pid[2:0] != 3'b011; //reg last_data_toggle = 0; wire bad_data_toggle = data_packet_received && rx_pid[3] != data_toggle[rx_endp]; //last_data_toggle == data_toggle[current_endp]; //////////////////////////////////////////////////////////////////////////////// // endpoint state machine //////////////////////////////////////////////////////////////////////////////// genvar ep_num; generate for (ep_num = 0; ep_num < NUM_OUT_EPS; ep_num = ep_num + 1) begin always @* begin ep_state_next[ep_num] <= ep_state[ep_num]; if (out_ep_stall[ep_num]) begin ep_state_next[ep_num] <= STALL; end else begin case (ep_state[ep_num]) READY_FOR_PKT : begin if (out_xfr_start && rx_endp == ep_num) begin ep_state_next[ep_num] <= PUTTING_PKT; end else begin ep_state_next[ep_num] <= READY_FOR_PKT; end end PUTTING_PKT : begin if (new_pkt_end && current_endp == ep_num) begin ep_state_next[ep_num] <= GETTING_PKT; end else if (rollback_data && current_endp == ep_num) begin ep_state_next[ep_num] <= READY_FOR_PKT; end else begin ep_state_next[ep_num] <= PUTTING_PKT; end end GETTING_PKT : begin if (ep_get_addr[ep_num][5:0] >= (ep_put_addr[ep_num][5:0] - 6'H2)) begin ep_state_next[ep_num] <= READY_FOR_PKT; end else begin ep_state_next[ep_num] <= GETTING_PKT; end end STALL : begin if (setup_token_received && rx_endp == ep_num) begin ep_state_next[ep_num] <= READY_FOR_PKT; end else begin ep_state_next[ep_num] <= STALL; end end default begin ep_state_next[ep_num] <= READY_FOR_PKT; end endcase end // Determine the next get_address (init, inc, maintain) if (ep_state_next[ep_num][1:0] == READY_FOR_PKT) begin ep_get_addr_next[ep_num][5:0] <= 0; end else if (ep_state_next[ep_num][1:0] == GETTING_PKT && out_ep_data_get[ep_num]) begin ep_get_addr_next[ep_num][5:0] <= ep_get_addr[ep_num][5:0] + 6'H1; end else begin ep_get_addr_next[ep_num][5:0] <= ep_get_addr[ep_num][5:0]; end end // end of the always @* // Advance the state to the next one. always @(posedge clk) begin if (reset || reset_ep[ep_num]) begin ep_state[ep_num] <= READY_FOR_PKT; end else begin ep_state[ep_num] <= ep_state_next[ep_num]; end ep_get_addr[ep_num][5:0] <= ep_get_addr_next[ep_num][5:0]; end assign out_ep_data_avail[ep_num] = (ep_get_addr[ep_num][5:0] < (ep_put_addr[ep_num][5:0] - 6'H2)) && (ep_state[ep_num][1:0] == GETTING_PKT); end endgenerate integer i; always @(posedge clk) begin if (reset) begin out_ep_setup <= 0; end else begin if (setup_token_received) begin out_ep_setup[rx_endp] <= 1; end else if (out_token_received) begin out_ep_setup[rx_endp] <= 0; end end for (i = 0; i < NUM_OUT_EPS; i = i + 1) begin if (reset_ep[i]) begin out_ep_setup[i] <= 0; end end end always @(posedge clk) out_ep_data <= out_data_buffer[buffer_get_addr][7:0]; // use the bus grant line to determine the out_ep_num (where the data is) integer ep_num_decoder; always @* begin out_ep_num <= 0; for (ep_num_decoder = 0; ep_num_decoder < NUM_OUT_EPS; ep_num_decoder = ep_num_decoder + 1) begin if (out_ep_grant[ep_num_decoder]) begin out_ep_num <= ep_num_decoder; end end end //////////////////////////////////////////////////////////////////////////////// // out transfer state machine //////////////////////////////////////////////////////////////////////////////// always @* begin out_ep_acked <= 0; out_xfr_start <= 0; out_xfr_state_next <= out_xfr_state; tx_pkt_start <= 0; tx_pid <= 0; new_pkt_end <= 0; rollback_data <= 0; case (out_xfr_state) IDLE : begin if (out_token_received || setup_token_received) begin out_xfr_state_next <= RCVD_OUT; out_xfr_start <= 1; end else begin out_xfr_state_next <= IDLE; end end RCVD_OUT : begin if (rx_pkt_start) begin out_xfr_state_next <= RCVD_DATA_START; end else begin out_xfr_state_next <= RCVD_OUT; end end RCVD_DATA_START : begin if (bad_data_toggle) begin out_xfr_state_next <= IDLE; rollback_data <= 1; tx_pkt_start <= 1; tx_pid <= 4'b0010; // ACK end else if (invalid_packet_received || non_data_packet_received) begin out_xfr_state_next <= IDLE; rollback_data <= 1; end else if (data_packet_received) begin out_xfr_state_next <= RCVD_DATA_END; end else begin out_xfr_state_next <= RCVD_DATA_START; end end RCVD_DATA_END : begin out_xfr_state_next <= IDLE; tx_pkt_start <= 1; if (ep_state[current_endp] == STALL) begin tx_pid <= 4'b1110; // STALL end else if (nak_out_transfer) begin tx_pid <= 4'b1010; // NAK rollback_data <= 1; end else begin tx_pid <= 4'b0010; // ACK new_pkt_end <= 1; out_ep_acked[current_endp] <= 1; //end else begin // tx_pid <= 4'b0010; // ACK // rollback_data <= 1; end end default begin out_xfr_state_next <= IDLE; end endcase end wire current_ep_busy = (ep_state[current_endp] == GETTING_PKT) || (ep_state[current_endp] == READY_FOR_PKT); integer j; always @(posedge clk) begin if (reset) begin out_xfr_state <= IDLE; end else begin out_xfr_state <= out_xfr_state_next; if (out_xfr_start) begin current_endp <= rx_endp; //last_data_toggle <= setup_token_received ? 0 : data_toggle[rx_endp]; end if (new_pkt_end) begin data_toggle[current_endp] <= !data_toggle[current_endp]; end if (setup_token_received) begin data_toggle[rx_endp] <= 0; end case (out_xfr_state) IDLE : begin end RCVD_OUT : begin if (current_ep_busy) begin nak_out_transfer <= 1; end else begin nak_out_transfer <= 0; ep_put_addr[current_endp][5:0] <= 0; end end RCVD_DATA_START : begin if (!nak_out_transfer && rx_data_put && !ep_put_addr[current_endp][5]) begin out_data_buffer[buffer_put_addr][7:0] <= rx_data; end if (!nak_out_transfer && rx_data_put) begin ep_put_addr[current_endp][5:0] <= ep_put_addr[current_endp][5:0] + 6'H1; end end RCVD_DATA_END : begin end endcase end for (j = 0; j < NUM_OUT_EPS; j = j + 1) begin if (reset || reset_ep[j]) begin data_toggle[j] <= 0; ep_put_addr[j][5:0] <= 0; end end end endmodule
module usb_uart_bridge_ep ( input clk, input reset, //////////////////// // out endpoint interface //////////////////// output out_ep_req, // request the data interface for the out endpoint input out_ep_grant, // data interface granted input out_ep_data_avail, // flagging data available to get from the host - stays up until the cycle upon which it is empty input out_ep_setup, // [setup packet sent? - not used here] output out_ep_data_get, // request to get the data input [7:0] out_ep_data, // data from the host output out_ep_stall, // an output enabling the device to stop inputs (not used) input out_ep_acked, // indicating that the outgoing data was acked //////////////////// // in endpoint interface //////////////////// output in_ep_req, // request the data interface for the in endpoint input in_ep_grant, // data interface granted input in_ep_data_free, // end point is ready for data - (specifically there is a buffer and it has space) // after going low it takes a while to get another back, but it does this automatically output in_ep_data_put, // forces end point to read our data output [7:0] in_ep_data, // data back to the host output in_ep_data_done, // signalling that we're done sending data output in_ep_stall, // an output enabling the device to stop outputs (not used) input in_ep_acked, // indicating that the outgoing data was acked // uart pipeline in input [7:0] uart_in_data, input uart_in_valid, output uart_in_ready, // uart pipeline out output [7:0] uart_out_data, output uart_out_valid, input uart_out_ready, output [3:0] debug ); // Timeout counter width. localparam TimeoutWidth = 3; // We don't stall assign out_ep_stall = 1'b0; assign in_ep_stall = 1'b0; // Registers for the out pipeline (out of the module) reg [7:0] uart_out_data_reg; reg [7:0] uart_out_data_overflow_reg; reg uart_out_valid_reg; // registers for the out end point (out of the host) reg out_ep_req_reg; reg out_ep_data_get_reg; // out pipeline / out endpoint state machine state (6 states -> 3 bits) reg [1:0] pipeline_out_state; localparam PipelineOutState_Idle = 0; localparam PipelineOutState_WaitData = 1; localparam PipelineOutState_PushData = 2; localparam PipelineOutState_WaitPipeline = 3; // connect the pipeline registers to the outgoing ports assign uart_out_data = uart_out_data_reg; assign uart_out_valid = uart_out_valid_reg; // automatically make the bus request from the data_available // latch it with out_ep_req_reg assign out_ep_req = ( out_ep_req_reg || out_ep_data_avail ); wire out_granted_data_available; assign out_granted_data_available = out_ep_req && out_ep_grant; assign out_ep_data_get = ( uart_out_ready || ~uart_out_valid_reg ) && out_ep_data_get_reg; reg [7:0] out_stall_data; reg out_stall_valid; // do HOST OUT, DEVICE IN, PIPELINE OUT (!) always @(posedge clk) begin if ( reset ) begin pipeline_out_state <= PipelineOutState_Idle; uart_out_data_reg <= 0; uart_out_valid_reg <= 0; out_ep_req_reg <= 0; out_ep_data_get_reg <= 0; out_stall_data <= 0; out_stall_valid <= 0; end else begin case( pipeline_out_state ) PipelineOutState_Idle: begin // Waiting for the data_available signal indicating that a data packet has arrived if ( out_granted_data_available ) begin // indicate that we want the data out_ep_data_get_reg <= 1; // although the bus has been requested automatically, we latch the request so we control it out_ep_req_reg <= 1; // now wait for the data to set up pipeline_out_state <= PipelineOutState_WaitData; uart_out_valid_reg <= 0; out_stall_data <= 0; out_stall_valid <= 0; end end PipelineOutState_WaitData: begin // it takes one cycle for the juices to start flowing // we got here when we were starting or if the outgoing pipe stalled if ( uart_out_ready || ~uart_out_valid_reg ) begin //if we were stalled, we can send the byte we caught while we were stalled // the actual stalled byte now having been VALID & READY'ed if ( out_stall_valid ) begin uart_out_data_reg <= out_stall_data; uart_out_valid_reg <= 1; out_stall_data <= 0; out_stall_valid <= 0; if ( out_ep_data_avail ) pipeline_out_state <= PipelineOutState_PushData; else begin pipeline_out_state <= PipelineOutState_WaitPipeline; end end else begin pipeline_out_state <= PipelineOutState_PushData; end end end PipelineOutState_PushData: begin // can grab a character if either the out was accepted or the out reg is empty if ( uart_out_ready || ~uart_out_valid_reg ) begin // now we really have got some data and a place to shove it uart_out_data_reg <= out_ep_data; uart_out_valid_reg <= 1; if ( ~out_ep_data_avail ) begin // stop streaming, now just going to wait until the character is accepted out_ep_data_get_reg <= 0; pipeline_out_state <= PipelineOutState_WaitPipeline; end end else begin // We're in push data so there is a character, but our pipeline has stalled // need to save the character and wait. out_stall_data <= out_ep_data; out_stall_valid <= 1; pipeline_out_state <= PipelineOutState_WaitData; if ( ~out_ep_data_avail ) out_ep_data_get_reg <= 0; end end PipelineOutState_WaitPipeline: begin // unhand the bus (don't want to block potential incoming) - be careful, this works instantly! out_ep_req_reg <= 0; if ( uart_out_ready ) begin uart_out_valid_reg <= 0; uart_out_data_reg <= 0; pipeline_out_state <= PipelineOutState_Idle; end end endcase end end // in endpoint control registers reg in_ep_req_reg; reg in_ep_data_done_reg; // in pipeline / in endpoint state machine state (4 states -> 2 bits) reg [1:0] pipeline_in_state; localparam PipelineInState_Idle = 0; localparam PipelineInState_WaitData = 1; localparam PipelineInState_CycleData = 2; localparam PipelineInState_WaitEP = 3; // connect the pipeline register to the outgoing port assign uart_in_ready = ( pipeline_in_state == PipelineInState_CycleData ) && in_ep_data_free; // uart_in_valid and a buffer being ready is the request for the bus. // It is granted automatically if available, and latched on by the SM. // Note once requested, uart_in_valid may go on and off as data is available. // When requested, connect the end point registers to the outgoing ports assign in_ep_req = ( uart_in_valid && in_ep_data_free) || in_ep_req_reg; // Confirmation that the bus was granted wire in_granted_in_valid = in_ep_grant && uart_in_valid; // Here are the things we use to get data sent // ... put this word assign in_ep_data_put = ( pipeline_in_state == PipelineInState_CycleData ) && uart_in_valid && in_ep_data_free; // ... we're done putting - send the buffer assign in_ep_data_done = in_ep_data_done_reg; // ... the actual data, direct from the pipeline to the usb in buffer assign in_ep_data = uart_in_data; // If we have a half filled buffer, send it after a while by using a timer // 4 bits of counter, we'll just count up until bit 3 is high... 8 clock cycles seems more than enough to wait // to send the packet reg [TimeoutWidth:0] in_ep_timeout; // do PIPELINE IN, FPGA/Device OUT, Host IN always @(posedge clk) begin if ( reset ) begin pipeline_in_state <= PipelineInState_Idle; in_ep_req_reg <= 0; in_ep_data_done_reg <= 0; end else begin case( pipeline_in_state ) PipelineInState_Idle: begin in_ep_data_done_reg <= 0; if ( in_granted_in_valid && in_ep_data_free ) begin // got the bus, there is free space, now do the data // confirm request bus - this will hold the request up until we're done with it in_ep_req_reg <= 1; pipeline_in_state <= PipelineInState_CycleData; end end PipelineInState_CycleData: begin if (uart_in_valid ) begin if ( ~in_ep_data_free ) begin // back to idle pipeline_in_state <= PipelineInState_Idle; // release the bus in_ep_req_reg <= 0; end end else begin // No valid character. Let's just pause for a second to see if any more are forthcoming. // clear the timeout counter in_ep_timeout <= 0; pipeline_in_state <= PipelineInState_WaitData; end end PipelineInState_WaitData: begin in_ep_timeout <= in_ep_timeout + 1; if ( uart_in_valid ) begin pipeline_in_state <= PipelineInState_CycleData; end else begin // check for a timeout if ( in_ep_timeout[ TimeoutWidth ] ) begin in_ep_data_done_reg <= 1; pipeline_in_state <= PipelineInState_WaitEP; end end end PipelineInState_WaitEP: begin // maybe done is ignored if putting? in_ep_data_done_reg <= 0; // back to idle pipeline_in_state <= PipelineInState_Idle; // release the bus in_ep_req_reg <= 0; end endcase end end //assign debug = { in_ep_data_free, in_ep_data_done, pipeline_in_state[ 1 ], pipeline_in_state[ 0 ] }; endmodule
module tb_top(); reg clk; reg lfextclk; reg rst_n; wire hfclk = clk; `define CPU_TOP u_e200_soc_top.u_e200_subsys_top.u_e200_subsys_main.u_e200_cpu_top `define EXU `CPU_TOP.u_e200_cpu.u_e200_core.u_e200_exu `define ITCM `CPU_TOP.u_e200_srams.u_e200_itcm_ram.u_e200_itcm_gnrl_ram.u_sirv_sim_ram `define PC_WRITE_TOHOST `E200_PC_SIZE'h80000086 `define PC_EXT_IRQ_BEFOR_MRET `E200_PC_SIZE'h800000a6 `define PC_SFT_IRQ_BEFOR_MRET `E200_PC_SIZE'h800000be `define PC_TMR_IRQ_BEFOR_MRET `E200_PC_SIZE'h800000d6 `define PC_AFTER_SETMTVEC `E200_PC_SIZE'h8000015C wire [`E200_XLEN-1:0] x3 = `EXU.u_e200_exu_regfile.rf_r[3]; wire [`E200_PC_SIZE-1:0] pc = `EXU.u_e200_exu_commit.alu_cmt_i_pc; wire [`E200_PC_SIZE-1:0] pc_vld = `EXU.u_e200_exu_commit.alu_cmt_i_valid; reg [31:0] pc_write_to_host_cnt; reg [31:0] pc_write_to_host_cycle; reg [31:0] valid_ir_cycle; reg [31:0] cycle_count; reg pc_write_to_host_flag; always @(posedge hfclk or negedge rst_n) begin if(rst_n == 1'b0) begin pc_write_to_host_cnt <= 32'b0; pc_write_to_host_flag <= 1'b0; pc_write_to_host_cycle <= 32'b0; end else if (pc_vld & (pc == `PC_WRITE_TOHOST)) begin pc_write_to_host_cnt <= pc_write_to_host_cnt + 1'b1; pc_write_to_host_flag <= 1'b1; if (pc_write_to_host_flag == 1'b0) begin pc_write_to_host_cycle <= cycle_count; end end end always @(posedge hfclk or negedge rst_n) begin if(rst_n == 1'b0) begin cycle_count <= 32'b0; end else begin cycle_count <= cycle_count + 1'b1; end end wire i_valid = `EXU.i_valid; wire i_ready = `EXU.i_ready; always @(posedge hfclk or negedge rst_n) begin if(rst_n == 1'b0) begin valid_ir_cycle <= 32'b0; end else if(i_valid & i_ready & (pc_write_to_host_flag == 1'b0)) begin valid_ir_cycle <= valid_ir_cycle + 1'b1; end end // Randomly force the external interrupt `define EXT_IRQ u_e200_soc_top.u_e200_subsys_top.u_e200_subsys_main.plic_ext_irq `define SFT_IRQ u_e200_soc_top.u_e200_subsys_top.u_e200_subsys_main.clint_sft_irq `define TMR_IRQ u_e200_soc_top.u_e200_subsys_top.u_e200_subsys_main.clint_tmr_irq `define U_CPU u_e200_soc_top.u_e200_subsys_top.u_e200_subsys_main.u_e200_cpu_top.u_e200_cpu `define ITCM_BUS_ERR `U_CPU.u_e200_itcm_ctrl.sram_icb_rsp_err `define ITCM_BUS_READ `U_CPU.u_e200_itcm_ctrl.sram_icb_rsp_read `define STATUS_MIE `U_CPU.u_e200_core.u_e200_exu.u_e200_exu_commit.u_e200_exu_excp.status_mie_r wire stop_assert_irq = (pc_write_to_host_cnt > 32); reg tb_itcm_bus_err; reg tb_ext_irq; reg tb_tmr_irq; reg tb_sft_irq; initial begin tb_ext_irq = 1'b0; tb_tmr_irq = 1'b0; tb_sft_irq = 1'b0; end `ifdef ENABLE_TB_FORCE initial begin tb_itcm_bus_err = 1'b0; #100 @(pc == `PC_AFTER_SETMTVEC ) // Wait the program goes out the reset_vector program forever begin repeat ($urandom_range(1, 20)) @(posedge clk) tb_itcm_bus_err = 1'b0; // Wait random times repeat ($urandom_range(1, 200)) @(posedge clk) tb_itcm_bus_err = 1'b1; // Wait random times if(stop_assert_irq) begin break; end end end initial begin force `EXT_IRQ = tb_ext_irq; force `SFT_IRQ = tb_sft_irq; force `TMR_IRQ = tb_tmr_irq; // We force the bus-error only when: // It is in common code, not in exception code, by checking MIE bit // It is in read operation, not write, otherwise the test cannot recover force `ITCM_BUS_ERR = tb_itcm_bus_err & `STATUS_MIE & `ITCM_BUS_READ ; end initial begin #100 @(pc == `PC_AFTER_SETMTVEC ) // Wait the program goes out the reset_vector program forever begin repeat ($urandom_range(1, 1000)) @(posedge clk) tb_ext_irq = 1'b0; // Wait random times tb_ext_irq = 1'b1; // assert the irq @((pc == `PC_EXT_IRQ_BEFOR_MRET)) // Wait the program run into the IRQ handler by check PC values tb_ext_irq = 1'b0; if(stop_assert_irq) begin break; end end end initial begin #100 @(pc == `PC_AFTER_SETMTVEC ) // Wait the program goes out the reset_vector program forever begin repeat ($urandom_range(1, 1000)) @(posedge clk) tb_sft_irq = 1'b0; // Wait random times tb_sft_irq = 1'b1; // assert the irq @((pc == `PC_SFT_IRQ_BEFOR_MRET)) // Wait the program run into the IRQ handler by check PC values tb_sft_irq = 1'b0; if(stop_assert_irq) begin break; end end end initial begin #100 @(pc == `PC_AFTER_SETMTVEC ) // Wait the program goes out the reset_vector program forever begin repeat ($urandom_range(1, 1000)) @(posedge clk) tb_tmr_irq = 1'b0; // Wait random times tb_tmr_irq = 1'b1; // assert the irq @((pc == `PC_TMR_IRQ_BEFOR_MRET)) // Wait the program run into the IRQ handler by check PC values tb_tmr_irq = 1'b0; if(stop_assert_irq) begin break; end end end `endif reg[8*300:1] testcase; integer dumpwave; initial begin $display("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); if($value$plusargs("TESTCASE=%s",testcase))begin $display("TESTCASE=%s",testcase); end pc_write_to_host_flag <=0; clk <=0; lfextclk <=0; rst_n <=0; #120 rst_n <=1; @(pc_write_to_host_cnt == 32'd8) #10 rst_n <=1; `ifdef ENABLE_TB_FORCE @((~tb_tmr_irq) & (~tb_sft_irq) & (~tb_ext_irq)) #10 rst_n <=1;// Wait the interrupt to complete `endif $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~~~~ Test Result Summary ~~~~~~~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); $display("~TESTCASE: %s ~~~~~~~~~~~~~", testcase); $display("~~~~~~~~~~~~~~Total cycle_count value: %d ~~~~~~~~~~~~~", cycle_count); $display("~~~~~~~~~~The valid Instruction Count: %d ~~~~~~~~~~~~~", valid_ir_cycle); $display("~~~~~The test ending reached at cycle: %d ~~~~~~~~~~~~~", pc_write_to_host_cycle); $display("~~~~~~~~~~~~~~~The final x3 Reg value: %d ~~~~~~~~~~~~~", x3); $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); if (x3 == 1) begin $display("~~~~~~~~~~~~~~~~ TEST_PASS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~ ##### ## #### #### ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~ # # # # # # ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~ # # # # #### #### ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~ ##### ###### # #~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~ # # # # # # #~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~ # # # #### #### ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); end else begin $display("~~~~~~~~~~~~~~~~ TEST_FAIL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~###### ## # # ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~# # # # # ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~##### # # # # ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~# ###### # # ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~# # # # # ~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~# # # # ######~~~~~~~~~~~~~~~~"); $display("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); end #10 $finish; end initial begin #40000000 $display("Time Out !!!"); $finish; end always begin #2 clk <= ~clk; end always begin #33 lfextclk <= ~lfextclk; end initial begin $value$plusargs("DUMPWAVE=%d",dumpwave); if(dumpwave != 0)begin // To add your waveform generation function end end integer i; reg [7:0] itcm_mem [0:(`E200_ITCM_RAM_DP*8)-1]; initial begin $readmemh({testcase, ".verilog"}, itcm_mem); for (i=0;i<(`E200_ITCM_RAM_DP);i=i+1) begin `ITCM.mem_r[i][00+7:00] = itcm_mem[i*8+0]; `ITCM.mem_r[i][08+7:08] = itcm_mem[i*8+1]; `ITCM.mem_r[i][16+7:16] = itcm_mem[i*8+2]; `ITCM.mem_r[i][24+7:24] = itcm_mem[i*8+3]; `ITCM.mem_r[i][32+7:32] = itcm_mem[i*8+4]; `ITCM.mem_r[i][40+7:40] = itcm_mem[i*8+5]; `ITCM.mem_r[i][48+7:48] = itcm_mem[i*8+6]; `ITCM.mem_r[i][56+7:56] = itcm_mem[i*8+7]; end $display("ITCM 0x00: %h", `ITCM.mem_r[8'h00]); $display("ITCM 0x01: %h", `ITCM.mem_r[8'h01]); $display("ITCM 0x02: %h", `ITCM.mem_r[8'h02]); $display("ITCM 0x03: %h", `ITCM.mem_r[8'h03]); $display("ITCM 0x04: %h", `ITCM.mem_r[8'h04]); $display("ITCM 0x05: %h", `ITCM.mem_r[8'h05]); $display("ITCM 0x06: %h", `ITCM.mem_r[8'h06]); $display("ITCM 0x07: %h", `ITCM.mem_r[8'h07]); $display("ITCM 0x16: %h", `ITCM.mem_r[8'h16]); $display("ITCM 0x20: %h", `ITCM.mem_r[8'h20]); end wire jtag_TDI = 1'b0; wire jtag_TDO; wire jtag_TCK = 1'b0; wire jtag_TMS = 1'b0; wire jtag_TRST = 1'b0; wire jtag_DRV_TDO = 1'b0; e200_soc_top u_e200_soc_top( .hfextclk(hfclk), .hfxoscen(), .lfextclk(lfextclk), .lfxoscen(), .io_pads_jtag_TCK_i_ival (jtag_TCK), .io_pads_jtag_TMS_i_ival (jtag_TMS), .io_pads_jtag_TDI_i_ival (jtag_TDI), .io_pads_jtag_TDO_o_oval (jtag_TDO), .io_pads_jtag_TDO_o_oe (), .io_pads_gpio_0_i_ival (1'b1), .io_pads_gpio_0_o_oval (), .io_pads_gpio_0_o_oe (), .io_pads_gpio_0_o_ie (), .io_pads_gpio_0_o_pue (), .io_pads_gpio_0_o_ds (), .io_pads_gpio_1_i_ival (1'b1), .io_pads_gpio_1_o_oval (), .io_pads_gpio_1_o_oe (), .io_pads_gpio_1_o_ie (), .io_pads_gpio_1_o_pue (), .io_pads_gpio_1_o_ds (), .io_pads_gpio_2_i_ival (1'b1), .io_pads_gpio_2_o_oval (), .io_pads_gpio_2_o_oe (), .io_pads_gpio_2_o_ie (), .io_pads_gpio_2_o_pue (), .io_pads_gpio_2_o_ds (), .io_pads_gpio_3_i_ival (1'b1), .io_pads_gpio_3_o_oval (), .io_pads_gpio_3_o_oe (), .io_pads_gpio_3_o_ie (), .io_pads_gpio_3_o_pue (), .io_pads_gpio_3_o_ds (), .io_pads_gpio_4_i_ival (1'b1), .io_pads_gpio_4_o_oval (), .io_pads_gpio_4_o_oe (), .io_pads_gpio_4_o_ie (), .io_pads_gpio_4_o_pue (), .io_pads_gpio_4_o_ds (), .io_pads_gpio_5_i_ival (1'b1), .io_pads_gpio_5_o_oval (), .io_pads_gpio_5_o_oe (), .io_pads_gpio_5_o_ie (), .io_pads_gpio_5_o_pue (), .io_pads_gpio_5_o_ds (), .io_pads_gpio_6_i_ival (1'b1), .io_pads_gpio_6_o_oval (), .io_pads_gpio_6_o_oe (), .io_pads_gpio_6_o_ie (), .io_pads_gpio_6_o_pue (), .io_pads_gpio_6_o_ds (), .io_pads_gpio_7_i_ival (1'b1), .io_pads_gpio_7_o_oval (), .io_pads_gpio_7_o_oe (), .io_pads_gpio_7_o_ie (), .io_pads_gpio_7_o_pue (), .io_pads_gpio_7_o_ds (), .io_pads_gpio_8_i_ival (1'b1), .io_pads_gpio_8_o_oval (), .io_pads_gpio_8_o_oe (), .io_pads_gpio_8_o_ie (), .io_pads_gpio_8_o_pue (), .io_pads_gpio_8_o_ds (), .io_pads_gpio_9_i_ival (1'b1), .io_pads_gpio_9_o_oval (), .io_pads_gpio_9_o_oe (), .io_pads_gpio_9_o_ie (), .io_pads_gpio_9_o_pue (), .io_pads_gpio_9_o_ds (), .io_pads_gpio_10_i_ival (1'b1), .io_pads_gpio_10_o_oval (), .io_pads_gpio_10_o_oe (), .io_pads_gpio_10_o_ie (), .io_pads_gpio_10_o_pue (), .io_pads_gpio_10_o_ds (), .io_pads_gpio_11_i_ival (1'b1), .io_pads_gpio_11_o_oval (), .io_pads_gpio_11_o_oe (), .io_pads_gpio_11_o_ie (), .io_pads_gpio_11_o_pue (), .io_pads_gpio_11_o_ds (), .io_pads_gpio_12_i_ival (1'b1), .io_pads_gpio_12_o_oval (), .io_pads_gpio_12_o_oe (), .io_pads_gpio_12_o_ie (), .io_pads_gpio_12_o_pue (), .io_pads_gpio_12_o_ds (), .io_pads_gpio_13_i_ival (1'b1), .io_pads_gpio_13_o_oval (), .io_pads_gpio_13_o_oe (), .io_pads_gpio_13_o_ie (), .io_pads_gpio_13_o_pue (), .io_pads_gpio_13_o_ds (), .io_pads_gpio_14_i_ival (1'b1), .io_pads_gpio_14_o_oval (), .io_pads_gpio_14_o_oe (), .io_pads_gpio_14_o_ie (), .io_pads_gpio_14_o_pue (), .io_pads_gpio_14_o_ds (), .io_pads_gpio_15_i_ival (1'b1), .io_pads_gpio_15_o_oval (), .io_pads_gpio_15_o_oe (), .io_pads_gpio_15_o_ie (), .io_pads_gpio_15_o_pue (), .io_pads_gpio_15_o_ds (), .io_pads_gpio_16_i_ival (1'b1), .io_pads_gpio_16_o_oval (), .io_pads_gpio_16_o_oe (), .io_pads_gpio_16_o_ie (), .io_pads_gpio_16_o_pue (), .io_pads_gpio_16_o_ds (), .io_pads_gpio_17_i_ival (1'b1), .io_pads_gpio_17_o_oval (), .io_pads_gpio_17_o_oe (), .io_pads_gpio_17_o_ie (), .io_pads_gpio_17_o_pue (), .io_pads_gpio_17_o_ds (), .io_pads_gpio_18_i_ival (1'b1), .io_pads_gpio_18_o_oval (), .io_pads_gpio_18_o_oe (), .io_pads_gpio_18_o_ie (), .io_pads_gpio_18_o_pue (), .io_pads_gpio_18_o_ds (), .io_pads_gpio_19_i_ival (1'b1), .io_pads_gpio_19_o_oval (), .io_pads_gpio_19_o_oe (), .io_pads_gpio_19_o_ie (), .io_pads_gpio_19_o_pue (), .io_pads_gpio_19_o_ds (), .io_pads_gpio_20_i_ival (1'b1), .io_pads_gpio_20_o_oval (), .io_pads_gpio_20_o_oe (), .io_pads_gpio_20_o_ie (), .io_pads_gpio_20_o_pue (), .io_pads_gpio_20_o_ds (), .io_pads_gpio_21_i_ival (1'b1), .io_pads_gpio_21_o_oval (), .io_pads_gpio_21_o_oe (), .io_pads_gpio_21_o_ie (), .io_pads_gpio_21_o_pue (), .io_pads_gpio_21_o_ds (), .io_pads_gpio_22_i_ival (1'b1), .io_pads_gpio_22_o_oval (), .io_pads_gpio_22_o_oe (), .io_pads_gpio_22_o_ie (), .io_pads_gpio_22_o_pue (), .io_pads_gpio_22_o_ds (), .io_pads_gpio_23_i_ival (1'b1), .io_pads_gpio_23_o_oval (), .io_pads_gpio_23_o_oe (), .io_pads_gpio_23_o_ie (), .io_pads_gpio_23_o_pue (), .io_pads_gpio_23_o_ds (), .io_pads_gpio_24_i_ival (1'b1), .io_pads_gpio_24_o_oval (), .io_pads_gpio_24_o_oe (), .io_pads_gpio_24_o_ie (), .io_pads_gpio_24_o_pue (), .io_pads_gpio_24_o_ds (), .io_pads_gpio_25_i_ival (1'b1), .io_pads_gpio_25_o_oval (), .io_pads_gpio_25_o_oe (), .io_pads_gpio_25_o_ie (), .io_pads_gpio_25_o_pue (), .io_pads_gpio_25_o_ds (), .io_pads_gpio_26_i_ival (1'b1), .io_pads_gpio_26_o_oval (), .io_pads_gpio_26_o_oe (), .io_pads_gpio_26_o_ie (), .io_pads_gpio_26_o_pue (), .io_pads_gpio_26_o_ds (), .io_pads_gpio_27_i_ival (1'b1), .io_pads_gpio_27_o_oval (), .io_pads_gpio_27_o_oe (), .io_pads_gpio_27_o_ie (), .io_pads_gpio_27_o_pue (), .io_pads_gpio_27_o_ds (), .io_pads_gpio_28_i_ival (1'b1), .io_pads_gpio_28_o_oval (), .io_pads_gpio_28_o_oe (), .io_pads_gpio_28_o_ie (), .io_pads_gpio_28_o_pue (), .io_pads_gpio_28_o_ds (), .io_pads_gpio_29_i_ival (1'b1), .io_pads_gpio_29_o_oval (), .io_pads_gpio_29_o_oe (), .io_pads_gpio_29_o_ie (), .io_pads_gpio_29_o_pue (), .io_pads_gpio_29_o_ds (), .io_pads_gpio_30_i_ival (1'b1), .io_pads_gpio_30_o_oval (), .io_pads_gpio_30_o_oe (), .io_pads_gpio_30_o_ie (), .io_pads_gpio_30_o_pue (), .io_pads_gpio_30_o_ds (), .io_pads_gpio_31_i_ival (1'b1), .io_pads_gpio_31_o_oval (), .io_pads_gpio_31_o_oe (), .io_pads_gpio_31_o_ie (), .io_pads_gpio_31_o_pue (), .io_pads_gpio_31_o_ds (), .io_pads_qspi_sck_o_oval (), .io_pads_qspi_dq_0_i_ival (1'b1), .io_pads_qspi_dq_0_o_oval (), .io_pads_qspi_dq_0_o_oe (), .io_pads_qspi_dq_0_o_ie (), .io_pads_qspi_dq_0_o_pue (), .io_pads_qspi_dq_0_o_ds (), .io_pads_qspi_dq_1_i_ival (1'b1), .io_pads_qspi_dq_1_o_oval (), .io_pads_qspi_dq_1_o_oe (), .io_pads_qspi_dq_1_o_ie (), .io_pads_qspi_dq_1_o_pue (), .io_pads_qspi_dq_1_o_ds (), .io_pads_qspi_dq_2_i_ival (1'b1), .io_pads_qspi_dq_2_o_oval (), .io_pads_qspi_dq_2_o_oe (), .io_pads_qspi_dq_2_o_ie (), .io_pads_qspi_dq_2_o_pue (), .io_pads_qspi_dq_2_o_ds (), .io_pads_qspi_dq_3_i_ival (1'b1), .io_pads_qspi_dq_3_o_oval (), .io_pads_qspi_dq_3_o_oe (), .io_pads_qspi_dq_3_o_ie (), .io_pads_qspi_dq_3_o_pue (), .io_pads_qspi_dq_3_o_ds (), .io_pads_qspi_cs_0_o_oval (), .io_pads_aon_erst_n_i_ival (rst_n),//This is the real reset, active low .io_pads_aon_pmu_dwakeup_n_i_ival (1'b1), .io_pads_aon_pmu_vddpaden_o_oval (), .io_pads_aon_pmu_padrst_o_oval (), .io_pads_bootrom_n_i_ival (1'b0),// In Simulation we boot from ROM .io_pads_dbgmode0_n_i_ival (1'b1), .io_pads_dbgmode1_n_i_ival (1'b1), .io_pads_dbgmode2_n_i_ival (1'b1) ); endmodule
module sirv_mrom # ( parameter AW = 12, parameter DW = 32, parameter DP = 1024 )( input [AW-1:2] rom_addr, output [DW-1:0] rom_dout ); wire [31:0] mask_rom [0:DP-1];// 4KB = 1KW assign rom_dout = mask_rom[rom_addr]; genvar i; generate if(1) begin: jump_to_ram_gen // Just jump to the ITCM base address for (i=0;i<1024;i=i+1) begin: rom_gen if(i==0) begin: rom0_gen assign mask_rom[i] = 32'h7ffff297; //auipc t0, 0x7ffff end else if(i==1) begin: rom1_gen assign mask_rom[i] = 32'h00028067; //jr t0 end else begin: rom_non01_gen assign mask_rom[i] = 32'h00000000; end end end else begin: jump_to_non_ram_gen // This is the freedom bootrom version, put here have a try // The actual executed trace is as below: // CYC: 8615 PC:00001000 IR:0100006f DASM: j pc + 0x10 // CYC: 8618 PC:00001010 IR:204002b7 DASM: lui t0, 0x20400 xpr[5] = 0x20400000 // CYC: 8621 PC:00001014 IR:00028067 DASM: jr t0 // The 20400000 is the flash address //MEMORY //{ // flash (rxai!w) : ORIGIN = 0x20400000, LENGTH = 512M // ram (wxa!ri) : ORIGIN = 0x80000000, LENGTH = 16K //} for (i=0;i<1024;i=i+1) begin: rom_gen if(i==0) begin: rom0_gen assign mask_rom[i] = 32'h100006f; end else if(i==1) begin: rom1_gen assign mask_rom[i] = 32'h13; end else if(i==2) begin: rom1_gen assign mask_rom[i] = 32'h13; end else if(i==3) begin: rom1_gen assign mask_rom[i] = 32'h6661;// our config code end else if(i==4) begin: rom1_gen //assign mask_rom[i] = 32'h204002b7; assign mask_rom[i] = 32'h20400000 | 32'h000002b7; end else if(i==5) begin: rom1_gen assign mask_rom[i] = 32'h28067; end else begin: rom_non01_gen assign mask_rom[i] = 32'h00000000; end end // In the https://github.com/sifive/freedom/blob/master/bootrom/xip/xip.S // ASM code is as below: // // // See LICENSE for license details. //// Execute in place //// Jump directly to XIP_TARGET_ADDR // // .text // .option norvc // .globl _start //_start: // j 1f // nop // nop //#ifdef CONFIG_STRING // .word cfg_string //#else // .word 0 // Filled in by GenerateBootROM in Chisel //#endif // //1: // li t0, XIP_TARGET_ADDR // jr t0 // // .section .rodata //#ifdef CONFIG_STRING //cfg_string: // .incbin CONFIG_STRING //#endif end endgenerate endmodule
module e203_dtcm_ram( input sd, input ds, input ls, input cs, input we, input [`E203_DTCM_RAM_AW-1:0] addr, input [`E203_DTCM_RAM_MW-1:0] wem, input [`E203_DTCM_RAM_DW-1:0] din, output [`E203_DTCM_RAM_DW-1:0] dout, input rst_n, input clk ); sirv_gnrl_ram #( .FORCE_X2ZERO(1),//Always force X to zeros .DP(`E203_DTCM_RAM_DP), .DW(`E203_DTCM_RAM_DW), .MW(`E203_DTCM_RAM_MW), .AW(`E203_DTCM_RAM_AW) ) u_e203_dtcm_gnrl_ram( .sd (sd ), .ds (ds ), .ls (ls ), .rst_n (rst_n ), .clk (clk ), .cs (cs ), .we (we ), .addr(addr), .din (din ), .wem (wem ), .dout(dout) ); endmodule
module e203_itcm_ram( input sd, input ds, input ls, input cs, input we, input [`E203_ITCM_RAM_AW-1:0] addr, input [`E203_ITCM_RAM_MW-1:0] wem, input [`E203_ITCM_RAM_DW-1:0] din, output [`E203_ITCM_RAM_DW-1:0] dout, input rst_n, input clk ); sirv_gnrl_ram #( `ifndef E203_HAS_ECC//{ .FORCE_X2ZERO(0), `endif//} .DP(`E203_ITCM_RAM_DP), .DW(`E203_ITCM_RAM_DW), .MW(`E203_ITCM_RAM_MW), .AW(`E203_ITCM_RAM_AW) ) u_e203_itcm_gnrl_ram( .sd (sd ), .ds (ds ), .ls (ls ), .rst_n (rst_n ), .clk (clk ), .cs (cs ), .we (we ), .addr(addr), .din (din ), .wem (wem ), .dout(dout) ); endmodule
module fpga_tb_top(); reg CLK100MHZ; reg ck_rst; initial begin CLK100MHZ <=0; ck_rst <=0; #15000 ck_rst <=1; end always begin #10 CLK100MHZ <= ~CLK100MHZ; end system u_system ( .CLK100MHZ(CLK100MHZ), .ck_rst(ck_rst), .led_0(), .led_1(), .led_2(), .led_3(), .led0_r(), .led0_g(), .led0_b(), .led1_r(), .led1_g(), .led1_b(), .led2_r(), .led2_g(), .led2_b(), .sw_0(), .sw_1(), .sw_2(), .sw_3(), .btn_0(), .btn_1(), .btn_2(), .btn_3(), .qspi_cs (), .qspi_sck(), .qspi_dq (), .uart_rxd_out(), .uart_txd_in (), .ja_0(), .ja_1(), .ck_io(), .ck_miso(), .ck_mosi(), .ck_ss (), .ck_sck (), .jd_0(), // TDO .jd_1(), // TRST_n .jd_2(), // TCK .jd_4(), // TDI .jd_5(), // TMS .jd_6() // SRST_n ); endmodule
module firmsoc ( input fifo_ft_clk, output uart_tx, input uart_rx ); wire fifo_ft_clk; wire clk_cpu; wire clk_spi; `ifdef SYNTHESIS // ecp5 pll EHXPLLL #( .PLLRST_ENA("DISABLED"), .INTFB_WAKE("DISABLED"), .STDBY_ENABLE("DISABLED"), .DPHASE_SOURCE("DISABLED"), .OUTDIVIDER_MUXA("DIVA"), .OUTDIVIDER_MUXB("DIVB"), .OUTDIVIDER_MUXC("DIVC"), .OUTDIVIDER_MUXD("DIVD"), .CLKI_DIV(2), .CLKOP_ENABLE("ENABLED"), .CLKOP_DIV(12), .CLKOP_CPHASE(5), .CLKOP_FPHASE(0), .FEEDBK_PATH("CLKOP"), .CLKFB_DIV(1) ) pll_i ( .RST(1'b0), .STDBY(1'b0), .CLKI(fifo_ft_clk), .CLKOP(clk_cpu), .CLKFB(clk_cpu), .CLKINTFB(), .PHASESEL0(1'b0), .PHASESEL1(1'b0), .PHASEDIR(1'b1), .PHASESTEP(1'b1), .PHASELOADREG(1'b1), .PLLWAKESYNC(1'b0), .ENCLKOP(1'b0), ); `else // testbench div_clk div_two_clk( .clk(fifo_ft_clk), .div2_clk(clk_cpu) ); assign clk_spi = fifo_ft_clk; `endif reg [5:0] reset_cnt = 0; wire resetn = &reset_cnt; always @(posedge clk_cpu) begin reset_cnt <= reset_cnt + !resetn; end parameter integer MEM_WORDS = 8192; parameter [31:0] STACKADDR = 32'h 0000_0000 + (4*MEM_WORDS); // end of memory parameter [31:0] PROGADDR_RESET = 32'h 0000_0000; // start of memory reg [31:0] ram [0:MEM_WORDS-1]; initial $readmemh("out/everest_fw.hex", ram); reg [31:0] ram_rdata; reg ram_ready; wire mem_valid; wire mem_instr; wire mem_ready; wire [31:0] mem_addr; wire [31:0] mem_wdata; wire [3:0] mem_wstrb; wire [31:0] mem_rdata; always @(posedge clk_cpu) begin ram_ready <= 1'b0; if (mem_addr[31:24] == 8'h00 && mem_valid) begin if (mem_wstrb[0]) ram[mem_addr[23:2]][7:0] <= mem_wdata[7:0]; if (mem_wstrb[1]) ram[mem_addr[23:2]][15:8] <= mem_wdata[15:8]; if (mem_wstrb[2]) ram[mem_addr[23:2]][23:16] <= mem_wdata[23:16]; if (mem_wstrb[3]) ram[mem_addr[23:2]][31:24] <= mem_wdata[31:24]; ram_rdata <= ram[mem_addr[23:2]]; ram_ready <= 1'b1; end end wire iomem_valid; reg iomem_ready; wire [31:0] iomem_addr; wire [31:0] iomem_wdata; wire [3:0] iomem_wstrb; wire [31:0] iomem_rdata; assign iomem_valid = mem_valid && (mem_addr[31:24] > 8'h 01); assign iomem_wstrb = mem_wstrb; assign iomem_addr = mem_addr; assign iomem_wdata = mem_wdata; wire simpleuart_reg_div_sel = mem_valid && (mem_addr == 32'h 0200_0004); wire [31:0] simpleuart_reg_div_do; wire simpleuart_reg_dat_sel = mem_valid && (mem_addr == 32'h 0200_0008); wire [31:0] simpleuart_reg_dat_do; wire simpleuart_reg_dat_wait; always @(posedge clk_cpu) begin iomem_ready <= 1'b0; if (iomem_valid && iomem_wstrb[0] && mem_addr == 32'h 02000000) begin iomem_ready <= 1'b1; end end assign mem_ready = (iomem_valid && iomem_ready) || simpleuart_reg_div_sel || (simpleuart_reg_dat_sel && !simpleuart_reg_dat_wait) || ram_ready; assign mem_rdata = simpleuart_reg_div_sel ? simpleuart_reg_div_do : simpleuart_reg_dat_sel ? simpleuart_reg_dat_do : ram_rdata; picorv32 #( .STACKADDR(STACKADDR), .PROGADDR_RESET(PROGADDR_RESET), .PROGADDR_IRQ(32'h 0000_0000), .BARREL_SHIFTER(0), .COMPRESSED_ISA(0), .ENABLE_MUL(0), .ENABLE_DIV(0), .ENABLE_IRQ(0), .ENABLE_IRQ_QREGS(0) ) cpu ( .clk (clk_cpu ), .resetn (resetn ), .mem_valid (mem_valid ), .mem_instr (mem_instr ), .mem_ready (mem_ready ), .mem_addr (mem_addr ), .mem_wdata (mem_wdata ), .mem_wstrb (mem_wstrb ), .mem_rdata (mem_rdata ) ); simpleuart simpleuart ( .clk (clk_cpu ), .resetn (resetn ), .ser_tx (uart_tx ), .ser_rx (uart_rx ), .reg_div_we (simpleuart_reg_div_sel ? mem_wstrb : 4'b 0000), .reg_div_di (mem_wdata), .reg_div_do (simpleuart_reg_div_do), .reg_dat_we (simpleuart_reg_dat_sel ? mem_wstrb[0] : 1'b 0), .reg_dat_re (simpleuart_reg_dat_sel && !mem_wstrb), .reg_dat_di (mem_wdata), .reg_dat_do (simpleuart_reg_dat_do), .reg_dat_wait(simpleuart_reg_dat_wait) ); endmodule
module picosoc_regs ( input clk, wen, input [5:0] waddr, input [5:0] raddr1, input [5:0] raddr2, input [31:0] wdata, output [31:0] rdata1, output [31:0] rdata2 ); reg [31:0] regs [0:31]; always @(posedge clk) if (wen) regs[waddr[4:0]] <= wdata; assign rdata1 = regs[raddr1[4:0]]; assign rdata2 = regs[raddr2[4:0]]; endmodule
module simpleuart ( input clk, input resetn, output ser_tx, input ser_rx, input [3:0] reg_div_we, input [31:0] reg_div_di, output [31:0] reg_div_do, input reg_dat_we, input reg_dat_re, input [31:0] reg_dat_di, output [31:0] reg_dat_do, output reg_dat_wait ); reg [31:0] cfg_divider; reg [3:0] recv_state; reg [31:0] recv_divcnt; reg [7:0] recv_pattern; reg [7:0] recv_buf_data; reg recv_buf_valid; reg [9:0] send_pattern; reg [3:0] send_bitcnt; reg [31:0] send_divcnt; reg send_dummy; assign reg_div_do = cfg_divider; assign reg_dat_wait = reg_dat_we && (send_bitcnt || send_dummy); assign reg_dat_do = recv_buf_valid ? recv_buf_data : ~0; always @(posedge clk) begin if (!resetn) begin cfg_divider <= 1; end else begin if (reg_div_we[0]) cfg_divider[ 7: 0] <= reg_div_di[ 7: 0]; if (reg_div_we[1]) cfg_divider[15: 8] <= reg_div_di[15: 8]; if (reg_div_we[2]) cfg_divider[23:16] <= reg_div_di[23:16]; if (reg_div_we[3]) cfg_divider[31:24] <= reg_div_di[31:24]; end end always @(posedge clk) begin if (!resetn) begin recv_state <= 0; recv_divcnt <= 0; recv_pattern <= 0; recv_buf_data <= 0; recv_buf_valid <= 0; end else begin recv_divcnt <= recv_divcnt + 1; if (reg_dat_re) recv_buf_valid <= 0; case (recv_state) 0: begin if (!ser_rx) recv_state <= 1; recv_divcnt <= 0; end 1: begin if (2*recv_divcnt > cfg_divider) begin recv_state <= 2; recv_divcnt <= 0; end end 10: begin if (recv_divcnt > cfg_divider) begin recv_buf_data <= recv_pattern; recv_buf_valid <= 1; recv_state <= 0; end end default: begin if (recv_divcnt > cfg_divider) begin recv_pattern <= {ser_rx, recv_pattern[7:1]}; recv_state <= recv_state + 1; recv_divcnt <= 0; end end endcase end end assign ser_tx = send_pattern[0]; always @(posedge clk) begin if (reg_div_we) send_dummy <= 1; send_divcnt <= send_divcnt + 1; if (!resetn) begin send_pattern <= ~0; send_bitcnt <= 0; send_divcnt <= 0; send_dummy <= 1; end else begin if (send_dummy && !send_bitcnt) begin send_pattern <= ~0; send_bitcnt <= 15; send_divcnt <= 0; send_dummy <= 0; end else if (reg_dat_we && !send_bitcnt) begin send_pattern <= {1'b1, reg_dat_di[7:0], 1'b0}; send_bitcnt <= 10; send_divcnt <= 0; end else if (send_divcnt > cfg_divider && send_bitcnt) begin send_pattern <= {1'b1, send_pattern[9:1]}; send_bitcnt <= send_bitcnt - 1; send_divcnt <= 0; end end end endmodule
module div_clk ( input clk, output div2_clk ); wire clk; wire rst; reg div2_clk; `ifndef SYNTHESIS initial div2_clk = 0; `endif always @(posedge clk) begin div2_clk <= ~div2_clk; end endmodule
module spiflash ( input csb, input clk, inout io0, // MOSI inout io1, // MISO inout io2, inout io3 ); localparam verbose = 0; localparam integer latency = 7; reg [7:0] buffer; integer bitcount = 0; integer bytecount = 0; integer dummycount = 0; reg [7:0] spi_cmd; reg [7:0] xip_cmd = 0; reg [23:0] spi_addr; reg [7:0] spi_in; reg [7:0] spi_out; reg spi_io_vld; reg qpi_mode = 0; reg powered_up = 0; localparam [3:0] mode_spi = 0; localparam [3:0] mode_qpi = 1; localparam [3:0] mode_dspi_rd = 2; localparam [3:0] mode_dspi_wr = 3; localparam [3:0] mode_qspi_rd = 4; localparam [3:0] mode_qspi_wr = 5; localparam [3:0] mode_qspi_ddr_rd = 6; localparam [3:0] mode_qspi_ddr_wr = 7; reg [3:0] mode = 0; reg [3:0] next_mode = 0; reg io0_oe = 0; reg io1_oe = 0; reg io2_oe = 0; reg io3_oe = 0; reg io0_dout = 0; reg io1_dout = 0; reg io2_dout = 0; reg io3_dout = 0; assign #1 io0 = io0_oe ? io0_dout : 1'bz; assign #1 io1 = io1_oe ? io1_dout : 1'bz; assign #1 io2 = io2_oe ? io2_dout : 1'bz; assign #1 io3 = io3_oe ? io3_dout : 1'bz; wire io0_delayed; wire io1_delayed; wire io2_delayed; wire io3_delayed; assign #1 io0_delayed = io0; assign #1 io1_delayed = io1; assign #1 io2_delayed = io2; assign #1 io3_delayed = io3; // 16 MB (128Mb) Flash reg [7:0] memory [0:16*1024*1024-1]; reg [1023:0] firmware_file; initial begin if (!$value$plusargs("firmware=%s", firmware_file)) firmware_file = "firmware.hex"; $readmemh(firmware_file, memory); end task spi_action; begin spi_in = buffer; if (bytecount == 1) begin spi_cmd = buffer; if (spi_cmd == 8'h ab) powered_up = 1; if (spi_cmd == 8'h b9) powered_up = 0; if (spi_cmd == 8'h ff) xip_cmd = 0; if (spi_cmd == 8'h 38) begin qpi_mode = 1; xip_cmd = 0; end if (spi_cmd == 8'h 66) xip_cmd = 0; if (spi_cmd == 8'h 99) begin powered_up = 1; xip_cmd = 0; end end if (powered_up && spi_cmd == 'h 03) begin if (bytecount == 2) spi_addr[23:16] = buffer; if (bytecount == 3) spi_addr[15:8] = buffer; if (bytecount == 4) spi_addr[7:0] = buffer; if (bytecount >= 4) begin buffer = memory[spi_addr]; spi_addr = spi_addr + 1; end end if (powered_up && spi_cmd == 'h bb) begin if (bytecount == 1) mode = mode_dspi_rd; if (bytecount == 2) spi_addr[23:16] = buffer; if (bytecount == 3) spi_addr[15:8] = buffer; if (bytecount == 4) spi_addr[7:0] = buffer; if (bytecount == 5) begin xip_cmd = (buffer == 8'h a5) ? spi_cmd : 8'h 00; mode = mode_dspi_wr; dummycount = latency; end if (bytecount >= 5) begin buffer = memory[spi_addr]; spi_addr = spi_addr + 1; end end if (powered_up && spi_cmd == 'h eb) begin if (bytecount == 1) mode = mode_qspi_rd; if (bytecount == 2) spi_addr[23:16] = buffer; if (bytecount == 3) spi_addr[15:8] = buffer; if (bytecount == 4) spi_addr[7:0] = buffer; if (bytecount == 5) begin xip_cmd = (buffer == 8'h a5) ? spi_cmd : 8'h 00; mode = mode_qspi_wr; dummycount = latency; end if (bytecount >= 5) begin buffer = memory[spi_addr]; spi_addr = spi_addr + 1; end end if (powered_up && spi_cmd == 'h ed) begin if (bytecount == 1) next_mode = mode_qspi_ddr_rd; if (bytecount == 2) spi_addr[23:16] = buffer; if (bytecount == 3) spi_addr[15:8] = buffer; if (bytecount == 4) spi_addr[7:0] = buffer; if (bytecount == 5) begin xip_cmd = (buffer == 8'h a5) ? spi_cmd : 8'h 00; mode = mode_qspi_ddr_wr; dummycount = latency; end if (bytecount >= 5) begin buffer = memory[spi_addr]; spi_addr = spi_addr + 1; end end spi_out = buffer; spi_io_vld = 1; if (verbose) begin if (bytecount == 1) $write("<SPI-START>"); $write("<SPI:%02x:%02x>", spi_in, spi_out); end end endtask task ddr_rd_edge; begin buffer = {buffer, io3_delayed, io2_delayed, io1_delayed, io0_delayed}; bitcount = bitcount + 4; if (bitcount == 8) begin bitcount = 0; bytecount = bytecount + 1; spi_action; end end endtask task ddr_wr_edge; begin io0_oe = 1; io1_oe = 1; io2_oe = 1; io3_oe = 1; io0_dout = buffer[4]; io1_dout = buffer[5]; io2_dout = buffer[6]; io3_dout = buffer[7]; buffer = {buffer, 4'h 0}; bitcount = bitcount + 4; if (bitcount == 8) begin bitcount = 0; bytecount = bytecount + 1; spi_action; end end endtask always @(csb) begin if (csb) begin if (verbose) begin $fflush; end buffer = 0; bitcount = 0; bytecount = 0; if (qpi_mode == 1) begin mode = mode_qpi; end else begin mode = mode_spi; end io0_oe = 0; io1_oe = 0; io2_oe = 0; io3_oe = 0; end else if (xip_cmd) begin buffer = xip_cmd; bitcount = 0; bytecount = 1; spi_action; end end always @(csb, clk) begin spi_io_vld = 0; if (!csb && !clk) begin if (dummycount > 0) begin io0_oe = 0; io1_oe = 0; io2_oe = 0; io3_oe = 0; end else case (mode) mode_spi: begin io0_oe = 0; io1_oe = 1; io2_oe = 0; io3_oe = 0; io1_dout = buffer[7]; end mode_qpi: begin io0_oe = 0; io1_oe = 0; io2_oe = 0; io3_oe = 0; io0_dout = buffer[4]; io1_dout = buffer[5]; io2_dout = buffer[6]; io3_dout = buffer[7]; end mode_dspi_rd: begin io0_oe = 0; io1_oe = 0; io2_oe = 0; io3_oe = 0; end mode_dspi_wr: begin io0_oe = 1; io1_oe = 1; io2_oe = 0; io3_oe = 0; io0_dout = buffer[6]; io1_dout = buffer[7]; end mode_qspi_rd: begin io0_oe = 0; io1_oe = 0; io2_oe = 0; io3_oe = 0; end mode_qspi_wr: begin io0_oe = 1; io1_oe = 1; io2_oe = 1; io3_oe = 1; io0_dout = buffer[4]; io1_dout = buffer[5]; io2_dout = buffer[6]; io3_dout = buffer[7]; end mode_qspi_ddr_rd: begin ddr_rd_edge; end mode_qspi_ddr_wr: begin ddr_wr_edge; end endcase if (next_mode) begin case (next_mode) mode_qspi_ddr_rd: begin io0_oe = 0; io1_oe = 0; io2_oe = 0; io3_oe = 0; end mode_qspi_ddr_wr: begin io0_oe = 1; io1_oe = 1; io2_oe = 1; io3_oe = 1; io0_dout = buffer[4]; io1_dout = buffer[5]; io2_dout = buffer[6]; io3_dout = buffer[7]; end endcase mode = next_mode; next_mode = 0; end end end always @(posedge clk) begin if (!csb) begin if (dummycount > 0) begin dummycount = dummycount - 1; end else case (mode) mode_spi: begin buffer = {buffer, io0}; bitcount = bitcount + 1; if (bitcount == 8) begin bitcount = 0; bytecount = bytecount + 1; spi_action; end end mode_qpi: begin buffer = {buffer, io3, io2, io1, io0}; bitcount = bitcount + 4; if (bitcount == 8) begin bitcount = 0; bytecount = bytecount + 1; spi_action; end end mode_dspi_rd, mode_dspi_wr: begin buffer = {buffer, io1, io0}; bitcount = bitcount + 2; if (bitcount == 8) begin bitcount = 0; bytecount = bytecount + 1; spi_action; end end mode_qspi_rd, mode_qspi_wr: begin buffer = {buffer, io3, io2, io1, io0}; bitcount = bitcount + 4; if (bitcount == 8) begin bitcount = 0; bytecount = bytecount + 1; spi_action; end end mode_qspi_ddr_rd: begin ddr_rd_edge; end mode_qspi_ddr_wr: begin ddr_wr_edge; end endcase end end endmodule
module testbench(); reg clk; always #5 clk = (clk === 1'b0); initial begin $dumpfile("testbench.vcd"); $dumpvars(0, testbench); repeat (10) begin repeat (50000) @(posedge clk); $display("+50000 cycles"); end $finish; end wire [7:0] led; always @(led) begin #1 $display("%b", led); end attosoc uut ( .clk (clk ) ); endmodule
module file_reader_a(output_z_ack,clk,rst,output_z,output_z_stb); integer file_count; integer input_file_0; input output_z_ack; input clk; input rst; output [31:0] output_z; output output_z_stb; reg [31:0] timer; reg timer_enable; reg stage_0_enable; reg stage_1_enable; reg stage_2_enable; reg [3:0] program_counter; reg [3:0] program_counter_0; reg [39:0] instruction_0; reg [3:0] opcode_0; reg [1:0] dest_0; reg [1:0] src_0; reg [1:0] srcb_0; reg [31:0] literal_0; reg [3:0] program_counter_1; reg [3:0] opcode_1; reg [1:0] dest_1; reg [31:0] register_1; reg [31:0] registerb_1; reg [31:0] literal_1; reg [1:0] dest_2; reg [31:0] result_2; reg write_enable_2; reg [31:0] address_2; reg [31:0] data_out_2; reg [31:0] data_in_2; reg memory_enable_2; reg [31:0] address_4; reg [31:0] data_out_4; reg [31:0] data_in_4; reg memory_enable_4; reg [31:0] s_output_z_stb; reg [31:0] s_output_z; reg [39:0] instructions [14:0]; reg [31:0] registers [2:0]; ////////////////////////////////////////////////////////////////////////////// // INSTRUCTION INITIALIZATION // // Initialise the contents of the instruction memory // // Intruction Set // ============== // 0 {'literal': True, 'right': False, 'unsigned': False, 'op': 'jmp_and_link'} // 1 {'literal': False, 'right': False, 'unsigned': False, 'op': 'stop'} // 2 {'literal': True, 'right': False, 'unsigned': False, 'op': 'literal'} // 3 {'file_name': 'stim_a', 'literal': False, 'right': False, 'unsigned': False, 'op': 'file_read'} // 4 {'literal': False, 'right': False, 'unsigned': False, 'op': 'nop'} // 5 {'literal': False, 'right': False, 'unsigned': False, 'op': 'move'} // 6 {'output': 'z', 'literal': False, 'right': False, 'unsigned': False, 'op': 'write'} // 7 {'literal': True, 'right': False, 'unsigned': False, 'op': 'goto'} // 8 {'literal': False, 'right': False, 'unsigned': False, 'op': 'jmp_to_reg'} // Intructions // =========== initial begin instructions[0] = {4'd0, 2'd0, 2'd0, 32'd2};//{'dest': 0, 'label': 2, 'op': 'jmp_and_link'} instructions[1] = {4'd1, 2'd0, 2'd0, 32'd0};//{'op': 'stop'} instructions[2] = {4'd2, 2'd1, 2'd0, 32'd0};//{'dest': 1, 'literal': 0, 'op': 'literal'} instructions[3] = {4'd3, 2'd2, 2'd0, 32'd0};//{'dest': 2, 'file_name': 'stim_a', 'op': 'file_read'} instructions[4] = {4'd4, 2'd0, 2'd0, 32'd0};//{'op': 'nop'} instructions[5] = {4'd4, 2'd0, 2'd0, 32'd0};//{'op': 'nop'} instructions[6] = {4'd5, 2'd1, 2'd2, 32'd0};//{'dest': 1, 'src': 2, 'op': 'move'} instructions[7] = {4'd4, 2'd0, 2'd0, 32'd0};//{'op': 'nop'} instructions[8] = {4'd4, 2'd0, 2'd0, 32'd0};//{'op': 'nop'} instructions[9] = {4'd5, 2'd2, 2'd1, 32'd0};//{'dest': 2, 'src': 1, 'op': 'move'} instructions[10] = {4'd4, 2'd0, 2'd0, 32'd0};//{'op': 'nop'} instructions[11] = {4'd4, 2'd0, 2'd0, 32'd0};//{'op': 'nop'} instructions[12] = {4'd6, 2'd0, 2'd2, 32'd0};//{'src': 2, 'output': 'z', 'op': 'write'} instructions[13] = {4'd7, 2'd0, 2'd0, 32'd3};//{'label': 3, 'op': 'goto'} instructions[14] = {4'd8, 2'd0, 2'd0, 32'd0};//{'src': 0, 'op': 'jmp_to_reg'} end ////////////////////////////////////////////////////////////////////////////// // OPEN FILES // // Open all files used at the start of the process initial begin input_file_0 = $fopenr("stim_a"); end ////////////////////////////////////////////////////////////////////////////// // CPU IMPLEMENTAION OF C PROCESS // // This section of the file contains a CPU implementing the C process. always @(posedge clk) begin write_enable_2 <= 0; //stage 0 instruction fetch if (stage_0_enable) begin stage_1_enable <= 1; instruction_0 <= instructions[program_counter]; opcode_0 = instruction_0[39:36]; dest_0 = instruction_0[35:34]; src_0 = instruction_0[33:32]; srcb_0 = instruction_0[1:0]; literal_0 = instruction_0[31:0]; if(write_enable_2) begin registers[dest_2] <= result_2; end program_counter_0 <= program_counter; program_counter <= program_counter + 1; end //stage 1 opcode fetch if (stage_1_enable) begin stage_2_enable <= 1; register_1 <= registers[src_0]; registerb_1 <= registers[srcb_0]; dest_1 <= dest_0; literal_1 <= literal_0; opcode_1 <= opcode_0; program_counter_1 <= program_counter_0; end //stage 2 opcode fetch if (stage_2_enable) begin dest_2 <= dest_1; case(opcode_1) 16'd0: begin program_counter <= literal_1; result_2 <= program_counter_1 + 1; write_enable_2 <= 1; stage_0_enable <= 1; stage_1_enable <= 0; stage_2_enable <= 0; end 16'd1: begin $fclose(input_file_0); stage_0_enable <= 0; stage_1_enable <= 0; stage_2_enable <= 0; end 16'd2: begin result_2 <= literal_1; write_enable_2 <= 1; end 16'd3: begin file_count = $fscanf(input_file_0, "%d\n", result_2); write_enable_2 <= 1; end 16'd5: begin result_2 <= register_1; write_enable_2 <= 1; end 16'd6: begin stage_0_enable <= 0; stage_1_enable <= 0; stage_2_enable <= 0; s_output_z_stb <= 1'b1; s_output_z <= register_1; end 16'd7: begin program_counter <= literal_1; stage_0_enable <= 1; stage_1_enable <= 0; stage_2_enable <= 0; end 16'd8: begin program_counter <= register_1; stage_0_enable <= 1; stage_1_enable <= 0; stage_2_enable <= 0; end endcase end if (s_output_z_stb == 1'b1 && output_z_ack == 1'b1) begin s_output_z_stb <= 1'b0; stage_0_enable <= 1; stage_1_enable <= 1; stage_2_enable <= 1; end if (timer == 0) begin if (timer_enable) begin stage_0_enable <= 1; stage_1_enable <= 1; stage_2_enable <= 1; timer_enable <= 0; end end else begin timer <= timer - 1; end if (rst == 1'b1) begin stage_0_enable <= 1; stage_1_enable <= 0; stage_2_enable <= 0; timer <= 0; timer_enable <= 0; program_counter <= 0; s_output_z_stb <= 0; end end assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module test_bench_tb; reg clk; reg rst; initial begin rst <= 1'b1; #50 rst <= 1'b0; end initial begin #1000000 $finish; end initial begin clk <= 1'b0; while (1) begin #5 clk <= ~clk; end end test_bench uut( .clk(clk), .rst(rst)); endmodule
module file_writer(input_a,input_a_stb,clk,rst,input_a_ack); integer file_count; integer output_file_0; input [31:0] input_a; input input_a_stb; input clk; input rst; output input_a_ack; reg [31:0] timer; reg timer_enable; reg stage_0_enable; reg stage_1_enable; reg stage_2_enable; reg [2:0] program_counter; reg [2:0] program_counter_0; reg [36:0] instruction_0; reg [2:0] opcode_0; reg dest_0; reg src_0; reg srcb_0; reg [31:0] literal_0; reg [2:0] program_counter_1; reg [2:0] opcode_1; reg dest_1; reg [31:0] register_1; reg [31:0] registerb_1; reg [31:0] literal_1; reg dest_2; reg [31:0] result_2; reg write_enable_2; reg [31:0] address_2; reg [31:0] data_out_2; reg [31:0] data_in_2; reg memory_enable_2; reg [31:0] address_4; reg [31:0] data_out_4; reg [31:0] data_in_4; reg memory_enable_4; reg [31:0] s_input_a_ack; reg [36:0] instructions [7:0]; reg [31:0] registers [1:0]; ////////////////////////////////////////////////////////////////////////////// // INSTRUCTION INITIALIZATION // // Initialise the contents of the instruction memory // // Intruction Set // ============== // 0 {'literal': True, 'right': False, 'unsigned': False, 'op': 'jmp_and_link'} // 1 {'literal': False, 'right': False, 'unsigned': False, 'op': 'stop'} // 2 {'input': 'a', 'literal': False, 'right': False, 'unsigned': False, 'op': 'read'} // 3 {'literal': False, 'right': False, 'unsigned': False, 'op': 'nop'} // 4 {'file_name': 'resp_z', 'literal': False, 'right': False, 'unsigned': False, 'op': 'file_write'} // 5 {'literal': True, 'right': False, 'unsigned': False, 'op': 'goto'} // 6 {'literal': False, 'right': False, 'unsigned': False, 'op': 'jmp_to_reg'} // Intructions // =========== initial begin instructions[0] = {3'd0, 1'd0, 1'd0, 32'd2};//{'dest': 0, 'label': 2, 'op': 'jmp_and_link'} instructions[1] = {3'd1, 1'd0, 1'd0, 32'd0};//{'op': 'stop'} instructions[2] = {3'd2, 1'd1, 1'd0, 32'd0};//{'dest': 1, 'input': 'a', 'op': 'read'} instructions[3] = {3'd3, 1'd0, 1'd0, 32'd0};//{'op': 'nop'} instructions[4] = {3'd3, 1'd0, 1'd0, 32'd0};//{'op': 'nop'} instructions[5] = {3'd4, 1'd0, 1'd1, 32'd0};//{'file_name': 'resp_z', 'src': 1, 'op': 'file_write'} instructions[6] = {3'd5, 1'd0, 1'd0, 32'd2};//{'label': 2, 'op': 'goto'} instructions[7] = {3'd6, 1'd0, 1'd0, 32'd0};//{'src': 0, 'op': 'jmp_to_reg'} end ////////////////////////////////////////////////////////////////////////////// // OPEN FILES // // Open all files used at the start of the process initial begin output_file_0 = $fopen("resp_z"); end ////////////////////////////////////////////////////////////////////////////// // CPU IMPLEMENTAION OF C PROCESS // // This section of the file contains a CPU implementing the C process. always @(posedge clk) begin write_enable_2 <= 0; //stage 0 instruction fetch if (stage_0_enable) begin stage_1_enable <= 1; instruction_0 <= instructions[program_counter]; opcode_0 = instruction_0[36:34]; dest_0 = instruction_0[33:33]; src_0 = instruction_0[32:32]; srcb_0 = instruction_0[0:0]; literal_0 = instruction_0[31:0]; if(write_enable_2) begin registers[dest_2] <= result_2; end program_counter_0 <= program_counter; program_counter <= program_counter + 1; end //stage 1 opcode fetch if (stage_1_enable) begin stage_2_enable <= 1; register_1 <= registers[src_0]; registerb_1 <= registers[srcb_0]; dest_1 <= dest_0; literal_1 <= literal_0; opcode_1 <= opcode_0; program_counter_1 <= program_counter_0; end //stage 2 opcode fetch if (stage_2_enable) begin dest_2 <= dest_1; case(opcode_1) 16'd0: begin program_counter <= literal_1; result_2 <= program_counter_1 + 1; write_enable_2 <= 1; stage_0_enable <= 1; stage_1_enable <= 0; stage_2_enable <= 0; end 16'd1: begin $fclose(output_file_0); stage_0_enable <= 0; stage_1_enable <= 0; stage_2_enable <= 0; end 16'd2: begin stage_0_enable <= 0; stage_1_enable <= 0; stage_2_enable <= 0; s_input_a_ack <= 1'b1; end 16'd4: begin $fdisplay(output_file_0, "%d", register_1); end 16'd5: begin program_counter <= literal_1; stage_0_enable <= 1; stage_1_enable <= 0; stage_2_enable <= 0; end 16'd6: begin program_counter <= register_1; stage_0_enable <= 1; stage_1_enable <= 0; stage_2_enable <= 0; end endcase end if (s_input_a_ack == 1'b1 && input_a_stb == 1'b1) begin result_2 <= input_a; write_enable_2 <= 1; s_input_a_ack <= 1'b0; stage_0_enable <= 1; stage_1_enable <= 1; stage_2_enable <= 1; end if (timer == 0) begin if (timer_enable) begin stage_0_enable <= 1; stage_1_enable <= 1; stage_2_enable <= 1; timer_enable <= 0; end end else begin timer <= timer - 1; end if (rst == 1'b1) begin stage_0_enable <= 1; stage_1_enable <= 0; stage_2_enable <= 0; timer <= 0; timer_enable <= 0; program_counter <= 0; s_input_a_ack <= 0; end end assign input_a_ack = s_input_a_ack; endmodule
module test_bench(clk, rst); input clk; input rst; wire [31:0] wire_39069600; wire wire_39069600_stb; wire wire_39069600_ack; wire [31:0] wire_39795024; wire wire_39795024_stb; wire wire_39795024_ack; wire [31:0] wire_39795168; wire wire_39795168_stb; wire wire_39795168_ack; file_reader_a file_reader_a_39796104( .clk(clk), .rst(rst), .output_z(wire_39069600), .output_z_stb(wire_39069600_stb), .output_z_ack(wire_39069600_ack)); file_reader_b file_reader_b_39759816( .clk(clk), .rst(rst), .output_z(wire_39795024), .output_z_stb(wire_39795024_stb), .output_z_ack(wire_39795024_ack)); file_writer file_writer_39028208( .clk(clk), .rst(rst), .input_a(wire_39795168), .input_a_stb(wire_39795168_stb), .input_a_ack(wire_39795168_ack)); multiplier multiplier_39759952( .clk(clk), .rst(rst), .input_a(wire_39069600), .input_a_stb(wire_39069600_stb), .input_a_ack(wire_39069600_ack), .input_b(wire_39795024), .input_b_stb(wire_39795024_stb), .input_b_ack(wire_39795024_ack), .output_z(wire_39795168), .output_z_stb(wire_39795168_stb), .output_z_ack(wire_39795168_ack)); endmodule
module float_to_int( input_a, input_a_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack); input clk; input rst; input [31:0] input_a; input input_a_stb; output input_a_ack; output [31:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [31:0] s_output_z; reg s_input_a_ack; reg [2:0] state; parameter get_a = 3'd0, special_cases = 3'd1, unpack = 3'd2, convert = 3'd3, put_z = 3'd4; reg [31:0] a_m, a, z; reg [8:0] a_e; reg a_s; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= unpack; end end unpack: begin a_m[31:8] <= {1'b1, a[22 : 0]}; a_m[7:0] <= 0; a_e <= a[30 : 23] - 127; a_s <= a[31]; state <= special_cases; end special_cases: begin if ($signed(a_e) == -127) begin z <= 0; state <= put_z; end else if ($signed(a_e) > 31) begin z <= 32'h80000000; state <= put_z; end else begin state <= convert; end end convert: begin if ($signed(a_e) < 31 && a_m) begin a_e <= a_e + 1; a_m <= a_m >> 1; end else begin if (a_m[31]) begin z <= 32'h80000000; end else begin z <= a_s ? -a_m : a_m; end state <= put_z; end end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module test_bench(clk, rst); input clk; input rst; wire [31:0] wire_39069600; wire wire_39069600_stb; wire wire_39069600_ack; wire [31:0] wire_39795168; wire wire_39795168_stb; wire wire_39795168_ack; file_reader_a file_reader_a_39796104( .clk(clk), .rst(rst), .output_z(wire_39069600), .output_z_stb(wire_39069600_stb), .output_z_ack(wire_39069600_ack)); file_writer file_writer_39028208( .clk(clk), .rst(rst), .input_a(wire_39795168), .input_a_stb(wire_39795168_stb), .input_a_ack(wire_39795168_ack)); float_to_int float_to_int_39759952( .clk(clk), .rst(rst), .input_a(wire_39069600), .input_a_stb(wire_39069600_stb), .input_a_ack(wire_39069600_ack), .output_z(wire_39795168), .output_z_stb(wire_39795168_stb), .output_z_ack(wire_39795168_ack)); endmodule
module file_reader_a(output_z_ack,clk,rst,output_z,output_z_stb); integer file_count; integer input_file_0; input clk; input rst; output [63:0] output_z; output output_z_stb; input output_z_ack; reg [63:0] s_output_z; reg s_output_z_stb; reg [31:0] low; reg [31:0] high; reg [1:0] state; initial begin input_file_0 = $fopenr("stim_a"); end always @(posedge clk) begin case(state) 0: begin state <= 1; end 1: begin file_count = $fscanf(input_file_0, "%d\n", high); state <= 2; end 2: begin file_count = $fscanf(input_file_0, "%d\n", low); state <= 3; end 3: begin s_output_z_stb <= 1; s_output_z[63:32] <= high; s_output_z[31:0] <= low; if(s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= 0; end end endcase if (rst == 1'b1) begin state <= 0; s_output_z_stb <= 0; end end assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module file_writer(input_a,input_a_stb,clk,rst,input_a_ack); integer file_count; integer output_file_0; input clk; input rst; input [63:0] input_a; input input_a_stb; output input_a_ack; reg s_input_a_ack; reg state; reg [63:0] value; initial begin output_file_0 = $fopen("resp_z"); $fclose(output_file_0); end always @(posedge clk) begin case(state) 0: begin s_input_a_ack <= 1'b1; if (s_input_a_ack && input_a_stb) begin value <= input_a; s_input_a_ack <= 1'b0; state <= 1; end end 1: begin output_file_0 = $fopena("resp_z"); $fdisplay(output_file_0, "%d", value[63:32]); $fdisplay(output_file_0, "%d", value[31:0]); $fclose(output_file_0); state <= 0; end endcase if (rst == 1'b1) begin state <= 0; s_input_a_ack <= 0; end end assign input_a_ack = s_input_a_ack; endmodule
module file_reader_b(output_z_ack,clk,rst,output_z,output_z_stb); integer file_count; integer input_file_0; input clk; input rst; output [63:0] output_z; output output_z_stb; input output_z_ack; reg [63:0] s_output_z; reg s_output_z_stb; reg [31:0] low; reg [31:0] high; reg [1:0] state; initial begin input_file_0 = $fopenr("stim_b"); end always @(posedge clk) begin case(state) 0: begin state <= 1; end 1: begin file_count = $fscanf(input_file_0, "%d", high); state <= 2; end 2: begin file_count = $fscanf(input_file_0, "%d", low); state <= 3; end 3: begin s_output_z_stb <= 1; s_output_z[63:32] <= high; s_output_z[31:0] <= low; if(s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= 0; end end endcase if (rst == 1'b1) begin state <= 0; s_output_z_stb <= 0; end end assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module test_bench(clk, rst); input clk; input rst; wire [63:0] wire_39069600; wire wire_39069600_stb; wire wire_39069600_ack; wire [63:0] wire_39795024; wire wire_39795024_stb; wire wire_39795024_ack; wire [63:0] wire_39795168; wire wire_39795168_stb; wire wire_39795168_ack; file_reader_a file_reader_a_39796104( .clk(clk), .rst(rst), .output_z(wire_39069600), .output_z_stb(wire_39069600_stb), .output_z_ack(wire_39069600_ack)); file_reader_b file_reader_b_39759816( .clk(clk), .rst(rst), .output_z(wire_39795024), .output_z_stb(wire_39795024_stb), .output_z_ack(wire_39795024_ack)); file_writer file_writer_39028208( .clk(clk), .rst(rst), .input_a(wire_39795168), .input_a_stb(wire_39795168_stb), .input_a_ack(wire_39795168_ack)); double_adder adder_39759952( .clk(clk), .rst(rst), .input_a(wire_39069600), .input_a_stb(wire_39069600_stb), .input_a_ack(wire_39069600_ack), .input_b(wire_39795024), .input_b_stb(wire_39795024_stb), .input_b_ack(wire_39795024_ack), .output_z(wire_39795168), .output_z_stb(wire_39795168_stb), .output_z_ack(wire_39795168_ack)); endmodule
module double_adder( input_a, input_b, input_a_stb, input_b_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack, input_b_ack); input clk; input rst; input [63:0] input_a; input input_a_stb; output input_a_ack; input [63:0] input_b; input input_b_stb; output input_b_ack; output [63:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [63:0] s_output_z; reg s_input_a_ack; reg s_input_b_ack; reg [3:0] state; parameter get_a = 4'd0, get_b = 4'd1, unpack = 4'd2, special_cases = 4'd3, align = 4'd4, add_0 = 4'd5, add_1 = 4'd6, normalise_1 = 4'd7, normalise_2 = 4'd8, round = 4'd9, pack = 4'd10, put_z = 4'd11; reg [63:0] a, b, z; reg [55:0] a_m, b_m; reg [52:0] z_m; reg [12:0] a_e, b_e, z_e; reg a_s, b_s, z_s; reg guard, round_bit, sticky; reg [56:0] sum; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= get_b; end end get_b: begin s_input_b_ack <= 1; if (s_input_b_ack && input_b_stb) begin b <= input_b; s_input_b_ack <= 0; state <= unpack; end end unpack: begin a_m <= {a[51 : 0], 3'd0}; b_m <= {b[51 : 0], 3'd0}; a_e <= a[62 : 52] - 1023; b_e <= b[62 : 52] - 1023; a_s <= a[63]; b_s <= b[63]; state <= special_cases; end special_cases: begin //if a is NaN or b is NaN return NaN if ((a_e == 1024 && a_m != 0) || (b_e == 1024 && b_m != 0)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; state <= put_z; //if a is inf return inf end else if (a_e == 1024) begin z[63] <= a_s; z[62:52] <= 2047; z[51:0] <= 0; //if a is inf and signs don't match return nan if ((b_e == 1024) && (a_s != b_s)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; end state <= put_z; //if b is inf return inf end else if (b_e == 1024) begin z[63] <= b_s; z[62:52] <= 2047; z[51:0] <= 0; state <= put_z; //if a is zero return b end else if ((($signed(a_e) == -1023) && (a_m == 0)) && (($signed(b_e) == -1023) && (b_m == 0))) begin z[63] <= a_s & b_s; z[62:52] <= b_e[10:0] + 1023; z[51:0] <= b_m[55:3]; state <= put_z; //if a is zero return b end else if (($signed(a_e) == -1023) && (a_m == 0)) begin z[63] <= b_s; z[62:52] <= b_e[10:0] + 1023; z[51:0] <= b_m[55:3]; state <= put_z; //if b is zero return a end else if (($signed(b_e) == -1023) && (b_m == 0)) begin z[63] <= a_s; z[62:52] <= a_e[10:0] + 1023; z[51:0] <= a_m[55:3]; state <= put_z; end else begin //Denormalised Number if ($signed(a_e) == -1023) begin a_e <= -1022; end else begin a_m[55] <= 1; end //Denormalised Number if ($signed(b_e) == -1023) begin b_e <= -1022; end else begin b_m[55] <= 1; end state <= align; end end align: begin if ($signed(a_e) > $signed(b_e)) begin b_e <= b_e + 1; b_m <= b_m >> 1; b_m[0] <= b_m[0] | b_m[1]; end else if ($signed(a_e) < $signed(b_e)) begin a_e <= a_e + 1; a_m <= a_m >> 1; a_m[0] <= a_m[0] | a_m[1]; end else begin state <= add_0; end end add_0: begin z_e <= a_e; if (a_s == b_s) begin sum <= {1'd0, a_m} + b_m; z_s <= a_s; end else begin if (a_m > b_m) begin sum <= {1'd0, a_m} - b_m; z_s <= a_s; end else begin sum <= {1'd0, b_m} - a_m; z_s <= b_s; end end state <= add_1; end add_1: begin if (sum[56]) begin z_m <= sum[56:4]; guard <= sum[3]; round_bit <= sum[2]; sticky <= sum[1] | sum[0]; z_e <= z_e + 1; end else begin z_m <= sum[55:3]; guard <= sum[2]; round_bit <= sum[1]; sticky <= sum[0]; end state <= normalise_1; end normalise_1: begin if (z_m[52] == 0 && $signed(z_e) > -1022) begin z_e <= z_e - 1; z_m <= z_m << 1; z_m[0] <= guard; guard <= round_bit; round_bit <= 0; end else begin state <= normalise_2; end end normalise_2: begin if ($signed(z_e) < -1022) begin z_e <= z_e + 1; z_m <= z_m >> 1; guard <= z_m[0]; round_bit <= guard; sticky <= sticky | round_bit; end else begin state <= round; end end round: begin if (guard && (round_bit | sticky | z_m[0])) begin z_m <= z_m + 1; if (z_m == 53'h1fffffffffffff) begin z_e <=z_e + 1; end end state <= pack; end pack: begin z[51 : 0] <= z_m[51:0]; z[62 : 52] <= z_e[10:0] + 1023; z[63] <= z_s; if ($signed(z_e) == -1022 && z_m[52] == 0) begin z[62 : 52] <= 0; end if ($signed(z_e) == -1022 && z_m[52:0] == 0) begin z[63] <= 0; end //if overflow occurs, return inf if ($signed(z_e) > 1023) begin z[51 : 0] <= 0; z[62 : 52] <= 2047; z[63] <= z_s; end state <= put_z; end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_input_b_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign input_b_ack = s_input_b_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module long_to_double( input_a, input_a_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack); input clk; input rst; input [63:0] input_a; input input_a_stb; output input_a_ack; output [63:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [63:0] s_output_z; reg s_input_a_ack; reg s_input_b_ack; reg [2:0] state; parameter get_a = 3'd0, convert_0 = 3'd1, convert_1 = 3'd2, convert_2 = 3'd3, round = 3'd4, pack = 3'd5, put_z = 3'd6; reg [63:0] a, z, value; reg [52:0] z_m; reg [10:0] z_r; reg [10:0] z_e; reg z_s; reg guard, round_bit, sticky; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= convert_0; end end convert_0: begin if ( a == 0 ) begin z_s <= 0; z_m <= 0; z_e <= -1023; state <= pack; end else begin value <= a[63] ? -a : a; z_s <= a[63]; state <= convert_1; end end convert_1: begin z_e <= 63; z_m <= value[63:11]; z_r <= value[10:0]; state <= convert_2; end convert_2: begin if (!z_m[52]) begin z_e <= z_e - 1; z_m <= z_m << 1; z_m[0] <= z_r[10]; z_r <= z_r << 1; end else begin guard <= z_r[10]; round_bit <= z_r[9]; sticky <= z_r[8:0] != 0; state <= round; end end round: begin if (guard && (round_bit || sticky || z_m[0])) begin z_m <= z_m + 1; if (z_m == 53'h1fffffffffffff) begin z_e <=z_e + 1; end end state <= pack; end pack: begin z[51 : 0] <= z_m[51:0]; z[62 : 52] <= z_e + 1023; z[63] <= z_s; state <= put_z; end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module test_bench(clk, rst); input clk; input rst; wire [63:0] wire_39069600; wire wire_39069600_stb; wire wire_39069600_ack; wire [63:0] wire_39795168; wire wire_39795168_stb; wire wire_39795168_ack; file_reader_a file_reader_a_39796104( .clk(clk), .rst(rst), .output_z(wire_39069600), .output_z_stb(wire_39069600_stb), .output_z_ack(wire_39069600_ack)); file_writer file_writer_39028208( .clk(clk), .rst(rst), .input_a(wire_39795168), .input_a_stb(wire_39795168_stb), .input_a_ack(wire_39795168_ack)); long_to_double int_to_float_39759952( .clk(clk), .rst(rst), .input_a(wire_39069600), .input_a_stb(wire_39069600_stb), .input_a_ack(wire_39069600_ack), .output_z(wire_39795168), .output_z_stb(wire_39795168_stb), .output_z_ack(wire_39795168_ack)); endmodule
module divider( input_a, input_b, input_a_stb, input_b_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack, input_b_ack); input clk; input rst; input [31:0] input_a; input input_a_stb; output input_a_ack; input [31:0] input_b; input input_b_stb; output input_b_ack; output [31:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [31:0] s_output_z; reg s_input_a_ack; reg s_input_b_ack; reg [3:0] state; parameter get_a = 4'd0, get_b = 4'd1, unpack = 4'd2, special_cases = 4'd3, normalise_a = 4'd4, normalise_b = 4'd5, divide_0 = 4'd6, divide_1 = 4'd7, divide_2 = 4'd8, divide_3 = 4'd9, normalise_1 = 4'd10, normalise_2 = 4'd11, round = 4'd12, pack = 4'd13, put_z = 4'd14; reg [31:0] a, b, z; reg [23:0] a_m, b_m, z_m; reg [9:0] a_e, b_e, z_e; reg a_s, b_s, z_s; reg guard, round_bit, sticky; reg [50:0] quotient, divisor, dividend, remainder; reg [5:0] count; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= get_b; end end get_b: begin s_input_b_ack <= 1; if (s_input_b_ack && input_b_stb) begin b <= input_b; s_input_b_ack <= 0; state <= unpack; end end unpack: begin a_m <= a[22 : 0]; b_m <= b[22 : 0]; a_e <= a[30 : 23] - 127; b_e <= b[30 : 23] - 127; a_s <= a[31]; b_s <= b[31]; state <= special_cases; end special_cases: begin //if a is NaN or b is NaN return NaN if ((a_e == 128 && a_m != 0) || (b_e == 128 && b_m != 0)) begin z[31] <= 1; z[30:23] <= 255; z[22] <= 1; z[21:0] <= 0; state <= put_z; //if a is inf and b is inf return NaN end else if ((a_e == 128) && (b_e == 128)) begin z[31] <= 1; z[30:23] <= 255; z[22] <= 1; z[21:0] <= 0; state <= put_z; //if a is inf return inf end else if (a_e == 128) begin z[31] <= a_s ^ b_s; z[30:23] <= 255; z[22:0] <= 0; state <= put_z; //if b is zero return NaN if ($signed(b_e == -127) && (b_m == 0)) begin z[31] <= 1; z[30:23] <= 255; z[22] <= 1; z[21:0] <= 0; state <= put_z; end //if b is inf return zero end else if (b_e == 128) begin z[31] <= a_s ^ b_s; z[30:23] <= 0; z[22:0] <= 0; state <= put_z; //if a is zero return zero end else if (($signed(a_e) == -127) && (a_m == 0)) begin z[31] <= a_s ^ b_s; z[30:23] <= 0; z[22:0] <= 0; state <= put_z; //if b is zero return NaN if (($signed(b_e) == -127) && (b_m == 0)) begin z[31] <= 1; z[30:23] <= 255; z[22] <= 1; z[21:0] <= 0; state <= put_z; end //if b is zero return inf end else if (($signed(b_e) == -127) && (b_m == 0)) begin z[31] <= a_s ^ b_s; z[30:23] <= 255; z[22:0] <= 0; state <= put_z; end else begin //Denormalised Number if ($signed(a_e) == -127) begin a_e <= -126; end else begin a_m[23] <= 1; end //Denormalised Number if ($signed(b_e) == -127) begin b_e <= -126; end else begin b_m[23] <= 1; end state <= normalise_a; end end normalise_a: begin if (a_m[23]) begin state <= normalise_b; end else begin a_m <= a_m << 1; a_e <= a_e - 1; end end normalise_b: begin if (b_m[23]) begin state <= divide_0; end else begin b_m <= b_m << 1; b_e <= b_e - 1; end end divide_0: begin z_s <= a_s ^ b_s; z_e <= a_e - b_e; quotient <= 0; remainder <= 0; count <= 0; dividend <= a_m << 27; divisor <= b_m; state <= divide_1; end divide_1: begin quotient <= quotient << 1; remainder <= remainder << 1; remainder[0] <= dividend[50]; dividend <= dividend << 1; state <= divide_2; end divide_2: begin if (remainder >= divisor) begin quotient[0] <= 1; remainder <= remainder - divisor; end if (count == 49) begin state <= divide_3; end else begin count <= count + 1; state <= divide_1; end end divide_3: begin z_m <= quotient[26:3]; guard <= quotient[2]; round_bit <= quotient[1]; sticky <= quotient[0] | (remainder != 0); state <= normalise_1; end normalise_1: begin if (z_m[23] == 0 && $signed(z_e) > -126) begin z_e <= z_e - 1; z_m <= z_m << 1; z_m[0] <= guard; guard <= round_bit; round_bit <= 0; end else begin state <= normalise_2; end end normalise_2: begin if ($signed(z_e) < -126) begin z_e <= z_e + 1; z_m <= z_m >> 1; guard <= z_m[0]; round_bit <= guard; sticky <= sticky | round_bit; end else begin state <= round; end end round: begin if (guard && (round_bit | sticky | z_m[0])) begin z_m <= z_m + 1; if (z_m == 24'hffffff) begin z_e <=z_e + 1; end end state <= pack; end pack: begin z[22 : 0] <= z_m[22:0]; z[30 : 23] <= z_e[7:0] + 127; z[31] <= z_s; if ($signed(z_e) == -126 && z_m[23] == 0) begin z[30 : 23] <= 0; end //if overflow occurs, return inf if ($signed(z_e) > 127) begin z[22 : 0] <= 0; z[30 : 23] <= 255; z[31] <= z_s; end state <= put_z; end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_input_b_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign input_b_ack = s_input_b_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module test_bench(clk, rst); input clk; input rst; wire [31:0] wire_39069600; wire wire_39069600_stb; wire wire_39069600_ack; wire [31:0] wire_39795024; wire wire_39795024_stb; wire wire_39795024_ack; wire [31:0] wire_39795168; wire wire_39795168_stb; wire wire_39795168_ack; file_reader_a file_reader_a_39796104( .clk(clk), .rst(rst), .output_z(wire_39069600), .output_z_stb(wire_39069600_stb), .output_z_ack(wire_39069600_ack)); file_reader_b file_reader_b_39759816( .clk(clk), .rst(rst), .output_z(wire_39795024), .output_z_stb(wire_39795024_stb), .output_z_ack(wire_39795024_ack)); file_writer file_writer_39028208( .clk(clk), .rst(rst), .input_a(wire_39795168), .input_a_stb(wire_39795168_stb), .input_a_ack(wire_39795168_ack)); divider divider_39759952( .clk(clk), .rst(rst), .input_a(wire_39069600), .input_a_stb(wire_39069600_stb), .input_a_ack(wire_39069600_ack), .input_b(wire_39795024), .input_b_stb(wire_39795024_stb), .input_b_ack(wire_39795024_ack), .output_z(wire_39795168), .output_z_stb(wire_39795168_stb), .output_z_ack(wire_39795168_ack)); endmodule
module double_to_long( input_a, input_a_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack); input clk; input rst; input [63:0] input_a; input input_a_stb; output input_a_ack; output [63:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [63:0] s_output_z; reg s_input_a_ack; reg [2:0] state; parameter get_a = 3'd0, special_cases = 3'd1, unpack = 3'd2, convert = 3'd3, put_z = 3'd4; reg [63:0] a_m, a, z; reg [11:0] a_e; reg a_s; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= unpack; end end unpack: begin a_m[63:11] <= {1'b1, a[51 : 0]}; a_m[10:0] <= 0; a_e <= a[62 : 52] - 1023; a_s <= a[63]; state <= special_cases; end special_cases: begin if ($signed(a_e) == -1023) begin //zero z <= 0; state <= put_z; end else if ($signed(a_e) == 1024 && a[51:0] != 0) begin //nan z <= 64'h8000000000000000; state <= put_z; end else if ($signed(a_e) > 63) begin //too big if (a_s) begin z <= 64'h8000000000000000; end else begin z <= 64'h0000000000000000; end state <= put_z; end else begin state <= convert; end end convert: begin if ($signed(a_e) < 63 && a_m) begin a_e <= a_e + 1; a_m <= a_m >> 1; end else begin if (a_m[63] && a_s) begin z <= 64'h8000000000000000; end else begin z <= a_s ? -a_m : a_m; end state <= put_z; end end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module float_to_double( input_a, input_a_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack); input clk; input rst; input [31:0] input_a; input input_a_stb; output input_a_ack; output [63:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [63:0] s_output_z; reg s_input_a_ack; reg s_input_b_ack; reg [1:0] state; parameter get_a = 3'd0, convert_0 = 3'd1, normalise_0 = 3'd2, put_z = 3'd3; reg [63:0] z; reg [10:0] z_e; reg [52:0] z_m; reg [31:0] a; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= convert_0; end end convert_0: begin z[63] <= a[31]; z[62:52] <= (a[30:23] - 127) + 1023; z[51:0] <= {a[22:0], 29'd0}; if (a[30:23] == 255) begin z[62:52] <= 2047; end state <= put_z; if (a[30:23] == 0) begin if (a[23:0]) begin state <= normalise_0; z_e <= 897; z_m <= {1'd0, a[22:0], 29'd0}; end z[62:52] <= 0; end end normalise_0: begin if (z_m[52]) begin z[62:52] <= z_e; z[51:0] <= z_m[51:0]; state <= put_z; end else begin z_m <= {z_m[51:0], 1'd0}; z_e <= z_e - 1; end end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module test_bench(clk, rst); input clk; input rst; wire [31:0] wire_39069600; wire wire_39069600_stb; wire wire_39069600_ack; wire [63:0] wire_39795168; wire wire_39795168_stb; wire wire_39795168_ack; file_reader_a file_reader_a_39796104( .clk(clk), .rst(rst), .output_z(wire_39069600), .output_z_stb(wire_39069600_stb), .output_z_ack(wire_39069600_ack)); file_writer file_writer_39028208( .clk(clk), .rst(rst), .input_a(wire_39795168), .input_a_stb(wire_39795168_stb), .input_a_ack(wire_39795168_ack)); float_to_double int_to_float_39759952( .clk(clk), .rst(rst), .input_a(wire_39069600), .input_a_stb(wire_39069600_stb), .input_a_ack(wire_39069600_ack), .output_z(wire_39795168), .output_z_stb(wire_39795168_stb), .output_z_ack(wire_39795168_ack)); endmodule
module double_to_float( input_a, input_a_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack); input clk; input rst; input [63:0] input_a; input input_a_stb; output input_a_ack; output [31:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [31:0] s_output_z; reg s_input_a_ack; reg [1:0] state; parameter get_a = 3'd0, unpack = 3'd1, denormalise = 3'd2, put_z = 3'd3; reg [63:0] a; reg [31:0] z; reg [10:0] z_e; reg [23:0] z_m; reg guard; reg round; reg sticky; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= unpack; end end unpack: begin z[31] <= a[63]; state <= put_z; if (a[62:52] == 0) begin z[30:23] <= 0; z[22:0] <= 0; end else if (a[62:52] < 897) begin z[30:23] <= 0; z_m <= {1'd1, a[51:29]}; z_e <= a[62:52]; guard <= a[28]; round <= a[27]; sticky <= a[26:0] != 0; state <= denormalise; end else if (a[62:52] == 2047) begin z[30:23] <= 255; z[22:0] <= 0; if (a[51:0]) begin z[22] <= 1; end end else if (a[62:52] > 1150) begin z[30:23] <= 255; z[22:0] <= 0; end else begin z[30:23] <= (a[62:52] - 1023) + 127; if (a[28] && (a[27] || a[26:0])) begin z[22:0] <= a[51:29] + 1; end else begin z[22:0] <= a[51:29]; end end end denormalise: begin if (z_e == 897 || (z_m == 0 && guard == 0)) begin state <= put_z; z[22:0] <= z_m; if (guard && (round || sticky)) begin z[22:0] <= z_m + 1; end end else begin z_e <= z_e + 1; z_m <= {1'd0, z_m[23:1]}; guard <= z_m[0]; round <= guard; sticky <= sticky | round; end end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module double_divider( input_a, input_b, input_a_stb, input_b_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack, input_b_ack); input clk; input rst; input [63:0] input_a; input input_a_stb; output input_a_ack; input [63:0] input_b; input input_b_stb; output input_b_ack; output [63:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [63:0] s_output_z; reg s_input_a_ack; reg s_input_b_ack; reg [3:0] state; parameter get_a = 4'd0, get_b = 4'd1, unpack = 4'd2, special_cases = 4'd3, normalise_a = 4'd4, normalise_b = 4'd5, divide_0 = 4'd6, divide_1 = 4'd7, divide_2 = 4'd8, divide_3 = 4'd9, normalise_1 = 4'd10, normalise_2 = 4'd11, round = 4'd12, pack = 4'd13, put_z = 4'd14; reg [63:0] a, b, z; reg [52:0] a_m, b_m, z_m; reg [12:0] a_e, b_e, z_e; reg a_s, b_s, z_s; reg guard, round_bit, sticky; reg [108:0] quotient, divisor, dividend, remainder; reg [6:0] count; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= get_b; end end get_b: begin s_input_b_ack <= 1; if (s_input_b_ack && input_b_stb) begin b <= input_b; s_input_b_ack <= 0; state <= unpack; end end unpack: begin a_m <= a[51 : 0]; b_m <= b[51 : 0]; a_e <= a[62 : 52] - 1023; b_e <= b[62 : 52] - 1023; a_s <= a[63]; b_s <= b[63]; state <= special_cases; end special_cases: begin //if a is NaN or b is NaN return NaN if ((a_e == 1024 && a_m != 0) || (b_e == 1024 && b_m != 0)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; state <= put_z; //if a is inf and b is inf return NaN end else if ((a_e == 1024) && (b_e == 1024)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; state <= put_z; //if a is inf return inf end else if (a_e == 1024) begin z[63] <= a_s ^ b_s; z[62:52] <= 2047; z[51:0] <= 0; state <= put_z; //if b is zero return NaN if ($signed(b_e == -1023) && (b_m == 0)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; state <= put_z; end //if b is inf return zero end else if (b_e == 1024) begin z[63] <= a_s ^ b_s; z[62:52] <= 0; z[51:0] <= 0; state <= put_z; //if a is zero return zero end else if (($signed(a_e) == -1023) && (a_m == 0)) begin z[63] <= a_s ^ b_s; z[62:52] <= 0; z[51:0] <= 0; state <= put_z; //if b is zero return NaN if (($signed(b_e) == -1023) && (b_m == 0)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; state <= put_z; end //if b is zero return inf end else if (($signed(b_e) == -1023) && (b_m == 0)) begin z[63] <= a_s ^ b_s; z[62:52] <= 2047; z[51:0] <= 0; state <= put_z; end else begin //Denormalised Number if ($signed(a_e) == -1023) begin a_e <= -1022; end else begin a_m[52] <= 1; end //Denormalised Number if ($signed(b_e) == -1023) begin b_e <= -1022; end else begin b_m[52] <= 1; end state <= normalise_a; end end normalise_a: begin if (a_m[52]) begin state <= normalise_b; end else begin a_m <= a_m << 1; a_e <= a_e - 1; end end normalise_b: begin if (b_m[52]) begin state <= divide_0; end else begin b_m <= b_m << 1; b_e <= b_e - 1; end end divide_0: begin z_s <= a_s ^ b_s; z_e <= a_e - b_e; quotient <= 0; remainder <= 0; count <= 0; dividend <= a_m << 56; divisor <= b_m; state <= divide_1; end divide_1: begin quotient <= quotient << 1; remainder <= remainder << 1; remainder[0] <= dividend[108]; dividend <= dividend << 1; state <= divide_2; end divide_2: begin if (remainder >= divisor) begin quotient[0] <= 1; remainder <= remainder - divisor; end if (count == 107) begin state <= divide_3; end else begin count <= count + 1; state <= divide_1; end end divide_3: begin z_m <= quotient[55:3]; guard <= quotient[2]; round_bit <= quotient[1]; sticky <= quotient[0] | (remainder != 0); state <= normalise_1; end normalise_1: begin if (z_m[52] == 0 && $signed(z_e) > -1022) begin z_e <= z_e - 1; z_m <= z_m << 1; z_m[0] <= guard; guard <= round_bit; round_bit <= 0; end else begin state <= normalise_2; end end normalise_2: begin if ($signed(z_e) < -1022) begin z_e <= z_e + 1; z_m <= z_m >> 1; guard <= z_m[0]; round_bit <= guard; sticky <= sticky | round_bit; end else begin state <= round; end end round: begin if (guard && (round_bit | sticky | z_m[0])) begin z_m <= z_m + 1; if (z_m == 53'hffffff) begin z_e <=z_e + 1; end end state <= pack; end pack: begin z[51 : 0] <= z_m[51:0]; z[62 : 52] <= z_e[10:0] + 1023; z[63] <= z_s; if ($signed(z_e) == -1022 && z_m[52] == 0) begin z[62 : 52] <= 0; end //if overflow occurs, return inf if ($signed(z_e) > 1023) begin z[51 : 0] <= 0; z[62 : 52] <= 2047; z[63] <= z_s; end state <= put_z; end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_input_b_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign input_b_ack = s_input_b_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module int_to_float( input_a, input_a_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack); input clk; input rst; input [31:0] input_a; input input_a_stb; output input_a_ack; output [31:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [31:0] s_output_z; reg s_input_a_ack; reg s_input_b_ack; reg [2:0] state; parameter get_a = 3'd0, convert_0 = 3'd1, convert_1 = 3'd2, convert_2 = 3'd3, round = 3'd4, pack = 3'd5, put_z = 3'd6; reg [31:0] a, z, value; reg [23:0] z_m; reg [7:0] z_r; reg [7:0] z_e; reg z_s; reg guard, round_bit, sticky; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= convert_0; end end convert_0: begin if ( a == 0 ) begin z_s <= 0; z_m <= 0; z_e <= -127; state <= pack; end else begin value <= a[31] ? -a : a; z_s <= a[31]; state <= convert_1; end end convert_1: begin z_e <= 31; z_m <= value[31:8]; z_r <= value[7:0]; state <= convert_2; end convert_2: begin if (!z_m[23]) begin z_e <= z_e - 1; z_m <= z_m << 1; z_m[0] <= z_r[7]; z_r <= z_r << 1; end else begin guard <= z_r[7]; round_bit <= z_r[6]; sticky <= z_r[5:0] != 0; state <= round; end end round: begin if (guard && (round_bit || sticky || z_m[0])) begin z_m <= z_m + 1; if (z_m == 24'hffffff) begin z_e <=z_e + 1; end end state <= pack; end pack: begin z[22 : 0] <= z_m[22:0]; z[30 : 23] <= z_e + 127; z[31] <= z_s; state <= put_z; end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module double_multiplier( input_a, input_b, input_a_stb, input_b_stb, output_z_ack, clk, rst, output_z, output_z_stb, input_a_ack, input_b_ack); input clk; input rst; input [63:0] input_a; input input_a_stb; output input_a_ack; input [63:0] input_b; input input_b_stb; output input_b_ack; output [63:0] output_z; output output_z_stb; input output_z_ack; reg s_output_z_stb; reg [63:0] s_output_z; reg s_input_a_ack; reg s_input_b_ack; reg [3:0] state; parameter get_a = 4'd0, get_b = 4'd1, unpack = 4'd2, special_cases = 4'd3, normalise_a = 4'd4, normalise_b = 4'd5, multiply_0 = 4'd6, multiply_1 = 4'd7, normalise_1 = 4'd8, normalise_2 = 4'd9, round = 4'd10, pack = 4'd11, put_z = 4'd12; reg [63:0] a, b, z; reg [52:0] a_m, b_m, z_m; reg [12:0] a_e, b_e, z_e; reg a_s, b_s, z_s; reg guard, round_bit, sticky; reg [105:0] product; always @(posedge clk) begin case(state) get_a: begin s_input_a_ack <= 1; if (s_input_a_ack && input_a_stb) begin a <= input_a; s_input_a_ack <= 0; state <= get_b; end end get_b: begin s_input_b_ack <= 1; if (s_input_b_ack && input_b_stb) begin b <= input_b; s_input_b_ack <= 0; state <= unpack; end end unpack: begin a_m <= a[51 : 0]; b_m <= b[51 : 0]; a_e <= a[62 : 52] - 1023; b_e <= b[62 : 52] - 1023; a_s <= a[63]; b_s <= b[63]; state <= special_cases; end special_cases: begin //if a is NaN or b is NaN return NaN if ((a_e == 1024 && a_m != 0) || (b_e == 1024 && b_m != 0)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; state <= put_z; //if a is inf return inf end else if (a_e == 1024) begin z[63] <= a_s ^ b_s; z[62:52] <= 2047; z[51:0] <= 0; state <= put_z; //if b is zero return NaN if (($signed(b_e) == -1023) && (b_m == 0)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; state <= put_z; end //if b is inf return inf end else if (b_e == 1024) begin z[63] <= a_s ^ b_s; z[62:52] <= 2047; z[51:0] <= 0; //if b is zero return NaN if (($signed(a_e) == -1023) && (a_m == 0)) begin z[63] <= 1; z[62:52] <= 2047; z[51] <= 1; z[50:0] <= 0; state <= put_z; end state <= put_z; //if a is zero return zero end else if (($signed(a_e) == -1023) && (a_m == 0)) begin z[63] <= a_s ^ b_s; z[62:52] <= 0; z[51:0] <= 0; state <= put_z; //if b is zero return zero end else if (($signed(b_e) == -1023) && (b_m == 0)) begin z[63] <= a_s ^ b_s; z[62:52] <= 0; z[51:0] <= 0; state <= put_z; end else begin //Denormalised Number if ($signed(a_e) == -1023) begin a_e <= -1022; end else begin a_m[52] <= 1; end //Denormalised Number if ($signed(b_e) == -1023) begin b_e <= -1022; end else begin b_m[52] <= 1; end state <= normalise_a; end end normalise_a: begin if (a_m[52]) begin state <= normalise_b; end else begin a_m <= a_m << 1; a_e <= a_e - 1; end end normalise_b: begin if (b_m[52]) begin state <= multiply_0; end else begin b_m <= b_m << 1; b_e <= b_e - 1; end end multiply_0: begin z_s <= a_s ^ b_s; z_e <= a_e + b_e + 1; product <= a_m * b_m; state <= multiply_1; end multiply_1: begin z_m <= product[105:53]; guard <= product[52]; round_bit <= product[51]; sticky <= (product[50:0] != 0); state <= normalise_1; end normalise_1: begin if (z_m[52] == 0) begin z_e <= z_e - 1; z_m <= z_m << 1; z_m[0] <= guard; guard <= round_bit; round_bit <= 0; end else begin state <= normalise_2; end end normalise_2: begin if ($signed(z_e) < -1022) begin z_e <= z_e + 1; z_m <= z_m >> 1; guard <= z_m[0]; round_bit <= guard; sticky <= sticky | round_bit; end else begin state <= round; end end round: begin if (guard && (round_bit | sticky | z_m[0])) begin z_m <= z_m + 1; if (z_m == 53'h1fffffffffffff) begin z_e <=z_e + 1; end end state <= pack; end pack: begin z[51 : 0] <= z_m[51:0]; z[62 : 52] <= z_e[11:0] + 1023; z[63] <= z_s; if ($signed(z_e) == -1022 && z_m[52] == 0) begin z[62 : 52] <= 0; end //if overflow occurs, return inf if ($signed(z_e) > 1023) begin z[51 : 0] <= 0; z[62 : 52] <= 2047; z[63] <= z_s; end state <= put_z; end put_z: begin s_output_z_stb <= 1; s_output_z <= z; if (s_output_z_stb && output_z_ack) begin s_output_z_stb <= 0; state <= get_a; end end endcase if (rst == 1) begin state <= get_a; s_input_a_ack <= 0; s_input_b_ack <= 0; s_output_z_stb <= 0; end end assign input_a_ack = s_input_a_ack; assign input_b_ack = s_input_b_ack; assign output_z_stb = s_output_z_stb; assign output_z = s_output_z; endmodule
module blinky ( input wire clk_p, input wire clk_n, output wire led ); wire clk_ibufg; wire clk; IBUFDS ibuf_inst (.I(clk_p), .IB(clk_n), .O(clk_ibufg)); BUFG bufg_inst (.I(clk_ibufg), .O(clk)); reg [24:0] r_count = 0; always @(posedge(clk)) r_count <= r_count + 1; assign led = r_count[24]; endmodule
module blinky ( input wire clk, output wire led ); reg [24:0] r_count = 0; always @(posedge(clk)) r_count <= r_count + 1; assign led = r_count[24]; endmodule
module uart # ( parameter DATA_WIDTH = 8 ) ( input wire clk, input wire rst, /* * AXI input */ input wire [DATA_WIDTH-1:0] s_axis_tdata, input wire s_axis_tvalid, output wire s_axis_tready, /* * AXI output */ output wire [DATA_WIDTH-1:0] m_axis_tdata, output wire m_axis_tvalid, input wire m_axis_tready, /* * UART interface */ input wire rxd, output wire txd, /* * Status */ output wire tx_busy, output wire rx_busy, output wire rx_overrun_error, output wire rx_frame_error, /* * Configuration */ input wire [15:0] prescale ); uart_tx #( .DATA_WIDTH(DATA_WIDTH) ) uart_tx_inst ( .clk(clk), .rst(rst), // axi input .s_axis_tdata(s_axis_tdata), .s_axis_tvalid(s_axis_tvalid), .s_axis_tready(s_axis_tready), // output .txd(txd), // status .busy(tx_busy), // configuration .prescale(prescale) ); uart_rx #( .DATA_WIDTH(DATA_WIDTH) ) uart_rx_inst ( .clk(clk), .rst(rst), // axi output .m_axis_tdata(m_axis_tdata), .m_axis_tvalid(m_axis_tvalid), .m_axis_tready(m_axis_tready), // input .rxd(rxd), // status .busy(rx_busy), .overrun_error(rx_overrun_error), .frame_error(rx_frame_error), // configuration .prescale(prescale) ); endmodule
module uart_rx # ( parameter DATA_WIDTH = 8 ) ( input wire clk, input wire rst, /* * AXI output */ output wire [DATA_WIDTH-1:0] m_axis_tdata, output wire m_axis_tvalid, input wire m_axis_tready, /* * UART interface */ input wire rxd, /* * Status */ output wire busy, output wire overrun_error, output wire frame_error, /* * Configuration */ input wire [15:0] prescale ); reg [DATA_WIDTH-1:0] m_axis_tdata_reg = 0; reg m_axis_tvalid_reg = 0; reg rxd_reg = 1; reg busy_reg = 0; reg overrun_error_reg = 0; reg frame_error_reg = 0; reg [DATA_WIDTH-1:0] data_reg = 0; reg [18:0] prescale_reg = 0; reg [3:0] bit_cnt = 0; assign m_axis_tdata = m_axis_tdata_reg; assign m_axis_tvalid = m_axis_tvalid_reg; assign busy = busy_reg; assign overrun_error = overrun_error_reg; assign frame_error = frame_error_reg; always @(posedge clk) begin if (rst) begin m_axis_tdata_reg <= 0; m_axis_tvalid_reg <= 0; rxd_reg <= 1; prescale_reg <= 0; bit_cnt <= 0; busy_reg <= 0; overrun_error_reg <= 0; frame_error_reg <= 0; end else begin rxd_reg <= rxd; overrun_error_reg <= 0; frame_error_reg <= 0; if (m_axis_tvalid && m_axis_tready) begin m_axis_tvalid_reg <= 0; end if (prescale_reg > 0) begin prescale_reg <= prescale_reg - 1; end else if (bit_cnt > 0) begin if (bit_cnt > DATA_WIDTH+1) begin if (!rxd_reg) begin bit_cnt <= bit_cnt - 1; prescale_reg <= (prescale << 3)-1; end else begin bit_cnt <= 0; prescale_reg <= 0; end end else if (bit_cnt > 1) begin bit_cnt <= bit_cnt - 1; prescale_reg <= (prescale << 3)-1; data_reg <= {rxd_reg, data_reg[DATA_WIDTH-1:1]}; end else if (bit_cnt == 1) begin bit_cnt <= bit_cnt - 1; if (rxd_reg) begin m_axis_tdata_reg <= data_reg; m_axis_tvalid_reg <= 1; overrun_error_reg <= m_axis_tvalid_reg; end else begin frame_error_reg <= 1; end end end else begin busy_reg <= 0; if (!rxd_reg) begin prescale_reg <= (prescale << 2)-2; bit_cnt <= DATA_WIDTH+2; data_reg <= 0; busy_reg <= 1; end end end end endmodule
module clk_wiz_0 ( // Clock out ports output clk_out1, output clk_out2, output clk_out3, output clk_out4, // Status and control signals input reset, output locked, // Clock in ports input clk_in1 ); clk_wiz_0_clk_wiz inst ( // Clock out ports .clk_out1(clk_out1), .clk_out2(clk_out2), .clk_out3(clk_out3), .clk_out4(clk_out4), // Status and control signals .reset(reset), .locked(locked), // Clock in ports .clk_in1(clk_in1) ); endmodule
module ddr3_top #( parameter real CONTROLLER_CLK_PERIOD = 10, //ns, clock period of the controller interface DDR3_CLK_PERIOD = 2.5, //ns, clock period of the DDR3 RAM device (must be 1/4 of the CONTROLLER_CLK_PERIOD) parameter ROW_BITS = 14, //width of row address COL_BITS = 10, //width of column address BA_BITS = 3, //width of bank address DQ_BITS = 8, //width of DQ LANES = 8, //lanes of DQ AUX_WIDTH = 4, //width of aux line (must be >= 4) WB2_ADDR_BITS = 7, //width of 2nd wishbone address bus WB2_DATA_BITS = 32, //width of 2nd wishbone data bus /* verilator lint_off UNUSEDPARAM */ parameter[0:0] OPT_LOWPOWER = 1, //1 = low power, 0 = low logic OPT_BUS_ABORT = 1, //1 = can abort bus, 0 = no abort (i_wb_cyc will be ignored, ideal for an AXI implementation which cannot abort transaction) /* verilator lint_on UNUSEDPARAM */ MICRON_SIM = 0, //enable faster simulation for micron ddr3 model (shorten POWER_ON_RESET_HIGH and INITIAL_CKE_LOW) TEST_DATAMASK = 0, //add test to datamask during calibration ODELAY_SUPPORTED = 1, //set to 1 when ODELAYE2 is supported parameter // The next parameters act more like a localparam (since user does not have to set this manually) but was added here to simplify port declaration serdes_ratio = $rtoi(CONTROLLER_CLK_PERIOD/DDR3_CLK_PERIOD), wb_addr_bits = ROW_BITS + COL_BITS + BA_BITS - $clog2(serdes_ratio*2), wb_data_bits = DQ_BITS*LANES*serdes_ratio*2, wb_sel_bits = wb_data_bits / 8, wb2_sel_bits = WB2_DATA_BITS / 8, //4 is the width of a single ddr3 command {cs_n, ras_n, cas_n, we_n} plus 3 (ck_en, odt, reset_n) plus bank bits plus row bits cmd_len = 4 + 3 + BA_BITS + ROW_BITS ) ( input wire i_controller_clk, i_ddr3_clk, i_ref_clk, //i_controller_clk = CONTROLLER_CLK_PERIOD, i_ddr3_clk = DDR3_CLK_PERIOD, i_ref_clk = 200MHz input wire i_ddr3_clk_90, //required only when ODELAY_SUPPORTED is zero input wire i_rst_n, // Wishbone inputs input wire i_wb_cyc, //bus cycle active (1 = normal operation, 0 = all ongoing transaction are to be cancelled) input wire i_wb_stb, //request a transfer input wire i_wb_we, //write-enable (1 = write, 0 = read) input wire[wb_addr_bits - 1:0] i_wb_addr, //burst-addressable {row,bank,col} input wire[wb_data_bits - 1:0] i_wb_data, //write data, for a 4:1 controller data width is 8 times the number of pins on the device input wire[wb_sel_bits - 1:0] i_wb_sel, //byte strobe for write (1 = write the byte) input wire[AUX_WIDTH - 1:0] i_aux, //for AXI-interface compatibility (given upon strobe) // Wishbone outputs output wire o_wb_stall, //1 = busy, cannot accept requests output wire o_wb_ack, //1 = read/write request has completed output wire[wb_data_bits - 1:0] o_wb_data, //read data, for a 4:1 controller data width is 8 times the number of pins on the device output wire[AUX_WIDTH - 1:0] o_aux, //for AXI-interface compatibility (given upon strobe) // // Wishbone 2 (PHY) inputs input wire i_wb2_cyc, //bus cycle active (1 = normal operation, 0 = all ongoing transaction are to be cancelled) input wire i_wb2_stb, //request a transfer input wire i_wb2_we, //write-enable (1 = write, 0 = read) input wire[WB2_ADDR_BITS - 1:0] i_wb2_addr, // memory-mapped register to be accessed input wire[WB2_DATA_BITS - 1:0] i_wb2_data, //write data input wire[wb2_sel_bits - 1:0] i_wb2_sel, //byte strobe for write (1 = write the byte) // Wishbone 2 (Controller) outputs output wire o_wb2_stall, //1 = busy, cannot accept requests output wire o_wb2_ack, //1 = read/write request has completed output wire[WB2_DATA_BITS - 1:0] o_wb2_data, //read data // // DDR3 I/O Interface output wire o_ddr3_clk_p, o_ddr3_clk_n, output wire o_ddr3_reset_n, output wire o_ddr3_cke, // CKE output wire o_ddr3_cs_n, // chip select signal output wire o_ddr3_ras_n, // RAS# output wire o_ddr3_cas_n, // CAS# output wire o_ddr3_we_n, // WE# output wire[ROW_BITS-1:0] o_ddr3_addr, output wire[BA_BITS-1:0] o_ddr3_ba_addr, inout wire[(DQ_BITS*LANES)-1:0] io_ddr3_dq, inout wire[(DQ_BITS*LANES)/8-1:0] io_ddr3_dqs, io_ddr3_dqs_n, output wire[LANES-1:0] o_ddr3_dm, output wire o_ddr3_odt, // on-die termination output wire[31:0] o_debug1, output wire[31:0] o_debug2, output wire[31:0] o_debug3 ); // Wire connections between controller and phy wire[cmd_len*serdes_ratio-1:0] cmd; wire dqs_tri_control, dq_tri_control; wire toggle_dqs; wire[wb_data_bits-1:0] data; wire[wb_sel_bits-1:0] dm; wire[LANES-1:0] bitslip; wire[DQ_BITS*LANES*8-1:0] iserdes_data; wire[LANES*8-1:0] iserdes_dqs; wire[LANES*8-1:0] iserdes_bitslip_reference; wire idelayctrl_rdy; wire[4:0] odelay_data_cntvaluein, odelay_dqs_cntvaluein; wire[4:0] idelay_data_cntvaluein, idelay_dqs_cntvaluein; wire[LANES-1:0] odelay_data_ld, odelay_dqs_ld; wire[LANES-1:0] idelay_data_ld, idelay_dqs_ld; wire write_leveling_calib; wire reset; //module instantiations ddr3_controller #( .CONTROLLER_CLK_PERIOD(CONTROLLER_CLK_PERIOD), //ns, clock period of the controller interface .DDR3_CLK_PERIOD(DDR3_CLK_PERIOD), //ns, clock period of the DDR3 RAM device (must be 1/4 of the CONTROLLER_CLK_PERIOD) .ODELAY_SUPPORTED(ODELAY_SUPPORTED), //set to 1 when ODELAYE2 is supported .ROW_BITS(ROW_BITS), //width of row address .COL_BITS(COL_BITS), //width of column address .BA_BITS(BA_BITS), //width of bank address .DQ_BITS(DQ_BITS), //width of DQ .LANES(LANES), //8 lanes of DQ .AUX_WIDTH(AUX_WIDTH), //width of aux line (must be >= 4) .WB2_ADDR_BITS(WB2_ADDR_BITS), //width of 2nd wishbone address bus .WB2_DATA_BITS(WB2_DATA_BITS), //width of 2nd wishbone data bus .OPT_LOWPOWER(OPT_LOWPOWER), //1 = low power, 0 = low logic .OPT_BUS_ABORT(OPT_BUS_ABORT), //1 = can abort bus, 0 = no abort (i_wb_cyc will be ignored, ideal for an AXI implementation which cannot abort transaction) .MICRON_SIM(MICRON_SIM), //simulation for micron ddr3 model (shorten POWER_ON_RESET_HIGH and INITIAL_CKE_LOW) .TEST_DATAMASK(TEST_DATAMASK) //add test to datamask during calibration ) ddr3_controller_inst ( .i_controller_clk(i_controller_clk), //i_controller_clk has period of CONTROLLER_CLK_PERIOD .i_rst_n(i_rst_n), //200MHz input clock // Wishbone inputs .i_wb_cyc(i_wb_cyc), //bus cycle active (1 = normal operation, 0 = all ongoing transaction are to be cancelled) .i_wb_stb(i_wb_stb), //request a transfer .i_wb_we(i_wb_we), //write-enable (1 = write, 0 = read) .i_wb_addr(i_wb_addr), //burst-addressable {row,bank,col} .i_wb_data(i_wb_data), //write data, for a 4:1 controller data width is 8 times the number of pins on the device .i_wb_sel(i_wb_sel), //byte strobe for write (1 = write the byte) .i_aux(i_aux), //for AXI-interface compatibility (given upon strobe) // Wishbone outputs .o_wb_stall(o_wb_stall), //1 = busy, cannot accept requests .o_wb_ack(o_wb_ack), //1 = read/write request has completed .o_wb_data(o_wb_data), //read data, for a 4:1 controller data width is 8 times the number of pins on the device .o_aux(o_aux), //for AXI-interface compatibility (returned upon ack) // Wishbone 2 (PHY) inputs .i_wb2_cyc(i_wb2_cyc), //bus cycle active (1 = normal operation, 0 = all ongoing transaction are to be cancelled) .i_wb2_stb(i_wb2_stb), //request a transfer .i_wb2_we(i_wb2_we), //write-enable (1 = write, 0 = read) .i_wb2_addr(i_wb2_addr), // memory-mapped register to be accessed .i_wb2_data(i_wb2_data), //write data .i_wb2_sel(i_wb2_sel), //byte strobe for write (1 = write the byte) // Wishbone 2 (Controller) outputs .o_wb2_stall(o_wb2_stall), //1 = busy, cannot accept requests .o_wb2_ack(o_wb2_ack), //1 = read/write request has completed .o_wb2_data(o_wb2_data), //read data // // PHY interface .i_phy_iserdes_data(iserdes_data), .i_phy_iserdes_dqs(iserdes_dqs), .i_phy_iserdes_bitslip_reference(iserdes_bitslip_reference), .i_phy_idelayctrl_rdy(idelayctrl_rdy), .o_phy_cmd(cmd), .o_phy_dqs_tri_control(dqs_tri_control), .o_phy_dq_tri_control(dq_tri_control), .o_phy_toggle_dqs(toggle_dqs), .o_phy_data(data), .o_phy_dm(dm), .o_phy_odelay_data_cntvaluein(odelay_data_cntvaluein), .o_phy_odelay_dqs_cntvaluein(odelay_dqs_cntvaluein), .o_phy_idelay_data_cntvaluein(idelay_data_cntvaluein), .o_phy_idelay_dqs_cntvaluein(idelay_dqs_cntvaluein), .o_phy_odelay_data_ld(odelay_data_ld), .o_phy_odelay_dqs_ld(odelay_dqs_ld), .o_phy_idelay_data_ld(idelay_data_ld), .o_phy_idelay_dqs_ld(idelay_dqs_ld), .o_phy_bitslip(bitslip), .o_phy_write_leveling_calib(write_leveling_calib), .o_phy_reset(reset), .o_debug1(o_debug1), .o_debug2(o_debug2) ); ddr3_phy #( .ROW_BITS(ROW_BITS), //width of row address .BA_BITS(BA_BITS), //width of bank address .DQ_BITS(DQ_BITS), //width of DQ .LANES(LANES), //8 lanes of DQ .CONTROLLER_CLK_PERIOD(CONTROLLER_CLK_PERIOD), //ns, period of clock input to this DDR3 controller module .DDR3_CLK_PERIOD(DDR3_CLK_PERIOD), //ns, period of clock input to DDR3 RAM device .ODELAY_SUPPORTED(ODELAY_SUPPORTED) ) ddr3_phy_inst ( .i_controller_clk(i_controller_clk), .i_ddr3_clk(i_ddr3_clk), .i_ref_clk(i_ref_clk), .i_ddr3_clk_90(i_ddr3_clk_90), .i_rst_n(i_rst_n), // Controller Interface .i_controller_reset(reset), .i_controller_cmd(cmd), .i_controller_dqs_tri_control(dqs_tri_control), .i_controller_dq_tri_control(dq_tri_control), .i_controller_toggle_dqs(toggle_dqs), .i_controller_data(data), .i_controller_dm(dm), .i_controller_odelay_data_cntvaluein(odelay_data_cntvaluein), .i_controller_odelay_dqs_cntvaluein(odelay_dqs_cntvaluein), .i_controller_idelay_data_cntvaluein(idelay_data_cntvaluein), .i_controller_idelay_dqs_cntvaluein(idelay_dqs_cntvaluein), .i_controller_odelay_data_ld(odelay_data_ld), .i_controller_odelay_dqs_ld(odelay_dqs_ld), .i_controller_idelay_data_ld(idelay_data_ld), .i_controller_idelay_dqs_ld(idelay_dqs_ld), .i_controller_bitslip(bitslip), .i_controller_write_leveling_calib(write_leveling_calib), .o_controller_iserdes_data(iserdes_data), .o_controller_iserdes_dqs(iserdes_dqs), .o_controller_iserdes_bitslip_reference(iserdes_bitslip_reference), .o_controller_idelayctrl_rdy(idelayctrl_rdy), // DDR3 I/O Interface .o_ddr3_clk_p(o_ddr3_clk_p), .o_ddr3_clk_n(o_ddr3_clk_n), .o_ddr3_reset_n(o_ddr3_reset_n), .o_ddr3_cke(o_ddr3_cke), // CKE .o_ddr3_cs_n(o_ddr3_cs_n), // chip select signal .o_ddr3_ras_n(o_ddr3_ras_n), // RAS# .o_ddr3_cas_n(o_ddr3_cas_n), // CAS# .o_ddr3_we_n(o_ddr3_we_n), // WE# .o_ddr3_addr(o_ddr3_addr), .o_ddr3_ba_addr(o_ddr3_ba_addr), .io_ddr3_dq(io_ddr3_dq), .io_ddr3_dqs(io_ddr3_dqs), .io_ddr3_dqs_n(io_ddr3_dqs_n), .o_ddr3_dm(o_ddr3_dm), .o_ddr3_odt(o_ddr3_odt) // on-die termination ); endmodule
module clk_wiz_0_clk_wiz (// Clock in ports // Clock out ports output clk_out1, output clk_out2, output clk_out3, output clk_out4, // Status and control signals input reset, output locked, input clk_in1 ); // Input buffering //------------------------------------ wire clk_in1_clk_wiz_0; wire clk_in2_clk_wiz_0; IBUF clkin1_ibufg (.O (clk_in1_clk_wiz_0), .I (clk_in1)); // Clocking PRIMITIVE //------------------------------------ // Instantiation of the MMCM PRIMITIVE // * Unused inputs are tied off // * Unused outputs are labeled unused wire clk_out1_clk_wiz_0; wire clk_out2_clk_wiz_0; wire clk_out3_clk_wiz_0; wire clk_out4_clk_wiz_0; wire clk_out5_clk_wiz_0; wire clk_out6_clk_wiz_0; wire clk_out7_clk_wiz_0; wire [15:0] do_unused; wire drdy_unused; wire psdone_unused; wire locked_int; wire clkfbout_clk_wiz_0; wire clkfbout_buf_clk_wiz_0; wire clkfboutb_unused; wire clkout0b_unused; wire clkout1b_unused; wire clkout2b_unused; wire clkout3b_unused; wire clkout4_unused; wire clkout5_unused; wire clkout6_unused; wire clkfbstopped_unused; wire clkinstopped_unused; wire reset_high; PLLE2_ADV #(.BANDWIDTH ("OPTIMIZED"), .COMPENSATION ("INTERNAL"), .STARTUP_WAIT ("FALSE"), .DIVCLK_DIVIDE (1), .CLKFBOUT_MULT (10), .CLKFBOUT_PHASE (0.000), .CLKOUT0_DIVIDE (12), .CLKOUT0_PHASE (0.000), .CLKOUT0_DUTY_CYCLE (0.500), .CLKOUT1_DIVIDE (3), .CLKOUT1_PHASE (0.000), .CLKOUT1_DUTY_CYCLE (0.500), .CLKOUT2_DIVIDE (5), .CLKOUT2_PHASE (0.000), .CLKOUT2_DUTY_CYCLE (0.500), .CLKOUT3_DIVIDE (3), .CLKOUT3_PHASE (90.000), .CLKOUT3_DUTY_CYCLE (0.500), .CLKIN1_PERIOD (10.000)) pll_adv_inst // Output clocks ( .CLKFBOUT (clkfbout_clk_wiz_0), .CLKOUT0 (clk_out1_clk_wiz_0), .CLKOUT1 (clk_out2_clk_wiz_0), .CLKOUT2 (clk_out3_clk_wiz_0), .CLKOUT3 (clk_out4_clk_wiz_0), // Input clock control .CLKFBIN (clkfbout_buf_clk_wiz_0), .CLKIN1 (clk_in1_clk_wiz_0), .CLKIN2 (1'b0), // Tied to always select the primary input clock .CLKINSEL (1'b1), // Ports for dynamic reconfiguration .DADDR (7'h0), .DCLK (1'b0), .DEN (1'b0), .DI (16'h0), .DO (do_unused), .DRDY (drdy_unused), .DWE (1'b0), // Other control and status signals .LOCKED (locked_int), .PWRDWN (1'b0), .RST (reset_high)); assign reset_high = reset; assign locked = locked_int; // Clock Monitor clock assigning //-------------------------------------- // Output buffering //----------------------------------- BUFG clkf_buf (.O (clkfbout_buf_clk_wiz_0), .I (clkfbout_clk_wiz_0)); BUFG clkout1_buf (.O (clk_out1), .I (clk_out1_clk_wiz_0)); BUFG clkout2_buf (.O (clk_out2), .I (clk_out2_clk_wiz_0)); BUFG clkout3_buf (.O (clk_out3), .I (clk_out3_clk_wiz_0)); BUFG clkout4_buf (.O (clk_out4), .I (clk_out4_clk_wiz_0)); endmodule
module uart_tx # ( parameter DATA_WIDTH = 8 ) ( input wire clk, input wire rst, /* * AXI input */ input wire [DATA_WIDTH-1:0] s_axis_tdata, input wire s_axis_tvalid, output wire s_axis_tready, /* * UART interface */ output wire txd, /* * Status */ output wire busy, /* * Configuration */ input wire [15:0] prescale ); reg s_axis_tready_reg = 0; reg txd_reg = 1; reg busy_reg = 0; reg [DATA_WIDTH:0] data_reg = 0; reg [18:0] prescale_reg = 0; reg [3:0] bit_cnt = 0; assign s_axis_tready = s_axis_tready_reg; assign txd = txd_reg; assign busy = busy_reg; always @(posedge clk) begin if (rst) begin s_axis_tready_reg <= 0; txd_reg <= 1; prescale_reg <= 0; bit_cnt <= 0; busy_reg <= 0; end else begin if (prescale_reg > 0) begin s_axis_tready_reg <= 0; prescale_reg <= prescale_reg - 1; end else if (bit_cnt == 0) begin s_axis_tready_reg <= 1; busy_reg <= 0; if (s_axis_tvalid) begin s_axis_tready_reg <= !s_axis_tready_reg; prescale_reg <= (prescale << 3)-1; bit_cnt <= DATA_WIDTH+1; data_reg <= {1'b1, s_axis_tdata}; txd_reg <= 0; busy_reg <= 1; end end else begin if (bit_cnt > 1) begin bit_cnt <= bit_cnt - 1; prescale_reg <= (prescale << 3)-1; {data_reg, txd_reg} <= {1'b0, data_reg}; end else if (bit_cnt == 1) begin bit_cnt <= bit_cnt - 1; prescale_reg <= (prescale << 3); txd_reg <= 1; end end end end endmodule
module arty_ddr3 ( input wire i_clk, input wire i_rst, // DDR3 I/O Interface output wire ddr3_clk_p, ddr3_clk_n, output wire ddr3_reset_n, output wire ddr3_cke, // CKE output wire ddr3_cs_n, // chip select signal output wire ddr3_ras_n, // RAS# output wire ddr3_cas_n, // CAS# output wire ddr3_we_n, // WE# output wire[14-1:0] ddr3_addr, output wire[3-1:0] ddr3_ba, inout wire[16-1:0] ddr3_dq, inout wire[2-1:0] ddr3_dqs_p, ddr3_dqs_n, output wire[2-1:0] ddr3_dm, output wire ddr3_odt, // on-die termination // UART line input wire rx, output wire tx, //Debug LEDs output wire[3:0] led ); wire i_controller_clk, i_ddr3_clk, i_ref_clk, i_ddr3_clk_90; wire m_axis_tvalid; wire rx_empty; wire tx_full; wire o_wb_ack; wire[7:0] o_wb_data; wire o_aux; wire[7:0] rd_data; wire o_wb_stall; reg i_wb_stb = 0, i_wb_we; wire[63:0] o_debug1; reg[7:0] i_wb_data; reg[7:0] i_wb_addr; assign led[0] = (o_debug1[4:0] == 23); //light up if at DONE_CALIBRATE assign led[1] = (o_debug1[4:0] == 23); //light up if at DONE_CALIBRATE assign led[2] = (o_debug1[4:0] == 23); //light up if at DONE_CALIBRATE assign led[3] = (o_debug1[4:0] == 23); //light up if at DONE_CALIBRATE always @(posedge i_controller_clk) begin begin i_wb_stb <= 0; i_wb_we <= 0; i_wb_addr <= 0; i_wb_data <= 0; if(!o_wb_stall && m_axis_tvalid) begin if(rd_data >= 97 && rd_data <= 122) begin //write i_wb_stb <= 1; i_wb_we <= 1; i_wb_addr <= ~rd_data ; i_wb_data <= rd_data; end else if(rd_data >= 65 && rd_data <= 90) begin //read i_wb_stb <= 1; //make request i_wb_we <= 0; //read i_wb_addr <= ~(rd_data + 8'd32); end end end end (* mark_debug = "true" *) wire clk_locked; clk_wiz_0 clk_wiz_inst ( // Clock out ports .clk_out1(i_controller_clk), //83.333 Mhz .clk_out2(i_ddr3_clk), // 333.333 MHz .clk_out3(i_ref_clk), //200MHz .clk_out4(i_ddr3_clk_90), // 333.333 MHz with 90 degree phase shift // Status and control signals .reset(i_rst), .locked(clk_locked), // Clock in ports .clk_in1(i_clk) ); uart #(.DATA_WIDTH(8)) uart_m ( .clk(i_controller_clk), .rst(i_rst), .s_axis_tdata(o_wb_data), .s_axis_tvalid(o_wb_ack), .s_axis_tready(), .m_axis_tdata(rd_data), .m_axis_tvalid(m_axis_tvalid), .m_axis_tready(1), .rxd(rx), .txd(tx), .prescale(1085) //9600 Baud Rate ); // DDR3 Controller ddr3_top #( .ROW_BITS(14), //width of row address .COL_BITS(10), //width of column address .BA_BITS(3), //width of bank address .DQ_BITS(8), //width of DQ .CONTROLLER_CLK_PERIOD(12), //ns, period of clock input to this DDR3 controller module .DDR3_CLK_PERIOD(3), //ns, period of clock input to DDR3 RAM device .ODELAY_SUPPORTED(0), //set to 1 when ODELAYE2 is supported .LANES(2), //8 lanes of DQ .AUX_WIDTH(16), .WB2_ADDR_BITS(32), .WB2_DATA_BITS(32), .OPT_LOWPOWER(1), //1 = low power, 0 = low logic .OPT_BUS_ABORT(1), //1 = can abort bus, 0 = no absort (i_wb_cyc will be ignored, ideal for an AXI implementation which cannot abort transaction) .MICRON_SIM(0), //simulation for micron ddr3 model (shorten POWER_ON_RESET_HIGH and INITIAL_CKE_LOW) .TEST_DATAMASK(1) //add test to datamask during calibration ) ddr3_top ( //clock and reset .i_controller_clk(i_controller_clk), .i_ddr3_clk(i_ddr3_clk), //i_controller_clk has period of CONTROLLER_CLK_PERIOD, i_ddr3_clk has period of DDR3_CLK_PERIOD .i_ref_clk(i_ref_clk), .i_ddr3_clk_90(i_ddr3_clk_90), .i_rst_n(!i_rst && clk_locked), // Wishbone inputs .i_wb_cyc(1), //bus cycle active (1 = normal operation, 0 = all ongoing transaction are to be cancelled) .i_wb_stb(i_wb_stb), //request a transfer .i_wb_we(i_wb_we), //write-enable (1 = write, 0 = read) .i_wb_addr(i_wb_addr), //burst-addressable {row,bank,col} .i_wb_data(i_wb_data), //write data, for a 4:1 controller data width is 8 times the number of pins on the device .i_wb_sel(16'hffff), //byte strobe for write (1 = write the byte) .i_aux(i_wb_we), //for AXI-interface compatibility (given upon strobe) // Wishbone outputs .o_wb_stall(o_wb_stall), //1 = busy, cannot accept requests .o_wb_ack(o_wb_ack), //1 = read/write request has completed .o_wb_data(o_wb_data), //read data, for a 4:1 controller data width is 8 times the number of pins on the device .o_aux(o_aux), // Wishbone 2 (PHY) inputs .i_wb2_cyc(0), //bus cycle active (1 = normal operation, 0 = all ongoing transaction are to be cancelled) .i_wb2_stb(0), //request a transfer .i_wb2_we(), //write-enable (1 = write, 0 = read) .i_wb2_addr(), //burst-addressable {row,bank,col} .i_wb2_data(0), //write data, for a 4:1 controller data width is 8 times the number of pins on the device .i_wb2_sel(0), //byte strobe for write (1 = write the byte) // Wishbone 2 (Controller) outputs .o_wb2_stall(), //1 = busy, cannot accept requests .o_wb2_ack(), //1 = read/write request has completed .o_wb2_data(), //read data, for a 4:1 controller data width is 8 times the number of pins on the device // PHY Interface (to be added later) // DDR3 I/O Interface .o_ddr3_clk_p(ddr3_clk_p), .o_ddr3_clk_n(ddr3_clk_n), .o_ddr3_reset_n(ddr3_reset_n), .o_ddr3_cke(ddr3_cke), // CKE .o_ddr3_cs_n(ddr3_cs_n), // chip select signal (controls rank 1 only) .o_ddr3_ras_n(ddr3_ras_n), // RAS# .o_ddr3_cas_n(ddr3_cas_n), // CAS# .o_ddr3_we_n(ddr3_we_n), // WE# .o_ddr3_addr(ddr3_addr), .o_ddr3_ba_addr(ddr3_ba), .io_ddr3_dq(ddr3_dq), .io_ddr3_dqs(ddr3_dqs_p), .io_ddr3_dqs_n(ddr3_dqs_n), .o_ddr3_dm(ddr3_dm), .o_ddr3_odt(ddr3_odt), // on-die termination .o_debug1(o_debug1) //////////////////////////////////// ); endmodule
module blinky ( input wire clk_p, input wire clk_n, output wire led, input wire button, output reg button_led, output wire diff_led_p, output wire diff_led_n ); wire clk_ibufg; wire clk; IBUFDS ibuf_inst (.I(clk_p), .IB(clk_n), .O(clk_ibufg)); BUFG bufg_inst (.I(clk_ibufg), .O(clk)); reg [26:0] r_count = 0; always @(posedge(clk)) begin r_count <= r_count + 1; button_led <= button; end assign led = r_count[26]; OBUFDS obuf_inst (.I(led), .O(diff_led_p), .OB(diff_led_n)); endmodule
module Ram_1w_1rs #( parameter integer wordCount = 0, parameter integer wordWidth = 0, parameter clockCrossing = 1'b0, parameter technology = "auto", parameter readUnderWrite = "dontCare", parameter integer wrAddressWidth = 0, parameter integer wrDataWidth = 0, parameter integer wrMaskWidth = 0, parameter wrMaskEnable = 1'b0, parameter integer rdAddressWidth = 0, parameter integer rdDataWidth = 0 )( input wr_clk, input wr_en, input [wrMaskWidth-1:0] wr_mask, input [wrAddressWidth-1:0] wr_addr, input [wrDataWidth-1:0] wr_data, input rd_clk, input rd_en, input [rdAddressWidth-1:0] rd_addr, output [rdDataWidth-1:0] rd_data ); generate genvar i; for (i=0;i<wrMaskWidth;i=i+1) begin reg [8-1:0] ram_block [(2**wrAddressWidth)-1:0]; always @ (posedge wr_clk) begin if(wr_en && wr_mask[i]) begin ram_block[wr_addr] <= wr_data[i*8 +:8]; end end reg [8-1:0] ram_rd_data; always @ (posedge rd_clk) begin if(rd_en) begin ram_rd_data <= ram_block[rd_addr]; end end assign rd_data[i*8 +:8] = ram_rd_data; end endgenerate endmodule
module toplevel( input io_J3, input io_H16, input io_G15, output io_G16, input io_F15, output io_B12, input io_B10, output [7:0] io_led ); wire [31:0] io_gpioA_read; wire [31:0] io_gpioA_write; wire [31:0] io_gpioA_writeEnable; wire io_mainClk; wire io_jtag_tck; SB_GB mainClkBuffer ( .USER_SIGNAL_TO_GLOBAL_BUFFER (io_J3), .GLOBAL_BUFFER_OUTPUT ( io_mainClk) ); SB_GB jtagClkBuffer ( .USER_SIGNAL_TO_GLOBAL_BUFFER (io_H16), .GLOBAL_BUFFER_OUTPUT ( io_jtag_tck) ); assign io_led = io_gpioA_write[7 : 0]; Murax murax ( .io_asyncReset(0), .io_mainClk (io_mainClk ), .io_jtag_tck(io_jtag_tck), .io_jtag_tdi(io_G15), .io_jtag_tdo(io_G16), .io_jtag_tms(io_F15), .io_gpioA_read (io_gpioA_read), .io_gpioA_write (io_gpioA_write), .io_gpioA_writeEnable(io_gpioA_writeEnable), .io_uart_txd(io_B12), .io_uart_rxd(io_B10) ); endmodule
module toplevel_pll(REFERENCECLK, PLLOUTCORE, PLLOUTGLOBAL, RESET); input REFERENCECLK; input RESET; /* To initialize the simulation properly, the RESET signal (Active Low) must be asserted at the beginning of the simulation */ output PLLOUTCORE; output PLLOUTGLOBAL; SB_PLL40_CORE toplevel_pll_inst(.REFERENCECLK(REFERENCECLK), .PLLOUTCORE(PLLOUTCORE), .PLLOUTGLOBAL(PLLOUTGLOBAL), .EXTFEEDBACK(), .DYNAMICDELAY(), .RESETB(RESET), .BYPASS(1'b0), .LATCHINPUTVALUE(), .LOCK(), .SDI(), .SDO(), .SCLK()); //\\ Fin=100, Fout=12; defparam toplevel_pll_inst.DIVR = 4'b0010; defparam toplevel_pll_inst.DIVF = 7'b0010110; defparam toplevel_pll_inst.DIVQ = 3'b110; defparam toplevel_pll_inst.FILTER_RANGE = 3'b011; defparam toplevel_pll_inst.FEEDBACK_PATH = "SIMPLE"; defparam toplevel_pll_inst.DELAY_ADJUSTMENT_MODE_FEEDBACK = "FIXED"; defparam toplevel_pll_inst.FDA_FEEDBACK = 4'b0000; defparam toplevel_pll_inst.DELAY_ADJUSTMENT_MODE_RELATIVE = "FIXED"; defparam toplevel_pll_inst.FDA_RELATIVE = 4'b0000; defparam toplevel_pll_inst.SHIFTREG_DIV_MODE = 2'b00; defparam toplevel_pll_inst.PLLOUT_SELECT = "GENCLK"; defparam toplevel_pll_inst.ENABLE_ICEGATE = 1'b0; endmodule
module toplevel( input wire clk100, input wire cpu_reset,//active low input wire tck, input wire tms, input wire tdi, input wire trst,//ignored output reg tdo, input wire serial_rx, output wire serial_tx, input wire user_sw0, input wire user_sw1, input wire user_sw2, input wire user_sw3, input wire user_btn0, input wire user_btn1, input wire user_btn2, input wire user_btn3, output wire user_led0, output wire user_led1, output wire user_led2, output wire user_led3 ); wire [31:0] io_gpioA_read; wire [31:0] io_gpioA_write; wire [31:0] io_gpioA_writeEnable; wire io_asyncReset = ~cpu_reset; assign {user_led3,user_led2,user_led1,user_led0} = io_gpioA_write[3 : 0]; assign io_gpioA_read[3:0] = {user_sw3,user_sw2,user_sw1,user_sw0}; assign io_gpioA_read[7:4] = {user_btn3,user_btn2,user_btn1,user_btn0}; assign io_gpioA_read[11:8] = {tck,tms,tdi,trst}; reg tesic_tck,tesic_tms,tesic_tdi; wire tesic_tdo; reg soc_tck,soc_tms,soc_tdi; wire soc_tdo; always @(*) begin {soc_tck, soc_tms, soc_tdi } = {tck,tms,tdi}; tdo = soc_tdo; end Murax core ( .io_asyncReset(io_asyncReset), .io_mainClk (clk100 ), .io_jtag_tck(soc_tck), .io_jtag_tdi(soc_tdi), .io_jtag_tdo(soc_tdo), .io_jtag_tms(soc_tms), .io_gpioA_read (io_gpioA_read), .io_gpioA_write (io_gpioA_write), .io_gpioA_writeEnable(io_gpioA_writeEnable), .io_uart_txd(serial_tx), .io_uart_rxd(serial_rx) ); endmodule
module SdramCtrlTester_tb ( input io_bus_cmd_valid, output io_bus_cmd_ready, input [23:0] io_bus_cmd_payload_address, input io_bus_cmd_payload_write, input [15:0] io_bus_cmd_payload_data, input [1:0] io_bus_cmd_payload_mask, input [7:0] io_bus_cmd_payload_context, output io_bus_rsp_valid, input io_bus_rsp_ready, output [15:0] io_bus_rsp_payload_data, output [7:0] io_bus_rsp_payload_context, input clk, input reset ); wire [12:0] io_sdram_ADDR; wire [1:0] io_sdram_BA; wire [15:0] io_sdram_DQ; wire [15:0] io_sdram_DQ_read; wire [15:0] io_sdram_DQ_write; wire io_sdram_DQ_writeEnable; wire [1:0] io_sdram_DQM; wire io_sdram_CASn; wire io_sdram_CKE; wire io_sdram_CSn; wire io_sdram_RASn; wire io_sdram_WEn; assign io_sdram_DQ_read = io_sdram_DQ; assign io_sdram_DQ = io_sdram_DQ_writeEnable ? io_sdram_DQ_write : 16'bZZZZZZZZZZZZZZZZ; mt48lc16m16a2 sdram( .Dq(io_sdram_DQ), .Addr(io_sdram_ADDR), .Ba(io_sdram_BA), .Clk(clk), .Cke(io_sdram_CKE), .Cs_n(io_sdram_CSn), .Ras_n(io_sdram_RASn), .Cas_n(io_sdram_CASn), .We_n(io_sdram_WEn), .Dqm(io_sdram_DQM) ); SdramCtrlTester uut ( .io_sdram_ADDR(io_sdram_ADDR), .io_sdram_BA(io_sdram_BA), .io_sdram_DQ_read(io_sdram_DQ_read), .io_sdram_DQ_write(io_sdram_DQ_write), .io_sdram_DQ_writeEnable(io_sdram_DQ_writeEnable), .io_sdram_DQM(io_sdram_DQM), .io_sdram_CASn(io_sdram_CASn), .io_sdram_CKE(io_sdram_CKE), .io_sdram_CSn(io_sdram_CSn), .io_sdram_RASn(io_sdram_RASn), .io_sdram_WEn(io_sdram_WEn), .io_bus_cmd_valid(io_bus_cmd_valid), .io_bus_cmd_ready(io_bus_cmd_ready), .io_bus_cmd_payload_address(io_bus_cmd_payload_address), .io_bus_cmd_payload_write(io_bus_cmd_payload_write), .io_bus_cmd_payload_data(io_bus_cmd_payload_data), .io_bus_cmd_payload_mask(io_bus_cmd_payload_mask), .io_bus_cmd_payload_context(io_bus_cmd_payload_context), .io_bus_rsp_valid(io_bus_rsp_valid), .io_bus_rsp_ready(io_bus_rsp_ready), .io_bus_rsp_payload_data(io_bus_rsp_payload_data), .io_bus_rsp_payload_context(io_bus_rsp_payload_context), .clk(clk), .reset(reset) ); // initial begin // $dumpfile("wave.vcd"); // $dumpvars(0, SdramCtrlTester_tb); // end endmodule
module Dummy(); initial begin $dumpfile("wave.vcd"); $dumpvars(1, Dummy); end endmodule
module BlackBoxToTest #(parameter aWidth=0, parameter bWidth=0) ( input [aWidth-1:0] io_inA, input [bWidth-1:0] io_inB, output reg [aWidth-1:0] io_outA, output reg [bWidth-1:0] io_outB, input io_clockPin, input io_resetPin ); always @ (posedge io_clockPin or posedge io_resetPin) begin if (io_resetPin) begin io_outA <= 0; io_outB <= 0; end else begin io_outA <= io_outA + io_inA; io_outB <= io_outB + io_inB; end end endmodule
module BlackBoxed ( output[7:0] bus3_cmd_read , input [7:0] bus3_cmd_write , input bus3_cmd_writeenable , inout [7:0] bus3_gpio ); assign bus3_gpio = bus3_cmd_writeenable ? bus3_cmd_write : 8'bZZZZZZZZ; assign bus3_cmd_read = bus3_gpio; endmodule
module BlackBoxed ( output bus3_cmd_read , input bus3_cmd_write , input bus3_cmd_writeenable , inout bus3_gpio ); assign bus3_gpio = bus3_cmd_writeenable ? bus3_cmd_write : 1'bZ; assign bus3_cmd_read = bus3_gpio; endmodule
module Axi4SharedSdramCtrlTester_tb ( input io_axi_arw_valid, output io_axi_arw_ready, input [24:0] io_axi_arw_payload_addr, input [1:0] io_axi_arw_payload_id, input [7:0] io_axi_arw_payload_len, input [2:0] io_axi_arw_payload_size, input [1:0] io_axi_arw_payload_burst, input io_axi_arw_payload_write, input io_axi_w_valid, output io_axi_w_ready, input [31:0] io_axi_w_payload_data, input [3:0] io_axi_w_payload_strb, input io_axi_w_payload_last, output io_axi_b_valid, input io_axi_b_ready, output [1:0] io_axi_b_payload_id, output [1:0] io_axi_b_payload_resp, output io_axi_r_valid, input io_axi_r_ready, output [31:0] io_axi_r_payload_data, output [1:0] io_axi_r_payload_id, output [1:0] io_axi_r_payload_resp, output io_axi_r_payload_last, input clk, input reset ); wire [12:0] io_sdram_ADDR; wire [1:0] io_sdram_BA; wire [15:0] io_sdram_DQ; wire [15:0] io_sdram_DQ_read; wire [15:0] io_sdram_DQ_write; wire io_sdram_DQ_writeEnable; wire [1:0] io_sdram_DQM; wire io_sdram_CASn; wire io_sdram_CKE; wire io_sdram_CSn; wire io_sdram_RASn; wire io_sdram_WEn; assign io_sdram_DQ_read = io_sdram_DQ; assign io_sdram_DQ = io_sdram_DQ_writeEnable ? io_sdram_DQ_write : 16'bZZZZZZZZZZZZZZZZ; mt48lc16m16a2 sdram( .Dq(io_sdram_DQ), .Addr(io_sdram_ADDR), .Ba(io_sdram_BA), .Clk(clk), .Cke(io_sdram_CKE), .Cs_n(io_sdram_CSn), .Ras_n(io_sdram_RASn), .Cas_n(io_sdram_CASn), .We_n(io_sdram_WEn), .Dqm(io_sdram_DQM) ); Axi4SharedSdramCtrlTester uut ( .io_sdram_ADDR(io_sdram_ADDR), .io_sdram_BA(io_sdram_BA), .io_sdram_DQ_read(io_sdram_DQ_read), .io_sdram_DQ_write(io_sdram_DQ_write), .io_sdram_DQ_writeEnable(io_sdram_DQ_writeEnable), .io_sdram_DQM(io_sdram_DQM), .io_sdram_CASn(io_sdram_CASn), .io_sdram_CKE(io_sdram_CKE), .io_sdram_CSn(io_sdram_CSn), .io_sdram_RASn(io_sdram_RASn), .io_sdram_WEn(io_sdram_WEn), .io_axi_arw_valid(io_axi_arw_valid), .io_axi_arw_ready(io_axi_arw_ready), .io_axi_arw_payload_addr(io_axi_arw_payload_addr), .io_axi_arw_payload_id(io_axi_arw_payload_id), .io_axi_arw_payload_len(io_axi_arw_payload_len), .io_axi_arw_payload_size(io_axi_arw_payload_size), .io_axi_arw_payload_burst(io_axi_arw_payload_burst), .io_axi_arw_payload_write(io_axi_arw_payload_write), .io_axi_w_valid(io_axi_w_valid), .io_axi_w_ready(io_axi_w_ready), .io_axi_w_payload_data(io_axi_w_payload_data), .io_axi_w_payload_strb(io_axi_w_payload_strb), .io_axi_w_payload_last(io_axi_w_payload_last), .io_axi_b_valid(io_axi_b_valid), .io_axi_b_ready(io_axi_b_ready), .io_axi_b_payload_id(io_axi_b_payload_id), .io_axi_b_payload_resp(io_axi_b_payload_resp), .io_axi_r_valid(io_axi_r_valid), .io_axi_r_ready(io_axi_r_ready), .io_axi_r_payload_data(io_axi_r_payload_data), .io_axi_r_payload_id(io_axi_r_payload_id), .io_axi_r_payload_resp(io_axi_r_payload_resp), .io_axi_r_payload_last(io_axi_r_payload_last), .clk(clk), .reset(reset) ); // initial begin // $dumpfile("wave.vcd"); // $dumpvars(0, SdramCtrlTester_tb); //end endmodule
module PLL ( input clk_in, output clk_out = 0 ); always @ (posedge clk_in) begin clk_out <= ! clk_out; end endmodule
module OSERDESE2 ( OFB, OQ, SHIFTOUT1, SHIFTOUT2, TBYTEOUT, TFB, TQ, CLK, CLKDIV, D1, D2, D3, D4, D5, D6, D7, D8, OCE, RST, SHIFTIN1, SHIFTIN2, T1, T2, T3, T4, TBYTEIN, TCE ); parameter DATA_RATE_OQ = "DDR"; parameter DATA_RATE_TQ = "DDR"; parameter integer DATA_WIDTH = 4; parameter [0:0] INIT_OQ = 1'b0; parameter [0:0] INIT_TQ = 1'b0; parameter [0:0] IS_CLKDIV_INVERTED = 1'b0; parameter [0:0] IS_CLK_INVERTED = 1'b0; parameter [0:0] IS_D1_INVERTED = 1'b0; parameter [0:0] IS_D2_INVERTED = 1'b0; parameter [0:0] IS_D3_INVERTED = 1'b0; parameter [0:0] IS_D4_INVERTED = 1'b0; parameter [0:0] IS_D5_INVERTED = 1'b0; parameter [0:0] IS_D6_INVERTED = 1'b0; parameter [0:0] IS_D7_INVERTED = 1'b0; parameter [0:0] IS_D8_INVERTED = 1'b0; parameter [0:0] IS_T1_INVERTED = 1'b0; parameter [0:0] IS_T2_INVERTED = 1'b0; parameter [0:0] IS_T3_INVERTED = 1'b0; parameter [0:0] IS_T4_INVERTED = 1'b0; `ifdef XIL_TIMING //Simprim parameter LOC = "UNPLACED"; `endif parameter SERDES_MODE = "MASTER"; parameter [0:0] SRVAL_OQ = 1'b0; parameter [0:0] SRVAL_TQ = 1'b0; parameter TBYTE_CTL = "FALSE"; parameter TBYTE_SRC = "FALSE"; parameter integer TRISTATE_WIDTH = 4; localparam in_delay = 0; localparam out_delay = 0; localparam INCLK_DELAY = 0; localparam OUTCLK_DELAY = 0; output OFB; output OQ; output SHIFTOUT1; output SHIFTOUT2; output TBYTEOUT; output TFB; output TQ; input CLK; input CLKDIV; input D1; input D2; input D3; input D4; input D5; input D6; input D7; input D8; input OCE; input RST; input SHIFTIN1; input SHIFTIN2; input T1; input T2; input T3; input T4; input TBYTEIN; input TCE; reg [1:0] counter; reg [7:0] dataA, dataB; reg [3:0] tA, tB; always @ (posedge CLKDIV or posedge RST) begin if (RST) begin end else begin dataA[0] <= D1; dataA[1] <= D2; dataA[2] <= D3; dataA[3] <= D4; dataA[4] <= D5; dataA[5] <= D6; dataA[6] <= D7; dataA[7] <= D8; tA[0] <= T1; tA[1] <= T2; tA[2] <= T3; tA[3] <= T4; end end always @ (posedge CLK or posedge RST) begin if (RST) begin counter <= 3; end else begin counter <= counter + 1; if(counter == DATA_WIDTH/2-1) begin counter <= 0; dataB <= dataA; tB <= tA; end; end end assign TQ = tB[0]; assign OQ = dataB[counter*2 + 1 - CLK]; endmodule
module ISERDESE2 ( O, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, SHIFTOUT1, SHIFTOUT2, BITSLIP, CE1, CE2, CLK, CLKB, CLKDIV, CLKDIVP, D, DDLY, DYNCLKDIVSEL, DYNCLKSEL, OCLK, OCLKB, OFB, RST, SHIFTIN1, SHIFTIN2 ); parameter DATA_RATE = "DDR"; parameter integer DATA_WIDTH = 4; parameter DYN_CLKDIV_INV_EN = "FALSE"; parameter DYN_CLK_INV_EN = "FALSE"; parameter [0:0] INIT_Q1 = 1'b0; parameter [0:0] INIT_Q2 = 1'b0; parameter [0:0] INIT_Q3 = 1'b0; parameter [0:0] INIT_Q4 = 1'b0; parameter INTERFACE_TYPE = "MEMORY"; parameter IOBDELAY = "NONE"; parameter [0:0] IS_CLKB_INVERTED = 1'b0; parameter [0:0] IS_CLKDIVP_INVERTED = 1'b0; parameter [0:0] IS_CLKDIV_INVERTED = 1'b0; parameter [0:0] IS_CLK_INVERTED = 1'b0; parameter [0:0] IS_D_INVERTED = 1'b0; parameter [0:0] IS_OCLKB_INVERTED = 1'b0; parameter [0:0] IS_OCLK_INVERTED = 1'b0; `ifdef XIL_TIMING //Simprim parameter LOC = "UNPLACED"; `endif parameter integer NUM_CE = 2; parameter OFB_USED = "FALSE"; parameter SERDES_MODE = "MASTER"; parameter [0:0] SRVAL_Q1 = 1'b0; parameter [0:0] SRVAL_Q2 = 1'b0; parameter [0:0] SRVAL_Q3 = 1'b0; parameter [0:0] SRVAL_Q4 = 1'b0; localparam in_delay = 0; localparam out_delay = 0; localparam INCLK_DELAY = 0; localparam OUTCLK_DELAY = 0; output O; output Q1; output Q2; output Q3; output Q4; output Q5; output Q6; output Q7; output Q8; output SHIFTOUT1; output SHIFTOUT2; input BITSLIP; input CE1; input CE2; input CLK; input CLKB; input CLKDIV; input CLKDIVP; input D; input DDLY; input DYNCLKDIVSEL; input DYNCLKSEL; input OCLK; input OCLKB; input OFB; input RST; input SHIFTIN1; input SHIFTIN2; endmodule
module OSERDESE2 ( OFB, OQ, SHIFTOUT1, SHIFTOUT2, TBYTEOUT, TFB, TQ, CLK, CLKDIV, D1, D2, D3, D4, D5, D6, D7, D8, OCE, RST, SHIFTIN1, SHIFTIN2, T1, T2, T3, T4, TBYTEIN, TCE ); parameter DATA_RATE_OQ = "DDR"; parameter DATA_RATE_TQ = "DDR"; parameter integer DATA_WIDTH = 4; parameter [0:0] INIT_OQ = 1'b0; parameter [0:0] INIT_TQ = 1'b0; parameter [0:0] IS_CLKDIV_INVERTED = 1'b0; parameter [0:0] IS_CLK_INVERTED = 1'b0; parameter [0:0] IS_D1_INVERTED = 1'b0; parameter [0:0] IS_D2_INVERTED = 1'b0; parameter [0:0] IS_D3_INVERTED = 1'b0; parameter [0:0] IS_D4_INVERTED = 1'b0; parameter [0:0] IS_D5_INVERTED = 1'b0; parameter [0:0] IS_D6_INVERTED = 1'b0; parameter [0:0] IS_D7_INVERTED = 1'b0; parameter [0:0] IS_D8_INVERTED = 1'b0; parameter [0:0] IS_T1_INVERTED = 1'b0; parameter [0:0] IS_T2_INVERTED = 1'b0; parameter [0:0] IS_T3_INVERTED = 1'b0; parameter [0:0] IS_T4_INVERTED = 1'b0; `ifdef XIL_TIMING //Simprim parameter LOC = "UNPLACED"; `endif parameter SERDES_MODE = "MASTER"; parameter [0:0] SRVAL_OQ = 1'b0; parameter [0:0] SRVAL_TQ = 1'b0; parameter TBYTE_CTL = "FALSE"; parameter TBYTE_SRC = "FALSE"; parameter integer TRISTATE_WIDTH = 4; localparam in_delay = 0; localparam out_delay = 0; localparam INCLK_DELAY = 0; localparam OUTCLK_DELAY = 0; output OFB; output OQ; output SHIFTOUT1; output SHIFTOUT2; output TBYTEOUT; output TFB; output TQ; input CLK; input CLKDIV; input D1; input D2; input D3; input D4; input D5; input D6; input D7; input D8; input OCE; input RST; input SHIFTIN1; input SHIFTIN2; input T1; input T2; input T3; input T4; input TBYTEIN; input TCE; endmodule
module PinsecTester_tb ( ); wire [12:0] io_sdram_ADDR; wire [1:0] io_sdram_BA; wire [15:0] io_sdram_DQ; wire [15:0] io_sdram_DQ_read; wire [15:0] io_sdram_DQ_write; wire io_sdram_DQ_writeEnable; wire [1:0] io_sdram_DQM; wire io_sdram_CASn; wire io_sdram_CKE; wire io_sdram_CSn; wire io_sdram_RASn; wire io_sdram_WEn; reg io_asyncReset; reg io_axiClk; reg io_vgaClk; reg loader_valid; reg [15 : 0]loader_data; reg [1 : 0]loader_bank; reg [31 : 0]loader_address; assign io_sdram_DQ_read = io_sdram_DQ; assign io_sdram_DQ = io_sdram_DQ_writeEnable ? io_sdram_DQ_write : 16'bZZZZZZZZZZZZZZZZ; mt48lc16m16a2 sdram( .Dq(io_sdram_DQ), .Addr(io_sdram_ADDR), .Ba(io_sdram_BA), .Clk(io_axiClk), .Cke(io_sdram_CKE), .Cs_n(io_sdram_CSn), .Ras_n(io_sdram_RASn), .Cas_n(io_sdram_CASn), .We_n(io_sdram_WEn), .Dqm(io_sdram_DQM), .loader_valid(loader_valid), .loader_data(loader_data), .loader_bank(loader_bank), .loader_address(loader_address) ); Pinsec uut ( .io_sdram_ADDR(io_sdram_ADDR), .io_sdram_BA(io_sdram_BA), .io_sdram_DQ_read(io_sdram_DQ_read), .io_sdram_DQ_write(io_sdram_DQ_write), .io_sdram_DQ_writeEnable(io_sdram_DQ_writeEnable), .io_sdram_DQM(io_sdram_DQM), .io_sdram_CASn(io_sdram_CASn), .io_sdram_CKE(io_sdram_CKE), .io_sdram_CSn(io_sdram_CSn), .io_sdram_RASn(io_sdram_RASn), .io_sdram_WEn(io_sdram_WEn), .io_asyncReset(io_asyncReset), .io_axiClk(io_axiClk), .io_vgaClk(io_vgaClk) ); initial begin // $dumpfile("E:/waves/wave.vcd"); // $dumpvars(0, uut); // $dumpvars(0, uut.axi_vgaCtrl); // $dumpvars(0, uut.axi_core); // $dumpvars(0, sdram); //$dumpvars(0, uut.axi_sdramCtrl); // $dumpvars(0, uut.axi_core.core.execute0_inInst_payload_pc); end endmodule
module adder(nibble1, nibble2, sum, carry_out); input [3:0] nibble1; input [3:0] nibble2; output [3:0] sum; output carry_out; wire [4:0] temp; assign temp = nibble1 + nibble2; assign sum = temp [3:0]; assign carry_out = temp [4]; endmodule
module counter(count, reset, enable, clk); output [3:0] count; input reset, enable, clk; reg [3:0] count_temp = 4'h0; assign count = count_temp; always @ (posedge clk) begin if (reset) count_temp <= 4'h0; else if (enable) count_temp <= count_temp + 4'h01; $display("Counter++"); end endmodule
module TestMemVerilator ( input [9:0] io_addr, input [10:0] io_wvalue, input io_wenable, output [10:0] io_rvalue, input clk, input reset ); reg [10:0] _zz_2_; wire _zz_3_; wire [10:0] _zz_1_; reg [10:0] mem [0:1023] /* verilator public */; assign _zz_3_ = 1'b1; always @ (posedge clk) begin if(_zz_3_) begin _zz_2_ <= mem[io_addr]; end end always @ (posedge clk) begin if(_zz_3_ && io_wenable ) begin mem[io_addr] <= _zz_1_; end end assign _zz_1_ = io_wvalue; assign io_rvalue = _zz_2_; endmodule
module rand_gen ( input clock, input enable, input reset, output reg [7:0] rnd ); localparam LFSR_LEN = 128; reg [LFSR_LEN-1:0] random; wire feedback = random[127] ^ random[125] ^ random[100] ^ random[98]; reg [2:0] bit_idx; always @(posedge clock) begin if (reset) begin random <= {LFSR_LEN{4'b0101}}; bit_idx <= 0; rnd <= 0; end else if (enable) begin random <= {random[LFSR_LEN-2:0], feedback}; rnd[bit_idx] <= feedback; bit_idx <= bit_idx + 1; end end endmodule
module phy_len_calculation ( input clock, input reset, input enable, input [4:0] state, input [4:0] old_state, input [19:0] num_bits_to_decode, input [7:0] pkt_rate,//bit [7] 1 means ht; 0 means non-ht output reg [14:0] n_ofdm_sym,//max 20166 = (22+65535*8)/26 output reg [19:0] n_bit_in_last_sym,//max ht ndbps 260 output reg phy_len_valid ); reg start_calculation; reg end_calculation; reg [8:0] n_dbps; // lookup table for N_DBPS (Number of data bits per OFDM symbol) always @( pkt_rate[7],pkt_rate[3:0] ) begin case ({pkt_rate[7],pkt_rate[3:0]}) 5'b01011 : begin //non-ht 6Mbps n_dbps = 24; end 5'b01111 : begin //non-ht 9Mbps n_dbps = 36; end 5'b01010 : begin //non-ht 12Mbps n_dbps = 48; end 5'b01110 : begin //non-ht 18Mbps n_dbps = 72; end 5'b01001 : begin //non-ht 24Mbps n_dbps = 96; end 5'b01101 : begin //non-ht 36Mbps n_dbps = 144; end 5'b01000 : begin //non-ht 48Mbps n_dbps = 192; end 5'b01100 : begin //non-ht 54Mbps n_dbps = 216; end 5'b10000 : begin //ht mcs 0 n_dbps = 26; end 5'b10001 : begin //ht mcs 1 n_dbps = 52; end 5'b10010 : begin //ht mcs 2 n_dbps = 78; end 5'b10011 : begin //ht mcs 3 n_dbps = 104; end 5'b10100 : begin //ht mcs 4 n_dbps = 156; end 5'b10101 : begin //ht mcs 5 n_dbps = 208; end 5'b10110 : begin //ht mcs 6 n_dbps = 234; end 5'b10111 : begin //ht mcs 7 n_dbps = 260; end default: begin n_dbps = 0; end endcase end `include "common_params.v" always @(posedge clock) begin if (reset) begin n_ofdm_sym <= 1; n_bit_in_last_sym <= 130; // half of max num bits to have a rough mid-point estimation in case no calculation happen phy_len_valid <= 0; start_calculation <= 0; end_calculation <= 0; end else begin if ( (state != S_HT_SIG_ERROR && old_state == S_CHECK_HT_SIG) || ((state == S_DECODE_DATA && (old_state == S_CHECK_SIGNAL || old_state == S_DETECT_HT))) ) begin n_bit_in_last_sym <= num_bits_to_decode; if (num_bits_to_decode <= n_dbps) begin phy_len_valid <= 1; end_calculation <= 1; end else begin start_calculation <= 1; end end if (start_calculation == 1 && end_calculation != 1) begin if (n_bit_in_last_sym <= n_dbps) begin phy_len_valid <= 1; end_calculation <= 1; end else begin n_bit_in_last_sym <= n_bit_in_last_sym - n_dbps; n_ofdm_sym = n_ofdm_sym + 1; end end end end endmodule
module fifo_sample_delay # ( parameter integer DATA_WIDTH = 8, parameter integer LOG2_FIFO_DEPTH = 7 ) ( input wire clk, input wire rst, input wire [(LOG2_FIFO_DEPTH-1):0] delay_ctl, input wire [(DATA_WIDTH-1):0] data_in, input wire data_in_valid, output wire [(DATA_WIDTH-1):0] data_out, output wire data_out_valid ); wire [LOG2_FIFO_DEPTH:0] rd_data_count; wire [LOG2_FIFO_DEPTH:0] wr_data_count; wire full; wire empty; reg rd_en_start; wire rd_en; reg [LOG2_FIFO_DEPTH:0] wr_data_count_reg; wire wr_complete_pulse; assign wr_complete_pulse = (wr_data_count > wr_data_count_reg); assign rd_en = (rd_en_start&wr_complete_pulse); assign data_out_valid = (rd_en_start&data_in_valid); xpm_fifo_sync #( .DOUT_RESET_VALUE("0"), // String .ECC_MODE("no_ecc"), // String .FIFO_MEMORY_TYPE("auto"), // String .FIFO_READ_LATENCY(0), // DECIMAL .FIFO_WRITE_DEPTH(1<<LOG2_FIFO_DEPTH), // DECIMAL .FULL_RESET_VALUE(0), // DECIMAL .PROG_EMPTY_THRESH(10), // DECIMAL .PROG_FULL_THRESH(10), // DECIMAL .RD_DATA_COUNT_WIDTH(LOG2_FIFO_DEPTH+1), // DECIMAL .READ_DATA_WIDTH(DATA_WIDTH), // DECIMAL .READ_MODE("fwft"), // String .USE_ADV_FEATURES("0404"), // only enable rd_data_count and wr_data_count .WAKEUP_TIME(0), // DECIMAL .WRITE_DATA_WIDTH(DATA_WIDTH), // DECIMAL .WR_DATA_COUNT_WIDTH(LOG2_FIFO_DEPTH+1) // DECIMAL ) fifo_1clk_i ( .almost_empty(), .almost_full(), .data_valid(), .dbiterr(), .dout(data_out), .empty(empty), .full(full), .overflow(), .prog_empty(), .prog_full(), .rd_data_count(rd_data_count), .rd_rst_busy(), .sbiterr(), .underflow(), .wr_ack(), .wr_data_count(wr_data_count), .wr_rst_busy(), .din(data_in), .injectdbiterr(), .injectsbiterr(), .rd_en(rd_en), .rst(rst), .sleep(), .wr_clk(clk), .wr_en(data_in_valid) ); always @(posedge clk) begin if (rst) begin wr_data_count_reg <= 0; rd_en_start <= 0; end else begin wr_data_count_reg <= wr_data_count; rd_en_start <= ((wr_data_count == delay_ctl)?1:rd_en_start); end end endmodule
module sync_short ( input clock, input reset, input enable, input [31:0] min_plateau, input threshold_scale, input [31:0] sample_in, input sample_in_strobe, input demod_is_ongoing, output reg short_preamble_detected, input [15:0] phase_out, input phase_out_stb, output [31:0] phase_in_i, output [31:0] phase_in_q, output phase_in_stb, output reg signed [15:0] phase_offset ); `include "common_params.v" localparam WINDOW_SHIFT = 4; localparam DELAY_SHIFT = 4; reg reset_delay1; reg reset_delay2; reg reset_delay3; reg reset_delay4; wire [31:0] mag_sq; wire mag_sq_stb; wire [31:0] mag_sq_avg; wire mag_sq_avg_stb; reg [31:0] prod_thres; wire [31:0] sample_delayed; wire sample_delayed_stb; reg [31:0] sample_delayed_conj; reg sample_delayed_conj_stb; wire [63:0] prod; wire prod_stb; wire [63:0] prod_avg; wire prod_avg_stb; reg [15:0] phase_out_neg; reg [15:0] phase_offset_neg; wire [31:0] delay_prod_avg_mag; wire delay_prod_avg_mag_stb; reg [31:0] plateau_count; // this is to ensure that the short preambles contains both positive and // negative in-phase, to avoid raise false positives when there is a constant // power reg [31:0] pos_count; reg [31:0] min_pos; reg has_pos; reg [31:0] neg_count; reg [31:0] min_neg; reg has_neg; //wire [31:0] min_plateau; // minimal number of samples that has to exceed plateau threshold to claim // a short preamble /*setting_reg #(.my_addr(SR_MIN_PLATEAU), .width(32), .at_reset(100)) sr_0 ( .clk(clock), .rst(reset), .strobe(set_stb), .addr(set_addr), .in(set_data), .out(min_plateau), .changed());*/ complex_to_mag_sq mag_sq_inst ( .clock(clock), .enable(enable), .reset(reset), .i(sample_in[31:16]), .q(sample_in[15:0]), .input_strobe(sample_in_strobe), .mag_sq(mag_sq), .mag_sq_strobe(mag_sq_stb) ); // moving_avg #(.DATA_WIDTH(32), .WINDOW_SHIFT(WINDOW_SHIFT)) mag_sq_avg_inst ( // .clock(clock), // .enable(enable), // .reset(reset), // .data_in(mag_sq), // .input_strobe(mag_sq_stb), // .data_out(mag_sq_avg), // .output_strobe(mag_sq_avg_stb) // ); mv_avg #(.DATA_WIDTH(33), .LOG2_AVG_LEN(WINDOW_SHIFT)) mag_sq_avg_inst ( .clk(clock), .rstn(~(reset|reset_delay1|reset_delay2|reset_delay3|reset_delay4)), // .rstn(~reset), .data_in({1'd0, mag_sq}), .data_in_valid(mag_sq_stb), .data_out(mag_sq_avg), .data_out_valid(mag_sq_avg_stb) ); // delay_sample #(.DATA_WIDTH(32), .DELAY_SHIFT(DELAY_SHIFT)) sample_delayed_inst ( // .clock(clock), // .enable(enable), // .reset(reset), // .data_in(sample_in), // .input_strobe(sample_in_strobe), // .data_out(sample_delayed), // .output_strobe(sample_delayed_stb) // ); fifo_sample_delay # (.DATA_WIDTH(32), .LOG2_FIFO_DEPTH(5)) sample_delayed_inst ( .clk(clock), .rst(reset|reset_delay1|reset_delay2|reset_delay3|reset_delay4), .delay_ctl(16), .data_in(sample_in), .data_in_valid(sample_in_strobe), .data_out(sample_delayed), .data_out_valid(sample_delayed_stb) ); complex_mult delay_prod_inst ( .clock(clock), .enable(enable), .reset(reset), .a_i(sample_in[31:16]), .a_q(sample_in[15:0]), .b_i(sample_delayed_conj[31:16]), .b_q(sample_delayed_conj[15:0]), .input_strobe(sample_delayed_conj_stb), .p_i(prod[63:32]), .p_q(prod[31:0]), .output_strobe(prod_stb) ); // moving_avg #(.DATA_WIDTH(32), .WINDOW_SHIFT(WINDOW_SHIFT)) // delay_prod_avg_i_inst ( // .clock(clock), // .enable(enable), // .reset(reset), // .data_in(prod[63:32]), // .input_strobe(prod_stb), // .data_out(prod_avg[63:32]), // .output_strobe(prod_avg_stb) // ); // moving_avg #(.DATA_WIDTH(32), .WINDOW_SHIFT(WINDOW_SHIFT)) // delay_prod_avg_q_inst ( // .clock(clock), // .enable(enable), // .reset(reset), // .data_in(prod[31:0]), // .input_strobe(prod_stb), // .data_out(prod_avg[31:0]) // ); mv_avg_dual_ch #(.DATA_WIDTH0(32), .DATA_WIDTH1(32), .LOG2_AVG_LEN(WINDOW_SHIFT)) delay_prod_avg_inst ( .clk(clock), .rstn(~(reset|reset_delay1|reset_delay2|reset_delay3|reset_delay4)), // .rstn(~reset), .data_in0(prod[63:32]), .data_in1(prod[31:0]), .data_in_valid(prod_stb), .data_out0(prod_avg[63:32]), .data_out1(prod_avg[31:0]), .data_out_valid(prod_avg_stb) ); mv_avg_dual_ch #(.DATA_WIDTH0(32), .DATA_WIDTH1(32), .LOG2_AVG_LEN(6)) freq_offset_inst ( .clk(clock), .rstn(~(reset|reset_delay1|reset_delay2|reset_delay3|reset_delay4)), // .rstn(~reset), .data_in0(prod[63:32]), .data_in1(prod[31:0]), .data_in_valid(prod_stb), .data_out0(phase_in_i), .data_out1(phase_in_q), .data_out_valid(phase_in_stb) ); complex_to_mag #(.DATA_WIDTH(32)) delay_prod_avg_mag_inst ( .clock(clock), .reset(reset), .enable(enable), .i(prod_avg[63:32]), .q(prod_avg[31:0]), .input_strobe(prod_avg_stb), .mag(delay_prod_avg_mag), .mag_stb(delay_prod_avg_mag_stb) ); always @(posedge clock) begin if (reset) begin reset_delay1 <= reset; reset_delay2 <= reset; reset_delay3 <= reset; reset_delay4 <= reset; sample_delayed_conj <= 0; sample_delayed_conj_stb <= 0; pos_count <= 0; min_pos <= 0; has_pos <= 0; neg_count <= 0; min_neg <= 0; has_neg <= 0; prod_thres <= 0; plateau_count <= 0; short_preamble_detected <= 0; phase_offset <= phase_offset; // do not clear it. sync short will reset soon after stf detected, but sync long still needs it. end else if (enable) begin reset_delay4 <= reset_delay3; reset_delay3 <= reset_delay2; reset_delay2 <= reset_delay1; reset_delay1 <= reset; sample_delayed_conj_stb <= sample_delayed_stb; sample_delayed_conj[31:16] <= sample_delayed[31:16]; sample_delayed_conj[15:0] <= ~sample_delayed[15:0]+1; min_pos <= min_plateau>>2; min_neg <= min_plateau>>2; has_pos <= pos_count > min_pos; has_neg <= neg_count > min_neg; phase_out_neg <= ~phase_out + 1; phase_offset_neg <= {{4{phase_out[15]}}, phase_out[15:4]}; prod_thres <= ( threshold_scale? ({2'b0, mag_sq_avg[31:2]} + {3'b0, mag_sq_avg[31:3]}):({1'b0, mag_sq_avg[31:1]} + {2'b0, mag_sq_avg[31:2]}) ); if (delay_prod_avg_mag_stb) begin if (delay_prod_avg_mag > prod_thres) begin if (sample_in[31]) begin neg_count <= neg_count + 1; end else begin pos_count <= pos_count + 1; end if (plateau_count > min_plateau) begin plateau_count <= 0; pos_count <= 0; neg_count <= 0; short_preamble_detected <= has_pos & has_neg; if (has_pos && has_neg && demod_is_ongoing==0) begin // only update and lock phase_offset to new value when short_preamble_detected and not start demod yet if(phase_out_neg[3] == 0) // E.g. 131/16 = 8.1875 -> 8, -138/16 = -8.625 -> -9 phase_offset <= {{4{phase_out_neg[15]}}, phase_out_neg[15:4]}; else // E.g. -131/16 = -8.1875 -> -8, 138/16 = 8.625 -> 9 phase_offset <= ~phase_offset_neg + 1; end end else begin plateau_count <= plateau_count + 1; short_preamble_detected <= 0; end end else begin plateau_count <= 0; pos_count <= 0; neg_count <= 0; short_preamble_detected <= 0; end end else begin short_preamble_detected <= 0; end end else begin short_preamble_detected <= 0; end end endmodule
module rate_to_idx ( input clock, input enable, input reset, input [7:0] rate, input input_strobe, output reg [7:0] idx, output reg output_strobe ); always @(posedge clock) begin if (reset) begin idx <= 0; output_strobe <= 0; end else if (enable & input_strobe) begin case ({rate[7], rate[2:0]}) 4'b0011: begin // 6 mbps idx <= 0; end 4'b0111: begin // 9 mbps idx <= 1; end 4'b0010: begin // 12 mbps idx <= 2; end 4'b0110: begin // 18 mbps idx <= 3; end 4'b0001: begin // 24 mbps idx <= 4; end 4'b0101: begin // 36 mbps idx <= 5; end 4'b0000: begin // 48 mbps idx <= 6; end 4'b0100: begin // 54 mbps idx <= 7; end default: begin // mcs idx <= {5'b0, rate[2:0]}; end endcase output_strobe <= 1; end else begin output_strobe <= 0; end end endmodule
module last_sym_indicator ( input clock, input reset, input enable, input ofdm_sym_valid, input [7:0] pkt_rate,//bit [7] 1 means ht; 0 means non-ht input [15:0] pkt_len, input ht_correction, output reg last_sym_flag ); localparam S_WAIT_FOR_ALL_SYM = 0; localparam S_ALL_SYM_RECEIVED = 1; reg state; reg ofdm_sym_valid_reg; reg [8:0] n_dbps; reg [7:0] n_ofdm_sym; wire [16:0] n_bit; wire [16:0] n_bit_target; assign n_bit = n_dbps*(n_ofdm_sym+ht_correction); assign n_bit_target = (({1'b0,pkt_len}<<3) + 16 + 6); // lookup table for N_DBPS (Number of data bits per OFDM symbol) always @( pkt_rate[7],pkt_rate[3:0] ) begin case ({pkt_rate[7],pkt_rate[3:0]}) 5'b01011 : begin //non-ht 6Mbps n_dbps = 24; end 5'b01111 : begin //non-ht 9Mbps n_dbps = 36; end 5'b01010 : begin //non-ht 12Mbps n_dbps = 48; end 5'b01110 : begin //non-ht 18Mbps n_dbps = 72; end 5'b01001 : begin //non-ht 24Mbps n_dbps = 96; end 5'b01101 : begin //non-ht 36Mbps n_dbps = 144; end 5'b01000 : begin //non-ht 48Mbps n_dbps = 192; end 5'b01100 : begin //non-ht 54Mbps n_dbps = 216; end 5'b10000 : begin //ht mcs 0 n_dbps = 26; end 5'b10001 : begin //ht mcs 1 n_dbps = 52; end 5'b10010 : begin //ht mcs 2 n_dbps = 78; end 5'b10011 : begin //ht mcs 3 n_dbps = 104; end 5'b10100 : begin //ht mcs 4 n_dbps = 156; end 5'b10101 : begin //ht mcs 5 n_dbps = 208; end 5'b10110 : begin //ht mcs 6 n_dbps = 234; end 5'b10111 : begin //ht mcs 7 n_dbps = 260; end default: begin n_dbps = 0; end endcase end always @(posedge clock) begin if (reset) begin ofdm_sym_valid_reg <= 0; end else begin ofdm_sym_valid_reg <= ofdm_sym_valid; end end always @(posedge clock) begin if (reset) begin n_ofdm_sym <= 0; last_sym_flag <= 0; state <= S_WAIT_FOR_ALL_SYM; end else if (ofdm_sym_valid==0 && ofdm_sym_valid_reg==1) begin //falling edge means that current deinterleaving is finished, then we can start flush to speedup finishing work. n_ofdm_sym <= n_ofdm_sym + 1; if (enable) begin case(state) S_WAIT_FOR_ALL_SYM: begin if ( (n_bit_target-n_bit)<=n_dbps ) begin last_sym_flag <= 0; state <= S_ALL_SYM_RECEIVED; end end S_ALL_SYM_RECEIVED: begin last_sym_flag <= 1; state <= S_ALL_SYM_RECEIVED; end default: begin end endcase end end end endmodule
module crc32( input [7:0] data_in, input crc_en, output [31:0] crc_out, input rst, input clk); reg [31:0] lfsr_q,lfsr_c; assign crc_out = lfsr_q; always @(*) begin lfsr_c[0] = lfsr_q[24] ^ lfsr_q[30] ^ data_in[0] ^ data_in[6]; lfsr_c[1] = lfsr_q[24] ^ lfsr_q[25] ^ lfsr_q[30] ^ lfsr_q[31] ^ data_in[0] ^ data_in[1] ^ data_in[6] ^ data_in[7]; lfsr_c[2] = lfsr_q[24] ^ lfsr_q[25] ^ lfsr_q[26] ^ lfsr_q[30] ^ lfsr_q[31] ^ data_in[0] ^ data_in[1] ^ data_in[2] ^ data_in[6] ^ data_in[7]; lfsr_c[3] = lfsr_q[25] ^ lfsr_q[26] ^ lfsr_q[27] ^ lfsr_q[31] ^ data_in[1] ^ data_in[2] ^ data_in[3] ^ data_in[7]; lfsr_c[4] = lfsr_q[24] ^ lfsr_q[26] ^ lfsr_q[27] ^ lfsr_q[28] ^ lfsr_q[30] ^ data_in[0] ^ data_in[2] ^ data_in[3] ^ data_in[4] ^ data_in[6]; lfsr_c[5] = lfsr_q[24] ^ lfsr_q[25] ^ lfsr_q[27] ^ lfsr_q[28] ^ lfsr_q[29] ^ lfsr_q[30] ^ lfsr_q[31] ^ data_in[0] ^ data_in[1] ^ data_in[3] ^ data_in[4] ^ data_in[5] ^ data_in[6] ^ data_in[7]; lfsr_c[6] = lfsr_q[25] ^ lfsr_q[26] ^ lfsr_q[28] ^ lfsr_q[29] ^ lfsr_q[30] ^ lfsr_q[31] ^ data_in[1] ^ data_in[2] ^ data_in[4] ^ data_in[5] ^ data_in[6] ^ data_in[7]; lfsr_c[7] = lfsr_q[24] ^ lfsr_q[26] ^ lfsr_q[27] ^ lfsr_q[29] ^ lfsr_q[31] ^ data_in[0] ^ data_in[2] ^ data_in[3] ^ data_in[5] ^ data_in[7]; lfsr_c[8] = lfsr_q[0] ^ lfsr_q[24] ^ lfsr_q[25] ^ lfsr_q[27] ^ lfsr_q[28] ^ data_in[0] ^ data_in[1] ^ data_in[3] ^ data_in[4]; lfsr_c[9] = lfsr_q[1] ^ lfsr_q[25] ^ lfsr_q[26] ^ lfsr_q[28] ^ lfsr_q[29] ^ data_in[1] ^ data_in[2] ^ data_in[4] ^ data_in[5]; lfsr_c[10] = lfsr_q[2] ^ lfsr_q[24] ^ lfsr_q[26] ^ lfsr_q[27] ^ lfsr_q[29] ^ data_in[0] ^ data_in[2] ^ data_in[3] ^ data_in[5]; lfsr_c[11] = lfsr_q[3] ^ lfsr_q[24] ^ lfsr_q[25] ^ lfsr_q[27] ^ lfsr_q[28] ^ data_in[0] ^ data_in[1] ^ data_in[3] ^ data_in[4]; lfsr_c[12] = lfsr_q[4] ^ lfsr_q[24] ^ lfsr_q[25] ^ lfsr_q[26] ^ lfsr_q[28] ^ lfsr_q[29] ^ lfsr_q[30] ^ data_in[0] ^ data_in[1] ^ data_in[2] ^ data_in[4] ^ data_in[5] ^ data_in[6]; lfsr_c[13] = lfsr_q[5] ^ lfsr_q[25] ^ lfsr_q[26] ^ lfsr_q[27] ^ lfsr_q[29] ^ lfsr_q[30] ^ lfsr_q[31] ^ data_in[1] ^ data_in[2] ^ data_in[3] ^ data_in[5] ^ data_in[6] ^ data_in[7]; lfsr_c[14] = lfsr_q[6] ^ lfsr_q[26] ^ lfsr_q[27] ^ lfsr_q[28] ^ lfsr_q[30] ^ lfsr_q[31] ^ data_in[2] ^ data_in[3] ^ data_in[4] ^ data_in[6] ^ data_in[7]; lfsr_c[15] = lfsr_q[7] ^ lfsr_q[27] ^ lfsr_q[28] ^ lfsr_q[29] ^ lfsr_q[31] ^ data_in[3] ^ data_in[4] ^ data_in[5] ^ data_in[7]; lfsr_c[16] = lfsr_q[8] ^ lfsr_q[24] ^ lfsr_q[28] ^ lfsr_q[29] ^ data_in[0] ^ data_in[4] ^ data_in[5]; lfsr_c[17] = lfsr_q[9] ^ lfsr_q[25] ^ lfsr_q[29] ^ lfsr_q[30] ^ data_in[1] ^ data_in[5] ^ data_in[6]; lfsr_c[18] = lfsr_q[10] ^ lfsr_q[26] ^ lfsr_q[30] ^ lfsr_q[31] ^ data_in[2] ^ data_in[6] ^ data_in[7]; lfsr_c[19] = lfsr_q[11] ^ lfsr_q[27] ^ lfsr_q[31] ^ data_in[3] ^ data_in[7]; lfsr_c[20] = lfsr_q[12] ^ lfsr_q[28] ^ data_in[4]; lfsr_c[21] = lfsr_q[13] ^ lfsr_q[29] ^ data_in[5]; lfsr_c[22] = lfsr_q[14] ^ lfsr_q[24] ^ data_in[0]; lfsr_c[23] = lfsr_q[15] ^ lfsr_q[24] ^ lfsr_q[25] ^ lfsr_q[30] ^ data_in[0] ^ data_in[1] ^ data_in[6]; lfsr_c[24] = lfsr_q[16] ^ lfsr_q[25] ^ lfsr_q[26] ^ lfsr_q[31] ^ data_in[1] ^ data_in[2] ^ data_in[7]; lfsr_c[25] = lfsr_q[17] ^ lfsr_q[26] ^ lfsr_q[27] ^ data_in[2] ^ data_in[3]; lfsr_c[26] = lfsr_q[18] ^ lfsr_q[24] ^ lfsr_q[27] ^ lfsr_q[28] ^ lfsr_q[30] ^ data_in[0] ^ data_in[3] ^ data_in[4] ^ data_in[6]; lfsr_c[27] = lfsr_q[19] ^ lfsr_q[25] ^ lfsr_q[28] ^ lfsr_q[29] ^ lfsr_q[31] ^ data_in[1] ^ data_in[4] ^ data_in[5] ^ data_in[7]; lfsr_c[28] = lfsr_q[20] ^ lfsr_q[26] ^ lfsr_q[29] ^ lfsr_q[30] ^ data_in[2] ^ data_in[5] ^ data_in[6]; lfsr_c[29] = lfsr_q[21] ^ lfsr_q[27] ^ lfsr_q[30] ^ lfsr_q[31] ^ data_in[3] ^ data_in[6] ^ data_in[7]; lfsr_c[30] = lfsr_q[22] ^ lfsr_q[28] ^ lfsr_q[31] ^ data_in[4] ^ data_in[7]; lfsr_c[31] = lfsr_q[23] ^ lfsr_q[29] ^ data_in[5]; end // always always @(posedge clk, posedge rst) begin if(rst) begin lfsr_q <= {32{1'b1}}; end else begin lfsr_q <= crc_en ? lfsr_c : lfsr_q; end end // always endmodule // crc
module delay_sample #( parameter DATA_WIDTH = 16, parameter DELAY_SHIFT = 4 ) ( input clock, input enable, input reset, input [(DATA_WIDTH-1):0] data_in, input input_strobe, output [(DATA_WIDTH-1):0] data_out, output reg output_strobe ); localparam DELAY_SIZE = 1<<DELAY_SHIFT; reg [DELAY_SHIFT-1:0] addr; reg full; ram_2port #(.DWIDTH(DATA_WIDTH), .AWIDTH(DELAY_SHIFT)) delay_line ( .clka(clock), .ena(1), .wea(input_strobe), .addra(addr), .dia(data_in), .doa(), .clkb(clock), .enb(input_strobe), .web(1'b0), .addrb(addr), .dib(32'hFFFF), .dob(data_out) ); always @(posedge clock) begin if (reset) begin addr <= 0; full <= 0; end else if (enable) begin if (input_strobe) begin addr <= addr + 1; if (addr == DELAY_SIZE-1) begin full <= 1; end output_strobe <= full; end else begin output_strobe <= 0; end end else begin output_strobe <= 0; end end endmodule
module complex_to_mag_sq ( input clock, input enable, input reset, input signed [15:0] i, input signed [15:0] q, input input_strobe, output [31:0] mag_sq, output mag_sq_strobe ); reg valid_in; reg [15:0] input_i; reg [15:0] input_q; reg [15:0] input_q_neg; complex_mult mult_inst ( .clock(clock), .reset(reset), .enable(enable), .a_i(input_i), .a_q(input_q), .b_i(input_i), .b_q(input_q_neg), .input_strobe(valid_in), .p_i(mag_sq), .output_strobe(mag_sq_strobe) ); always @(posedge clock) begin if (reset) begin input_i <= 0; input_q <= 0; input_q_neg <= 0; valid_in <= 0; end else if (enable) begin valid_in <= input_strobe; input_i <= i; input_q <= q; input_q_neg <= ~q+1; end end endmodule
module calc_mean ( input clock, input enable, input reset, input signed [15:0] a, input signed [15:0] b, input sign, input input_strobe, output reg signed [15:0] c, output reg output_strobe ); reg signed [15:0] aa; reg signed [15:0] bb; reg signed [15:0] cc; reg [1:0] delay; reg [1:0] sign_stage; always @(posedge clock) begin if (reset) begin aa <= 0; bb <= 0; cc <= 0; c <= 0; output_strobe <= 0; delay <= 0; end else if (enable) begin delay[0] <= input_strobe; delay[1] <= delay[0]; output_strobe <= delay[1]; sign_stage[1] <= sign_stage[0]; sign_stage[0] <= sign; aa <= a>>>1; bb <= b>>>1; cc <= aa + bb; c <= sign_stage[1]? ~cc+1: cc; end end endmodule