2022年6月8日星期三

[STM32] 通過 I2C 控制 LCD1602

PCF8574 是擴展 I/O 的晶片並透過 I2C 協議通訊。主控端可以通過 PCF8574 暫存器進行 I/O 端的讀取狀態或是做為輸出端口。

datasheet 連結 (https://www.nxp.com/docs/en/data-sheet/PCF8574_PCF8574A.pdf)

STM32,1602

PCF8574 Address 定義

STM32,1602

若要調整 Address , 則短接接地即可。


LCD1602

4 bit 初始流程

STM32,LCD1602

指令集

STM32,LCD1602

連接表格

PINDEFINEPCF8574 PIN
1VSS 
2VCC 
3VEE 
4RSP0
5R/WP1
6ENP2
7DB0 
8DB1 
9DB2 
10DB3 
11DB4P4
12DB5P5
13DB6P6
14DB7P7
15LED+123
16LED-123

程式碼


void lcd_send_cmd(char cmd)
{
    char data_h,data_l;
    uint8_t frame_data[4];
    data_h = (cmd&0xf0);
    data_l = ((cmd <<4)&0xf0);
    frame_data[0] = data_h | 0x0C;    //en=1, rs=0
    frame_data[1] = data_h | 0x08;    //en=0, rs=0
    frame_data[2] = data_l | 0x0C;    //en=1, rs=0
    frame_data[3] = data_l | 0x08;    //en=0, rs=0

    HAL_I2C_Master_Transmit(&hi2c1,LCD_ADDRESS,(uint8_t *)frame_data,4,0x100);

    HAL_Delay(1);
}


void lcd_send_data(char data)
{
    char data_h,data_l;
    uint8_t frame_data[4];
    data_h = (data&0xf0);
    data_l = ((data <<4)&0xf0);
    frame_data[0] = data_h | 0x0D;    //en=1, rs=1
    frame_data[1] = data_h | 0x09;    //en=0, rs=1
    frame_data[2] = data_l | 0x0D;    //en=1, rs=1
    frame_data[3] = data_l | 0x09;    //en=0, rs=1

    HAL_I2C_Master_Transmit(&hi2c1,LCD_ADDRESS,(uint8_t *)frame_data,4,0x100);
    HAL_Delay(1);
}


void lcd_clear()
{
    lcd_send_cmd(0x01);
    HAL_Delay(1);
}


void lcd_Init()
{
    HAL_Delay(50);
    lcd_send_cmd(0x30);
    HAL_Delay(5);
    lcd_send_cmd(0x30);
    HAL_Delay(1);
    lcd_send_cmd(0x30);
    HAL_Delay(10);
    lcd_send_cmd(0x20);
    HAL_Delay(10);


    lcd_send_cmd(0x28);        //function set
    HAL_Delay(1);
    lcd_send_cmd(0x08);        //Display on/off
    HAL_Delay(1);
    lcd_send_cmd(0x01);        //clear display
    HAL_Delay(1);
    lcd_send_cmd(0x06);        //Enter mode
    HAL_Delay(1);
    lcd_send_cmd(0x0C);        //Display on/off
    HAL_Delay(1);


}


void lcd_send_string (char *str)
{
    while(*str)
    {
        lcd_send_data(*str++);
    }
    HAL_Delay(1);
}


void lcd_put_cur(uint8_t row,uint8_t col)
{
    lcd_send_cmd(0x80 | (col + (0x40 * row)));
}

主控程式段



lcd_Init();


  /* USER CODE END 2 */


  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
      lcd_put_cur(0,2);
      lcd_send_string("Hello World!");
      lcd_put_cur(1,1);
      lcd_send_string("www.makdev.net");
      HAL_Delay(1000);
      lcd_clear();
      HAL_Delay(1000);
    /* USER CODE BEGIN 3 */
  }

顯示輸出

STM32,LCD1602

原始碼連結

https://github.com/cold63/STM32_Code/tree/master/L476G-LCD

 

0 comments:

發佈留言