#申请原创#
一、串口通讯实验
配置串口比较简单,进入MCC,添加UART1,选择RB5为RX,RB7为TX:
配置UART的速率为9600,并选择Redirect STDIO to UART,这样就方便直接使用printf函数通过串口发送数据:
生成代码后,在main函数中添加printf命令,我是在主循环之前先发送“开始运行!”,然后在主循环中每秒发送一次“串口通讯测试!”:
下面是运行时通过串口通讯助手获得的测试结果:
二、I2C通讯实验
本次I2C通讯是在前次PIC18F16Q40核心板测试的基础上进行的,使用的是硬件I2C,参考MCC生成的i2c_master_example.c代码写成的针对8位寄存器地址多字节写操作以及16位寄存器地址的单字节和多字节的读写操作函数:
添加的函数代码如下:
///////////////添加的测试函数
void I2C_8addrBuffWrite(i2c1_address_t address, uint8_t reg, uint8_t *data, uint8_t len) //8位地址多字节写
{
uint8_t i,Buffer[20];
Buffer[0] = reg;
for(i=1; i<(len+1); i++){
Buffer[i] = data[i-1];
}
i = i + 1;
while(!I2C1_Open(address)); // sit here until we get the bus..
I2C1_SetBuffer(Buffer,i);
I2C1_SetAddressNackCallback(NULL,NULL); //NACK polling?
I2C1_MasterWrite();
while(I2C1_BUSY == I2C1_Close()); // sit here until finished.
}
uint8_t I2C_16addr_ByteRead(i2c1_address_t address, uint16_t reg)
{
uint8_t dat = 0x00;
uint16_t addr = reg<<8 | reg>>8;
while(!I2C1_Open(address)); // 打开I2C设备.
I2C1_SetDataCompleteCallback(rd1RegCompleteHandler,&dat); // 传递数据指针
I2C1_SetBuffer(&addr,2); // 指定数据地址
I2C1_SetAddressNackCallback(NULL,NULL); // 等待应答
I2C1_MasterWrite();
while(I2C1_BUSY == I2C1_Close()); // 等待操作结束
return dat;
}
void I2C_16addr_BuffRead(i2c1_address_t address,uint16_t reg,uint8_t *data,uint8_t len)
{
uint16_t addr;
addr = reg<<8 | reg>>8;
i2c1_buffer_t bufferBlock; // result is little endian
bufferBlock.data = data;
bufferBlock.len = len;
while(!I2C1_Open(address)); // sit here until we get the bus..
I2C1_SetDataCompleteCallback(rdBlkRegCompleteHandler,&bufferBlock);
I2C1_SetBuffer(&addr,2);
I2C1_SetAddressNackCallback(NULL,NULL); //NACK polling?
I2C1_MasterWrite();
while(I2C1_BUSY == I2C1_Close()); // sit here until finished.
}
void I2C_16addr_ByteWrite(i2c1_address_t address,uint16_t reg,uint8_t data)
{
uint8_t Buffer[3];
Buffer[0] = reg>>8;
Buffer[1] = reg;
Buffer[2] = data;
while(!I2C1_Open(address)); // 打开I2C器件
I2C1_SetBuffer(Buffer,3); // 写入3个字节数据(地址2+数据1)
I2C1_SetAddressNackCallback(NULL,NULL); // NACK polling?
I2C1_MasterWrite();
while(I2C1_BUSY == I2C1_Close()); // 等待写操作完成
}
void I2C_16addr_BuffWrite(i2c1_address_t address, uint16_t reg, uint8_t *data, uint8_t len)
{
uint8_t i,Buffer[20];
Buffer[0] = reg>>8; // 地址高字节
Buffer[1] = reg; // 地址低字节
for(i=2; i<(len+2); i++){
Buffer[i] = data[i-2]; // 将要写入的数据依次排列在数组后面
}
i = len + 2;
while(!I2C1_Open(address)); // 打开I2C器件
I2C1_SetBuffer(Buffer,i); // 写入多个字节数据
I2C1_SetAddressNackCallback(NULL,NULL); // NACK polling?
I2C1_MasterWrite();
while(I2C1_BUSY == I2C1_Close()); // 等待写操作完成
}
有关I2C测试的过程可参考我的另一个帖子:https://bbs.21ic.com/icview-3138832-1-1.html。
MCC的配置如下,配置RB4为SDA,RB6为SCL:
下面是DS1307日历模块驱动实验过程的照片:
这是在显示屏显示的照片:
这是测试的动画:
下面是本次测试项目文件的压缩包:
Text2.X.rar
(1.83 MB)
|