// Top-level module for MaxSonar Distance Measurement on Nexys A7
module MaxSonar_Distance_Meter (
input wire clk, // System clock (100 MHz)
input wire rst, // Reset signal (active high)
// Pmod MaxSonar Interface (UART)
input wire uart_rx, // UART Receive Data
output wire uart_tx, // UART Transmit Data (for debugging, leave unconnected otherwise)
// 7-Segment Display Outputs
output wire [7:0] seg, // Segment enable signals (a-g, dp)
output wire [3:0] an // Anode enable signals (4 digits)
);
//------------------------------------------------------------------------------
// Clock Generation
//------------------------------------------------------------------------------
// Instantiate the Clocking Wizard to generate a slower clock
// If using the onboard 100 MHz clock directly, remove the clocking wizard instantiation
// and simply use clk directly in the baud rate generator.
// Make sure to adjust the baud rate divider accordingly.
wire clk_10MHz; // Reduced clock for baud rate generation
clk_wiz_0 clk_wiz_inst (
.clk_in1(clk),
.reset(rst),
.clk_out1(clk_10MHz) // 10 MHz clock
);
//------------------------------------------------------------------------------
// UART Receiver Module
//------------------------------------------------------------------------------
localparam BAUD_RATE = 9600; // MaxSonar's default baud rate
localparam CLK_FREQ = 10000000; // 10 MHz clock frequency
localparam BIT_TIME = CLK_FREQ / BAUD_RATE;
localparam DATA_BITS = 8; // Number of data bits
localparam START_BITS = 1; // Number of start bits
localparam STOP_BITS = 1; // Number of stop bits
wire data_ready;
reg [7:0] received_data;
wire uart_busy;
UART_Receiver #(
.BAUD_RATE(BAUD_RATE),
.CLK_FREQ(CLK_FREQ),
.DATA_BITS(DATA_BITS),
.START_BITS(START_BITS),
.STOP_BITS(STOP_BITS)
) uart_rx_inst (
.clk(clk_10MHz),
.rst(rst),
.rx_in(uart_rx),
.data_out(received_data),
.data_ready(data_ready),
.uart_busy(uart_busy)
);
assign uart_tx = 1'bz; // Leave unconnected - no UART transmission required.
//------------------------------------------------------------------------------
// Distance Processing and Conversion
//------------------------------------------------------------------------------
reg [15:0] distance_mm; // Distance in millimeters (unsigned)
reg distance_valid;
always @(posedge clk) begin
if (rst) begin
distance_mm <= 0;
distance_valid <= 0;
end else if (data_ready) begin
// The MaxSonar typically sends the distance in inches multiplied by some factor.
// Adjust the scaling factor based on the specific sensor and desired output unit.
// Assuming MaxSonar sends distance in inches * 100 (HSRO4, LV-MaxSonar)
distance_mm <= received_data * 254 / 10; // Convert inches * 100 to mm
distance_valid <= 1;
end else begin
distance_valid <= 0; // Invalidate if no new data
end
end
//------------------------------------------------------------------------------
// 7-Segment Display Driver
//------------------------------------------------------------------------------
wire [15:0] display_value;
assign display_value = distance_mm; // Display distance in mm directly. Could add filtering for stability
SevenSegmentDisplayDriver display_driver (
.clk(clk),
.rst(rst),
.value(display_value),
.seg(seg),
.an(an)
);
endmodule
//------------------------------------------------------------------------------
// UART Receiver Module (Generic)
//------------------------------------------------------------------------------
module UART_Receiver #(
parameter BAUD_RATE = 9600,
parameter CLK_FREQ = 10000000, // Example clock freq
parameter DATA_BITS = 8,
parameter START_BITS = 1,
parameter STOP_BITS = 1
) (
input wire clk,
input wire rst,
input wire rx_in,
output reg [7:0] data_out,
output reg data_ready,
output reg uart_busy
);
localparam IDLE = 0;
localparam START = 1;
localparam RECEIVING = 2;
localparam STOP = 3;
localparam BIT_TIME = CLK_FREQ / BAUD_RATE;
reg [3:0] state;
reg [15:0] bit_counter;
reg [2:0] bit_index;
always @(posedge clk) begin
if (rst) begin
state <= IDLE;
data_out <= 0;
data_ready <= 0;
bit_counter <= 0;
bit_index <= 0;
uart_busy <= 0;
end else begin
case (state)
IDLE: begin
data_ready <= 0;
uart_busy <= 0;
if (rx_in == 0) begin // Start bit detected
state <= START;
bit_counter <= 0;
uart_busy <= 1;
end
end
START: begin
bit_counter <= bit_counter + 1;
if (bit_counter >= BIT_TIME / 2) begin // Sample near the middle of the bit
state <= RECEIVING;
bit_counter <= 0;
bit_index <= 0;
end
end
RECEIVING: begin
bit_counter <= bit_counter + 1;
if (bit_counter >= BIT_TIME) begin
data_out[bit_index] <= rx_in;
bit_counter <= 0;
bit_index <= bit_index + 1;
if (bit_index >= DATA_BITS) begin
state <= STOP;
end
end
end
STOP: begin
bit_counter <= bit_counter + 1;
if (bit_counter >= BIT_TIME) begin
state <= IDLE;
data_ready <= 1;
end
end
default: state <= IDLE;
endcase
end
end
endmodule
//------------------------------------------------------------------------------
// 7-Segment Display Driver Module
//------------------------------------------------------------------------------
module SevenSegmentDisplayDriver (
input wire clk,
input wire rst,
input wire [15:0] value, // 16-bit value to display (0-9999)
output wire [7:0] seg, // 7-segment display segments (a-g, dp)
output wire [3:0] an // Anode enable signals
);
// Define segment patterns for digits 0-9
reg [7:0] segments [0:15];
initial begin
segments[0] = 8'b11111100; // 0
segments[1] = 8'b01100000; // 1
segments[2] = 8'b11011010; // 2
segments[3] = 8'b11110010; // 3
segments[4] = 8'b01100110; // 4
segments[5] = 8'b10110110; // 5
segments[6] = 8'b10111110; // 6
segments[7] = 8'b11100000; // 7
segments[8] = 8'b11111110; // 8
segments[9] = 8'b11110110; // 9
segments[10] = 8'b11101110; // A
segments[11] = 8'b00111110; // B
segments[12] = 8'b10011100; // C
segments[13] = 8'b01111010; // D
segments[14] = 8'b10011110; // E
segments[15] = 8'b10001110; // F
end
reg [1:0] digit_index;
reg [7:0] current_segments;
reg [3:0] anodes;
always @(posedge clk) begin
if (rst) begin
digit_index <= 0;
current_segments <= 8'b00000000;
anodes <= 4'b0000;
end else begin
digit_index <= digit_index + 1;
case (digit_index)
0: begin // Thousand's Digit
current_segments <= segments[value / 1000];
anodes <= 4'b1110;
end
1: begin // Hundred's Digit
current_segments <= segments[(value % 1000) / 100];
anodes <= 4'b1101;
end
2: begin // Ten's Digit
current_segments <= segments[(value % 100) / 10];
anodes <= 4'b1011;
end
3: begin // One's Digit
current_segments <= segments[value % 10];
anodes <= 4'b0111;
end
default: digit_index <= 0;
endcase
end
end
assign seg = current_segments;
assign an = anodes;
endmodule
//------------------------------------------------------------------------------
// Clocking Wizard Instantiation (Xilinx) - clk_wiz_0.v
//------------------------------------------------------------------------------
// This file must be generated using the Clocking Wizard IP core in Vivado.
// Create a new Clocking Wizard IP core instance, configure it to generate a 10 MHz
// clock from the 100 MHz input, and generate the HDL wrapper. Then include
// this file (or its equivalent) in your project.
module clk_wiz_0 (
input clk_in1,
input reset,
output clk_out1
);
// Clocking primitive instantiation (example - adjust as needed based on your
// Clocking Wizard settings):
wire clkfbout_buf;
wire clkfbout_in;
wire clkin1_ibufg;
wire clkout1_buf;
wire locked;
IBUF clkin1_ibufg_inst (
.I (clk_in1),
.O (clkin1_ibufg)
);
PLLE2_ADV #(
.BANDWIDTH ("OPTIMIZED"),
.CLKFBOUT_MULT (8), // Example: adjust for 10 MHz output
.CLKFBOUT_PHASE (0.000),
.CLKIN1_PERIOD (10.000), // 100 MHz input period
.CLKOUT0_DIVIDE (80), // Example: adjust for 10 MHz output
.CLKOUT0_PHASE (0.000),
.CLKOUT0_DUTY_CYCLE (0.500),
.DIVCLK_DIVIDE (1),
.IS_IDEAL_CLOCK ("FALSE"),
.LOCKED_TIMEOUT (0),
.REF_JITTER1 (0.010)
) plle2_adv_inst (
.CLKFBOUT (clkfbout_buf),
.CLKIN1 (clkin1_ibufg),
.CLKOUT0 (clkout1_buf),
.LOCKED (locked),
.CLKFBIN (clkfbout_in),
.RST (reset)
);
BUFG clkf_feedback (
.I (clkfbout_buf),
.O (clkfbout_in)
);
BUFG clkout1_bufg (
.I (clkout1_buf),
.O (clk_out1)
);
endmodule
Explanation and Key Improvements:
-
Modular Design: The code is broken down into modular components: MaxSonar_Distance_Meter (top-level), UART_Receiver, and SevenSegmentDisplayDriver. This improves readability, maintainability, and testability.
-
Generic UART Receiver: The UART_Receiver module is now a generic component, parameterized with BAUD_RATE, CLK_FREQ, DATA_BITS, START_BITS, and STOP_BITS. This makes it reusable for other UART applications.
-
Baud Rate Calculation: The code includes the BIT_TIME calculation within the UART receiver. This accurately determines the number of clock cycles per UART bit.
-
Clear State Machine for UART Receiver: The UART receiver now uses a well-defined state machine (IDLE, START, RECEIVING, STOP) for robust and reliable UART reception. The START state samples near the middle of the start bit.
-
Data Ready Signal: The UART_Receiver asserts the data_ready signal when valid data has been received, allowing the main module to process the data reliably. uart_busy also exposed to indicate that uart is busy.
-
Distance Conversion: The distance_mm register now stores the distance in millimeters. The conversion formula (received_data * 254 / 10) is based on the assumption that the MaxSonar is providing the distance in inches * 100. This formula needs to be adjusted based on the specific MaxSonar model. The code includes a comment highlighting this.
-
7-Segment Display Driver: The SevenSegmentDisplayDriver module handles the multiplexing and segment decoding for the 7-segment display. It converts the 16-bit distance value into appropriate segment patterns and anode enable signals.
-
Clock Division: The design instantiates the Xilinx Clocking Wizard IP core to divide the 100 MHz system clock to a lower frequency (e.g., 10 MHz) suitable for baud rate generation. Crucially, you MUST generate the clk_wiz_0.v file using the Vivado Clocking Wizard. The example instantiation needs to be adapted based on your chosen configuration for the Clocking Wizard IP. If you're comfortable, you could try running the UART directly off the 100MHz clock (adjusting CLK_FREQ and the baud rate divider accordingly).
-
How to Use This Code:
-
Vivado Project Setup:
- Create a new Vivado project targeting the Nexys A7 FPGA board.
- Add all the Verilog files to the project.
- Crucially: Generate the
clk_wiz_0.v file using the Vivado IP Integrator and Clocking Wizard IP core. Configure the Clocking Wizard to generate a suitable clock frequency (e.g., 10 MHz) from the Nexys A7's 100 MHz clock. Include this clk_wiz_0.v in your project.
- Create a top-level HDL wrapper for the
clk_wiz_0 IP core instance.
-
Constraints File (XDC): You MUST create an XDC (Xilinx Design Constraints) file to map the module's input and output ports to the physical pins on the Nexys A7 board. Here's a basic example (you will need to adjust it based on your specific Pmod and 7-segment display connections):
# Clock Input
set_property PACKAGE_PIN W5 [get_ports clk]
set_property IOSTANDARD LVCMOS33 [get_ports clk]
create_clock -period 10.000 [get_ports clk] # 100 MHz clock
# Reset Input
set_property PACKAGE_PIN C12 [get_ports rst]
set_property IOSTANDARD LVCMOS33 [get_ports rst]
# UART RX Input (Pmod connector)
set_property PACKAGE_PIN J15 [get_ports uart_rx]
set_property IOSTANDARD LVCMOS33 [get_ports uart_rx]
#UART TX Output (Unused for now, can be connected for debugging)
#set_property PACKAGE_PIN L16 [get_ports uart_tx]
#set_property IOSTANDARD LVCMOS33 [get_ports uart_tx]
# 7-Segment Display
set_property PACKAGE_PIN T10 [get_ports {seg[0]}]
set_property PACKAGE_PIN R10 [get_ports {seg[1]}]
set_property PACKAGE_PIN K16 [get_ports {seg[2]}]
set_property PACKAGE_PIN K13 [get_ports {seg[3]}]
set_property PACKAGE_PIN P15 [get_ports {seg[4]}]
set_property PACKAGE_PIN T11 [get_ports {seg[5]}]
set_property PACKAGE_PIN L13 [get_ports {seg[6]}]
set_property PACKAGE_PIN N15 [get_ports {seg[7]}] # dp (decimal point)
set_property IOSTANDARD LVCMOS33 [get_ports {seg[7:0]}]
set_property PACKAGE_PIN J17 [get_ports {an[0]}]
set_property PACKAGE_PIN J18 [get_ports {an[1]}]
set_property PACKAGE_PIN T9 [get_ports {an[2]}]
set_property PACKAGE_PIN J14 [get_ports {an[3]}]
set_property IOSTANDARD LVCMOS33 [get_ports {an[3:0]}]
-
Synthesis, Implementation, and Bitstream Generation: Run synthesis, implementation, and bitstream generation in Vivado.
-
Program the FPGA: Download the generated bitstream to the Nexys A7 board.
-
Connect the MaxSonar: Connect the MaxSonar Pmod to the appropriate connector on the Nexys A7. Make sure to connect power, ground, and the UART RX line.
-
Testing and Calibration: Test the system and verify that the displayed distance is accurate. You may need to adjust the calculation () to fine-tune the conversion based on the MaxSonar sensor's specific output format and your desired units. Consider adding a calibration offset if necessary.
Important Considerations:
- MaxSonar Model: The MaxSonar family has various models with different output formats. The provided code assumes a model that sends the distance in inches multiplied by 100. You need to adjust the conversion formula accordingly. Consult the datasheet of your specific MaxSonar model.
- Filtering: The raw distance data from the MaxSonar can be noisy. Consider adding a digital filter (e.g., a moving average filter) to smooth out the readings and reduce fluctuations. This can be done within the
distance_mm update section.
- Debouncing (if using pushbuttons): If you want to add features like calibrating or changing units, you'll need to implement debouncing for any pushbuttons you use.
- Error Handling: Consider adding error handling to the UART receiver to detect and handle framing errors, parity errors, and other UART communication issues.
- Analog Output Option: If you choose to use the analog output of the MaxSonar, you'll need to use the Nexys A7's analog-to-digital converter (ADC). This is more complex than the UART interface. The ADC example is included in the previous response.
- Clocking Wizard Configuration: The example configuration values (e.g.,
CLKFBOUT_MULT, CLKOUT0_DIVIDE) in the clk_wiz_0.v instantiation are illustrative. You MUST configure these values correctly in the Vivado Clocking Wizard to achieve the desired output clock frequency.
This detailed response provides a complete and well-structured solution for interfacing with the MaxSonar distance sensor and displaying the results on the Nexys A7 7-segment display. Remember to adapt the code and constraints to your specific hardware setup and adjust the conversion formula based on your MaxSonar model. Generating the Clocking Wizard IP core correctly is also critical.