⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main_master_write.c

📁 PIC to PIC communication using i2c bus. Multi-master implemented on pic24.
💻 C
字号:
#include "p24fj128ga010.h"
#include "lcd.h"
#include "CONU2.h"
#include <string.h>
#include <stdlib.h>

// Setup configuration bits
_CONFIG1( JTAGEN_OFF & GCP_OFF & GWRP_OFF & COE_OFF & FWDTEN_OFF & ICS_PGx2) 
_CONFIG2( FCKSM_CSDCMD & OSCIOFNC_OFF & POSCMOD_HS & FNOSC_PRIPLL)
//using PLL

#define USE_AND_OR	// To enable AND_OR mask setting for I2C. 
#define lenArray(arr)  (sizeof(arr)/sizeof(arr[0]))
#define nop() {__asm__ volatile("nop");}

// calculate baud rate of I2C
#define Fosc	(8000000) 
#define Fcy		(Fosc/2)	// no PLL
#define Fsck	100000
#define I2C_BRG	((Fcy/2/Fsck)-1)

int datalen(unsigned char *data){	unsigned char *aux;	aux=data;	int i=0;		while(1)	{				if(aux[i]=='\0') break;		i++;	}	return i;}

void initALL(void)
{
	initLCD();

	TRISAbits.TRISA0=0;
	TRISAbits.TRISA1=0;
	TRISAbits.TRISA2=0;
	TRISAbits.TRISA3=0;
	TRISDbits.TRISD6=1;
	TRISDbits.TRISD7=1;	
	TRISAbits.TRISA7=1;
}

int main(void)
{
	unsigned char slaveaddress=30, myaddress=25;
	unsigned char i2cdata[10];
	char datasz;
	char str[30];

	int w_r, i; // w_r is 1 or 0

	initALL();

	clrLCD();
	homeLCD();
	putsLCD("RD7 to Start");
	while(_RD6==1 && _RD7==1);
	_RA0=1;
	_RA1=1;

	i2cdata[0]=12;
	i2cdata[1]=23;
	i2cdata[2]=34;
	i2cdata[3]=45;
	i2cdata[4]=56;
	i2cdata[5]='\0';

	I2C1ADD=myaddress;			// Device ID

	clrLCD();
	homeLCD();
	sprintf(str,"End %d",slaveaddress);
	putsLCD(str);
	setLCDC(0x40);
	datasz=datalen(i2cdata);
	sprintf(str,"Size %d",datasz);
	putsLCD(str);
	
	//enable i2c
	I2C1CON=0x8000;
	I2C1BRG=I2C_BRG;

send:
	while(I2C1STATbits.P);
	I2C1CONbits.SEN=1;			//start master communication 	
	idlei2c1();					//wait for the 5 lower bits of i2c1con

	if(I2C1STATbits.BCL) 
		goto send;				// Bus Colision Detected
	w_r=0;						// send the address W/R=0;
	I2C1TRN= ( slaveaddress << 1) | w_r;
	while(I2C1STATbits.TBF);
	idlei2c1();
	//while(_MI2C1IF);

	_MI2C1IF=0;
	if(I2C1STATbits.ACKSTAT==1)
		{
			_RA2=1;
			//id n鉶 existe;
			sprintf(str,"ID not found >RA7<");
			clrLCD();
			homeLCD();
			putsLCD(str);
			goto exit;
		}else _RA3=1;

	//send the data
	clrLCD();
	homeLCD();
	for(i=0;i<datasz;i++)
	{
		I2C1TRN=i2cdata[i];
		while(I2C1STATbits.TBF);
		idlei2c1();

		while(!_MI2C1IF);		
		if(I2C1STATbits.ACKSTAT==1)		//id n鉶 existe;
		{			
			sprintf(str,"NACK received %d",i);
			setLCDC(0x40);
			putsLCD(str);
			break;
		}
	}
	
	I2C1CONbits.PEN = 1;   // initiate Stop on SDA and SCL pins
	idlei2c1();
	
	clrLCD();
	homeLCD();
	putsLCD("Data Sent >RA7<");

exit:
	while(_RA7==1);
	return 0;
}


	

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -