rovtech
Joined: 24 Sep 2006 Posts: 262
|
I2C data transfer from master to slave |
Posted: Thu Mar 18, 2010 6:57 pm |
|
|
I am trying to send 2 bytes of data from master to a slave. Most examples use an address as the first byte, is this really necessary? The following does NOT work. Any suggestions?
Code: | // Relevant slave code
/* Pre-processor directives */
#include <16F722.H>
#fuses INTRC, NOWDT, PUT, NOPROTECT
#use delay (clock=8MHZ) // osc defaults to 8 MHz
#use fast_io (B)
#use i2c (SLAVE, SCL=PIN_C3, SDA=PIN_C4, address=0x04)
// global variables
int p_speed, s_speed; // port & stbd speeds
// Interrupt on I2C
#INT_SSP
void ssp_interrupt () // have an interrupt
{
int incoming, state; // variables
state = i2c_isr_state (); // get state
if (state < 0x80) // master is sending data
{
incoming = i2c_read (); // throw away device address if state = 0
if (state == 1) // first data received is port speed
p_speed = incoming;
if (state == 2) // second data received is std speed
s_speed = incoming;
}
if (state >= 0x80) // master is requesting data from slave
{
i2c_write (adc_result); // send ADC value
}
}
// Relevant Master code
/* Pre-processor directives */
#include <16F884.H>
#fuses HS, NOWDT, PUT, NOPROTECT
#use delay (clock=8000000)
#use I2C (master, SCL=PIN_C3, SDA=PIN_C4)
#define SLAVE2_WRT_ADDR 0X04
/* The main function */
void main(void)
{
// declare variables
int p_speed, s_speed;
// initialize port directions
set_tris_c(0b10011000); // set Port C3, C4, C7 inputs, the rest outputs
// main loop
while (1)
{
// send data
I2C_START (); // start I2C
I2C_WRITE (SLAVE2_WRT_ADDR); // addr of side thrusters (0x04)
I2C_WRITE (p_speed); // send port speed
I2C_WRITE (s_speed); // send stbd speed
I2C_STOP (); // stop I2C
delay_ms (1000); // wait 1 second
} // end of while loop
} // end of main function
|
|
|