Altera_Forum
Honored Contributor
11 years agoI2C Protocol help
Hi,
I am new to VHDL. I am trying to implement an I2C master for practice (synthesizable code). At the moment , I have code written to send the start bit and then 8 data bits. The SDA should change only when the SCL is low and read when SCL is high. Right now my code changes the SDA on the same rising edge time as SCL which is more than likely incorrect. How would I modify my code below to change the SDA after the SCL goes low, preferably in the middle of the pulse? Adding delays such as using WAIT and AFTER are only for non-synthesizable code correct? Also, how would I let the SDA line float to wait for acknowledgement from a slave, i2c_sda<= 'X' ? Any help is much appreciated. Thanks in advance. .
Library IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.STD_LOGIC_UNSIGNED.ALL;
use ieee.numeric_std.all;
entity I2C is
port (in_clk : in std_logic;
i2c_scl : out std_logic;
i2c_sda : out std_logic
);
end I2C;
-------------------------------------------------------------------------
architecture behaviour of I2C is
signal count: integer:= 0;
signal data_count: integer:= 0;
signal out_clk : std_logic:= '1'; -- connected to scl
signal start_scl : std_logic := '0'; -- signal to start sending data if '1'
begin
i2c_scl<=out_clk;
process(in_clk)
begin
if (in_clk'event and in_clk = '1') then
count<= count + 1;
if (count = 0) then
i2c_sda<= '1';
elsif (count = 1) then
i2c_sda<= '0';
elsif (count = 2) then
out_clk<= '0'; -- start condition satisfied
start_scl<= '1';
elsif ( count > 2 and count < 10 ) then
out_clk<= not(out_clk); -- start scl clock
else
out_clk<= '1';
end if;
if (start_scl = '1') then
if (out_clk = '0') then
data_count<= data_count +1;
case data_count is
when 0 =>
i2c_sda<= '1';
when 1 =>
i2c_sda<= '0';
when 2 =>
i2c_sda<= '1';
when 3 =>
i2c_sda<= '0';
when 4 =>
i2c_sda<= '1';
when 5 =>
i2c_sda<= '0';
when 6 =>
i2c_sda<= '1';
when 7 =>
i2c_sda<= '0';
when 8 =>
i2c_sda<= '1';
when others =>
null;
end case;
end if;
end if;
end if;
end process;
end behaviour;
------------------------------------------------------------------------