STM32G031J6M6マイコンを使ってI2C低電圧キャラクタ液晶モジュール(SB1602B)を動かしてみた


by AKIHIRO YAMAMOTO | Published on 2021-11-23 , Last updated on 2021-11-27

32ビットマイコンが今なら120円。
ということで STM32マイコン STM32G031J6M6 を買ってみた。

これで ストロベリーリナックス I2C低電圧キャラクタ液晶モジュール(16x2行) を動かしてみる。

ピンヘッダをつける

細ピンヘッダとDIP変換基板をはんだ付けする。

image01

データシートを確認する

sb1602b_p01

  • I2C低電圧キャラクタ液晶モジュールの電源電圧 2.7V ~ 3.6V

stm32g0_ds_p01

  • STM32G031 の電源電圧 1.7V ~ 3.6V

stm32g0_ds_p45

  • STM32G031 の絶対最大定格より
    FT(5V tolerant I/O)ピンとその他のI/Oピンを含めて各ピン入出力15mAまでに抑えておこう。

今回は電源電圧3.3V(3V3)に決めたので3端子レギュレータで3.3Vを供給する。

STM32とLCDを接続

stm32g0_ds_p35

STM32G031J6M6の

  • pin 1 (PB9) — 赤色LED(Vf=2V) — 抵抗R(3k) — VDD(3V3)
  • pin 2 (VDD) — VDD(3V3)
  • pin 3 (VSS) — GND
  • pin 4 (NRST) を I2CLCD のリセットピン(#1)と接続
  • pin 5 (I2C2_SCL) を I2CLCD のSCLピン(#2)と接続
  • pin 6 (I2C2_SDA) を I2CLCD のSDAピン(#3)と接続

pin 4 (NRST) は GNDとの間にリセット用タクトスイッチを入れて, 抵抗R(3.9k)でプルアップしておく。
pin 5, 6 (SCL, SDA) は抵抗R(3k)でプルアップしておく。
抵抗値に深い意味はない(そこにあったので)。

I2C低電圧キャラクタ液晶モジュール(16x2行)の

  • pin 1 (~RST) — STM32G031J6M6 pin#4
  • pin 2 (SCL) — STM32G031J6M6 pin#5
  • pin 3 (SDA) — STM32G031J6M6 pin#6
  • pin 4 (VSS) — GND
  • pin 5 (VDD) — VDD(3V3)

接続した後に気になったのでI/Oピンに流れる電流を計算してみる。

LCDに流れる電流は無視できるほど小さいのでLEDのピンに流れる電流を計算する。

直列接続なのでI/Oピンに流れる電流と抵抗器に流れる電流は同じとみなすと単なるLED電流計算になるので
VDD = 3.3V, LEDの順方向電圧Vf = 2.0 V, R = 3kΩ
の場合に

抵抗器に流れる電流を計算すると

$$ \begin{aligned} I &= \frac{V}{R} \\ &= \frac{V_{DD} - V_f}{R} \\
&= \frac{3.3 - 2.0}{3000} \\
&= 0.43 ~\mathrm{mA} \end{aligned} $$

気にする必要などなかった。

ブレッドボードで配線する

ニッケル水素電池(1.2V)を4直列から3端子レギュレータNJU7223F33で3.3V電源を作る。

LCDの下はこうで image02

これでOK image03

まだ何も起きない。(あたりまえ)
STM32マイコンにプログラムを書き込まないと。

STM32CubeIDEでプログラムを書く

STM32CubeIDEのバージョンは

capture01

プロジェクトを新規作成

File -> New でSTM32 プロジェクトを選択して,
MCU: STM32G031J6, Cプロジェクトを選んで新規作成する。

クロックはHSI RC発振 (16MHz)を16分周して生成した1MHzをSYSCLKにしておけばいいんとちゃいますか。 capture02

  • PB9をGPIO_Output
  • I2C2を100kHzで駆動 capture03

この設定でCubeIDEに生成してもらったmain.cの USER CODE BEGIN ~ END の間をいじる。(それ以外に書いたものは消されるよ)

エディタに慣れないしC++を使いたくなるがそれはとにかく,
液晶モジュールのAVR用サンプルコードを見ながらちょいちょいと書いてみる。

Core/Src/main.c

/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
 * All rights reserved.</center></h2>
 *
 * This software component is licensed by ST under BSD 3-Clause license,
 * the "License"; You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *                        opensource.org/licenses/BSD-3-Clause
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include <stdint.h>
#include <i2c_lcd.h>

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C2_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void) {
	/* USER CODE BEGIN 1 */

	/* USER CODE END 1 */

	/* MCU Configuration--------------------------------------------------------*/

	/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
	HAL_Init();

	/* USER CODE BEGIN Init */

	/* USER CODE END Init */

	/* Configure the system clock */
	SystemClock_Config();

	/* USER CODE BEGIN SysInit */

	/* USER CODE END SysInit */

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_I2C2_Init();
	/* USER CODE BEGIN 2 */

	i2c_lcd_init(&hi2c2);

	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	// 1行目の表示
	i2c_lcd_puts(&hi2c2, "Strawberry Linux");
	// 2行目にカーソルを移動
	i2c_lcd_set_ddram_address(&hi2c2, 0x40);
	i2c_lcd_puts(&hi2c2, "I2C \xb4\xb7\xbc\xae\xb3 \xd3\xbc\xde\xad\xb0\xd9");

	icon_code_t i = 0;
	while (1) {
		/* USER CODE END WHILE */

		/* USER CODE BEGIN 3 */

		i2c_lcd_show_icon(&hi2c2, 0x1fff ^ (1 << i));
		i = (i + 1) % 13;
		HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 0);
		HAL_Delay(100);
		HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 1);
		HAL_Delay(1000);
	}
	/* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void) {
	RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
	RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };

	/** Configure the main internal regulator output voltage
	 */
	HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
	/** Initializes the RCC Oscillators according to the specified parameters
	 * in the RCC_OscInitTypeDef structure.
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
	RCC_OscInitStruct.HSIState = RCC_HSI_ON;
	RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV16;
	RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
		Error_Handler();
	}
	/** Initializes the CPU, AHB and APB buses clocks
	 */
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
			| RCC_CLOCKTYPE_PCLK1;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) {
		Error_Handler();
	}
}

