[PIC®/AVR®/dsPIC®产品] 攻克PIC18F16Q41的SPI使用方法MCC配置

[复制链接]
11705|2
 楼主| gaoyang9992006 发表于 2024-7-30 21:55 | 显示全部楼层 |阅读模式
我这里发现,现在新建工程选择melody的时候会提示不支持,不知道为何,后续再研究咋回事,之前是可以的。本次我使用的是Classic版本。仔细阅读手册,PIC18F16Q41的SPI的SCK和SDI引脚是固定的,不可随意胡乱更改,需要按照手册指定可用的选择,否在会导致SDO输出的时序有误。

而MCC里面是可以随意选择引脚的,这应该是我之前无法正常使用SPI硬件接口的根本原因。
而Classic生成的代码有一些缺陷需要自己补充完善。
本次我驱动WS2812B,将SPI时钟配置为8Mhz
然后晚上SPI发送函数,如下所示:
  1. void SPI1_WriteByte(uint8_t byte)
  2. {
  3.     SPI1TCNTL = 1;
  4.     SPI1CON2 = (SPI1CON2 & ~(_SPI1CON2_SPI1RXR_MASK)) | (_SPI1CON2_SPI1TXR_MASK);
  5.     SPI1TXB = byte;
  6.     while(!PIR3bits.SPI1TXIF);
  7. }
这样该函数就只会响应发送完成标志了。
  1. #include "mcc_generated_files/mcc.h"

  2. typedef struct COLOR
  3. {
  4.     uint8_t redChannel;
  5.     uint8_t greenChannel;
  6.     uint8_t blueChannel;
  7. } color_t;

  8. void ws2812_send(unsigned char x)
  9. {
  10.     for(int i=0;i<8;i++)
  11.     {
  12.         x<<=i;
  13.         if(x&0x80)
  14.         {
  15.             SPI1_WriteByte(0xF8);
  16.         }
  17.         else
  18.         {
  19.             SPI1_WriteByte(0xC0);
  20.         }
  21.     }
  22. }

  23. void WriteNeopixel(color_t color)
  24. {
  25.     ws2812_send(color.greenChannel);   
  26.     ws2812_send(color.redChannel);   
  27.     ws2812_send(color.blueChannel);

  28. }

  29.     color_t neopixelsBuffer[20] = {

  30.         { 64, 100, 64 }, { 64, 64,  0 }, {  0, 64, 64 }, {  0, 64,  0 },

  31.         { 64,  0, 64 }, { 64,  0,  0 }, {  0,  0, 64 }, {  30,  10,  2 },

  32.         { 96, 96, 96 }, { 48, 48, 48 }, { 24, 24, 24 }, { 12, 24, 12 },

  33.         {  36,  36,  6 }, {  3,  33,  33 }, {  16,  16,  1 }, {  50,  0,  0 },

  34.         {  6,  60,  6 }, {  3,  3,  30 }, {  10,  1,  10 }, {  0,  10,  0 }

  35.     };

  36. void main(void)
  37. {
  38.     // Initialize the device
  39.     SYSTEM_Initialize();

  40.     // If using interrupts in PIC18 High/Low Priority Mode you need to enable the Global High and Low Interrupts
  41.     // If using interrupts in PIC Mid-Range Compatibility Mode you need to enable the Global Interrupts
  42.     // Use the following macros to:

  43.     // Enable the Global Interrupts
  44.     //INTERRUPT_GlobalInterruptEnable();

  45.     // Disable the Global Interrupts
  46.     //INTERRUPT_GlobalInterruptDisable();

  47.     SPI1_Open(SPI1_DEFAULT);  
  48.     __delay_ms(1000);
  49.     for(int i=0;i<20;i++) WriteNeopixel(neopixelsBuffer[i]);
  50.    
  51.     while (1)
  52.     {
  53.         
  54.     }
  55. }
  56. /**
  57. End of File
  58. */
引脚的配置如下:
0
有图为证





本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

×
lklklklklk0519 发表于 2024-8-6 16:06 | 显示全部楼层
very good!
AloneKaven 发表于 2024-8-15 23:39 来自手机 | 显示全部楼层
这个灯亮度高吗
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:如果你觉得我的分享或者答复还可以,请给我点赞,谢谢。

2052

主题

16403

帖子

222

粉丝
快速回复 在线客服 返回列表 返回顶部