hayee
Joined: 05 Sep 2007 Posts: 252
|
|
Posted: Thu Mar 25, 2010 3:38 am |
|
|
Here is an example for SPI communication. One master and one slave.
In this code master reads the analog data and send to the slave using SPI.
For master
Code: |
void main()
{
float adc1,adc2,value1;
int b0,b1,b2,b3;
setup_adc_ports(ALL_ANALOG);
setup_adc(ADC_CLOCK_INTERNAL);
setup_psp(PSP_DISABLED);
setup_spi(SPI_MASTER|SPI_L_TO_H|SPI_CLK_DIV_4);
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
setup_timer_1(T1_DISABLED);
setup_timer_2(T2_DISABLED,0,1);
setup_comparator(NC_NC_NC_NC);
setup_vref(FALSE);
// TODO: USER CODE!!
while(1)
{
if (input(PIN_A5)==0)
{
set_adc_channel(0);
delay_ms(10);
adc1=read_adc();
adc2=(adc1*5)/1024;
value1=adc2;
printf("value is: %f \r\n",value1);
{
union convert
{
int8 b[4];
float fval;
}
val;
val.fval=value1;
b0=val.b[3];
b1=val.b[2];
b2=val.b[1];
b3=val.b[0];
}
spi_write(b0);
spi_write(b1);
spi_write(b2);
spi_write(b3);
}
else
{
delay_cycles(1);
}
}
} |
For slave
Code: |
float readnum(void);
void main()
{
float adc;
setup_adc_ports(ALL_ANALOG);
setup_adc(ADC_CLOCK_INTERNAL);
setup_psp(PSP_DISABLED);
setup_spi(FALSE);
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
setup_timer_1(T1_DISABLED);
setup_timer_2(T2_DISABLED,0,1);
setup_comparator(NC_NC_NC_NC);
setup_vref(FALSE);
SET_TRIS_B (0xF0);
// TODO: USER CODE!!
output_high(PIN_A5);
setup_spi(SPI_SLAVE | SPI_L_TO_H | SPI_CLK_DIV_4);
{
while(1)
{
adc=readnum();
printf(" %f ",adc);
delay_ms(100);
}
}
}
float readnum(void)
{
int8 b0,b1,b2,b3;
float result,value;
int32 x;
output_low(PIN_A5);
delay_us(100);
b0=spi_read(0);
b1=spi_read(0);
b2=spi_read(0);
b3=spi_read(0);
x=make32(b0,b1,b2,b3);
{
union convert
{
int32 y;
float fval;
}
val;
val.y=x;
result=val.fval;
}
output_high(PIN_A5);
return result;
} |
|
|