/**
 * @brief I2C2 Initialization Function
 * @param None
 * @retval None
 */
static void MX_I2C2_Init(void) {

	/* USER CODE BEGIN I2C2_Init 0 */

	/* USER CODE END I2C2_Init 0 */

	/* USER CODE BEGIN I2C2_Init 1 */

	/* USER CODE END I2C2_Init 1 */
	hi2c2.Instance = I2C2;
	hi2c2.Init.Timing = 0x00000103;
	hi2c2.Init.OwnAddress1 = 0;
	hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
	hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
	hi2c2.Init.OwnAddress2 = 0;
	hi2c2.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
	hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
	hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
	if (HAL_I2C_Init(&hi2c2) != HAL_OK) {
		Error_Handler();
	}
	/** Configure Analogue filter
	 */
	if (HAL_I2CEx_ConfigAnalogFilter(&hi2c2, I2C_ANALOGFILTER_ENABLE)
			!= HAL_OK) {
		Error_Handler();
	}
	/** Configure Digital filter
	 */
	if (HAL_I2CEx_ConfigDigitalFilter(&hi2c2, 0) != HAL_OK) {
		Error_Handler();
	}
	/* USER CODE BEGIN I2C2_Init 2 */

	/* USER CODE END I2C2_Init 2 */

}

/**
 * @brief GPIO Initialization Function
 * @param None
 * @retval None
 */
static void MX_GPIO_Init(void) {
	GPIO_InitTypeDef GPIO_InitStruct = { 0 };

	/* GPIO Ports Clock Enable */
	__HAL_RCC_GPIOB_CLK_ENABLE();
	__HAL_RCC_GPIOA_CLK_ENABLE();

	/*Configure GPIO pin Output Level */
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, GPIO_PIN_RESET);

	/*Configure GPIO pin : PB9 */
	GPIO_InitStruct.Pin = GPIO_PIN_9;
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
	HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void) {
	/* USER CODE BEGIN Error_Handler_Debug */
	/* User can add his own implementation to report the HAL error return state */
	__disable_irq();
	while (1) {
	}
	/* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

Core/Src/i2c_lcd.c

Core/Inc/i2c_lcd.h

プロジェクトのビルド

Ctrl + B でビルド。

capture04

14:16:08 **** Incremental Build of configuration Debug for project hello_stm32g0 ****
make -j16 all 
arm-none-eabi-size   hello_stm32g0.elf 
   text	   data	    bss	    dec	    hex	filename
   9152	     20	   1644	  10816	   2a40	hello_stm32g0.elf
Finished building: default.size.stdout
 

14:16:08 Build Finished. 0 errors, 0 warnings. (took 230ms)

中華ST-Linkでプログラミング

Nucleoボードを持っているからそのST-Linkを使えばいいのだけれど,
中華ST-Linkを使ってみたかった。

image04

stm32g0_ds_p38

STM32G031J6M6の

  • pin 3 (VSS) を ST-Link のGNDピン(#4)と接続
  • pin 4 (NRST) を ST-Link のRSTピン(#1)と接続
  • pin 7 (SWDIO) を ST-Link のSWDIOピン(#2)と接続
  • pin 8 (SWCLK) を ST-Link のSWCLKピン(#6)と接続 ST-Link のRSTピンはつながなくても書き込みの時に手動でリセットボタンを押してもいい。

image05

準備ができたらCubeIDEに戻ってRun -> Runする。
ファームウエアのアップデートが要求されるかも知れないけど何とかして。

capture05

STMicroelectronics ST-LINK GDB server. Version 5.9.1
Copyright (c) 2021, STMicroelectronics. All rights reserved.

Starting server with the following options:
        Persistent Mode            : Disabled
        Logging Level              : 1
        Listen Port Number         : 61234
        Status Refresh Delay       : 15s
        Verbose Mode               : Disabled
        SWD Debug                  : Enabled
        InitWhile                  : Enabled

Waiting for debugger connection...
Debugger connected
      -------------------------------------------------------------------
                       STM32CubeProgrammer v2.8.0                  
      -------------------------------------------------------------------

ST-LINK SN  : 57FF71064980495419400487
ST-LINK FW  : V2J38S7
Board       : --
Voltage     : 3.26V
SWD freq    : 4000 KHz
Connect mode: Under Reset
Reset mode  : Hardware reset
Device ID   : 0x466
Revision ID : Rev 1.1
Device name : STM32G03x/STM32G04x
Flash size  : 32 KBytes
Device type : MCU
Device CPU  : Cortex-M0+
BL Version  : 0x__



Memory Programming ...
Opening and parsing file: ST-LINK_GDB_server_a11524.srec
  File          : ST-LINK_GDB_server_a11524.srec
  Size          : 9172 Bytes
  Address       : 0x08000000 


Erasing memory corresponding to segment 0:
Erasing internal memory sectors [0 4]
Download in Progress:


File download complete
Time elapsed during download operation: 00:00:00.388



Verifying ...




Download verified successfully 

おつかれした! running

ここまで済ませたら, プログラマー(書き込み器)は不要になる。 coverimage


comments powered by Disqus