0% found this document useful (0 votes)
45 views38 pages

CPS Lab Report Final

The document describes experiments interfacing sensors like a light sensor, audio sensor, and configuring peripherals like GPIO and UART on an STM32 microcontroller. It provides code snippets to read data from the light sensor and log audio sensor values to the serial port. It also shows toggling an LED using GPIO and responding to a button press using GPIO interrupts.

Uploaded by

devikam230354ec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views38 pages

CPS Lab Report Final

The document describes experiments interfacing sensors like a light sensor, audio sensor, and configuring peripherals like GPIO and UART on an STM32 microcontroller. It provides code snippets to read data from the light sensor and log audio sensor values to the serial port. It also shows toggling an LED using GPIO and responding to a button press using GPIO interrupts.

Uploaded by

devikam230354ec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

NATIONAL INSTITUTE OF TECHNOLOGY

CALICUT
Department of Electronics and Communication Engineering

Winter 2023

EC6106E Design of Cyber Physical Systems


LAB REPORT

Under the Esteemed Guidance of


Dr. Jailsingh Bookhya
Assistant Professor, ECED

SUBMITTED BY
M231007EC Srinivas k
M230843EC Rishab SR

Group 13 - EDT
M.Tech - Electronics Design Technology
1. DC Motor Step Response
AIM : To Design and Simulate a DC motor model using MATLAB SIMULINK Software.
INTRODUCTION : the model circuit of dc motor with the armature is shown below & the
mechanical rotational equipment’s is also shown which indicates the dynamics experienced
by the rotor such as inertia(J) , friction constant (B).
Circuit parameter details :
R: indicated the armature winding cupper loss and conduction parameter
L: The internal power flow of the DC motor is alternating current(AC) so when the AC
current flow in to the winding wire the inductance creeps in which is modelled as L
So, Over all it forms a series circuit with the back emf (rotor) and the applied Vdc is
converted to AC by commutator which is known as mechanical rectifier
Load model is modelled with J,B,θ Which is force voltage analogy and we use force free
body diagram equation knowns as d'Alembert's principle instead of Kirchhoff's laws

Fig 1.1 Circuit level representation of DC Motor


The electrical component in the model calculates the value of the current, which the mechanical system uses to
calculate the speed of the motor and load.

The mechanical component in the model integrates the angular acceleration to calculate the angular speed of the
motor and load, which the electrical system uses to calculate the current.

The motor in this model has a resistance(R) of 3Ω, an electrical constant(Ke) of 0.025 Vs/rad, and a torque
constant(b) of 0.25 Nm/A. The total moment of inertia for the system(J) is 3.2μNms2, resulting in a
mechanical time constant(Kt) of 15.4ms.
The motor in this model has an inductance(L) of 2.5μH and a resistance(R) of 3Ω, resulting in an electrical
time constant (te) of 200ns.

SCHEMATIC DIAGRAM :

Fig 1.2 Schematic Diagram of DC Motor

PROCEDURE :
1) open Simulink in MATLAB tool, then go to the library browser & add the summer block , integrator
controller(1/s) ,proportional controller (k)
2) we consider the step input as R(s) input side and scope is connected at the output side as C(s) since
the model equations are derived from the transfer function
3) DC_MOTOR = C(S) R(S) = K (𝐽(𝑆+𝑏)∗𝐿(𝑆+𝑅)+K2) all these parameters are modelled as block
diagram.
4) Now consider the step response mentioning the wave form timing details as.

Parameter Value
Initial 0V
Final 230V

RESULTS :
Fig 1.5 Waveform window of Angular Position

Fig 1.6 Waveform window of Angular Speed


2. STM32 GPIO peripheral programming

i. LED Toggle Cube IDE

Objective: The main objective of this experiment is to understand the basics of GPIOs, how
a pin can be configured as an output or an input pin etc. By understanding these, we will
configure the PA 5 pin of the microcontroller as a GPIO Output pin, because the LD2, which
is in-built on the microcontroller, is connected to this pin. Then with the help of code we will
change the state of the LED. In this experiment, we're asked to make the LED turn ON and
OFF using the GPIO.

Requirements:
 STM32 Cube IDE software.
 STM32 Microcontroller.
 USB Cable for the microcontroller.
 PC or Laptop.

Steps followed :
1. Create a New Project in STM32.

2. Select the Board in the Board Selector as NUCLEO L476RG.


3. Assign a Project Name : LED_BLINK1

4. Make necessary changes while assigning a port :

In the Pinout & Configuration tab, click on PA5 pin and select it as GPIO_OUTPUT, if it is
not selected by default.
5. Press Ctrl+S to generate your code.

CODE :
1. Insert this code snippets in the main.c code.
2. This code must be included in while loop for toggling of LED.

/* USER CODE BEGIN WHILE */


while (1)
{
// HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
// HAL_Delay(500);
// HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
// HAL_Delay(500);
// Or
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
HAL_Delay(100);

}
/* USER CODE END WHILE */

Output :

Fig 2.1 LED toggling (ON State) Fig 2.2 LED toggling (OFF State)

2. ii. Using GPIO interrupts to respond to user button press

Overview: GPIO is a very important peripheral for interfacing digital IO devices. Here,
learns the technique to configure the GPIO peripheral for basic devices such as onboard
LEDs and Buttons. Also learn how to configure the GPIO interrupts functionality.

Steps followed :
1. Create a New Project in STM32 .
2. Select the Board in the Board Selector as NUCLEO L476RG .

3. Assign a Project Name :


4. In the Pin Out & Configuration select PA5 as GPIO_Input and PC13 as GPIO_output and
label them as led and btn .

5. Press Ctrl+S to generate your code.

CODE :
1. Insert this code snippets in the main.c code.
2. This code must be included in while loop for toggling of LED.
3. Insert the following code snippet to turn on the LED when the switch is pressed else
LED will be in OFF state.

/* USER CODE BEGIN WHILE */


while (1)
{
if(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13)== GPIO_PIN_RESET)
{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
}
/* USER CODE END WHILE */

/* USER CODE BEGIN 3 */


}
/* USER CODE END 3 */

Output :
Fig 2.3 When the switch is Not pressed: Fig 2.4 When the switch is pressed
3. Interface BH1750 and audio sensor to STM32 board

i. Interfacing Light Sensor (BH1750)

Overview: This experiment features the interfacing of light sensor to STM32 board to collect
sample data. BH1750 is a Digital Ambient light sensor, as it uses the I2C communication
protocol. Here, we can measure the intensity of ambient light in its surroundings. It is used to
detect the level of brightness or illuminance.

Steps followed :

1. Create a New Project in STM32 .

2. Select the Board in the Board Selector as NUCLEO L476RG .


3. Assign a Project Name :

4. Make all the necessary pinout adjustments as instructed in the DigiToad Technology
Instruction Manual.

5. Press Ctrl+S to generate your code.

Code :

#include "main.h"

#include "bh1750.h"
#include "stdio.h" #include
"string.h"

MX_GPIO_Init();
MX_USART2_UART_Init();
MX_I2C1_Init();

BH1750_Init(&hi2c1);

while (1)
{
/* USER CODE END WHILE */
float my_lux = BH1750_ReadLux(&hi2c1);
printf("Lux = %.2f\r\n", my_lux); // @suppress("Float formattingsupport")
HAL_Delay(1000);
/* USER CODE BEGIN 3 */
}

int io_putchar(int ch){


HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
return ch;
}

Output :

Various intensity values were sensed and displayed in the command window.

ii. Interfacing audio Sensor


Overview : This experiment features the interfacing of audio sensor to STM32 board to collect
sample data. Audio Sensor can measure the intensity of ambient sound disturbances in its
surroundings. It is used to detect the sound intensity levels.

Steps followed :
1. Create a New Project in STM32 .

2. Select the Board in the Board Selector as NUCLEO L476RG .

3. Assign a Project Name :


4. Make all the necessary pinout adjustments as instructed in the Digitoad Technology
Instruction Manual.

5. Press Ctrl+S to generate your code

Code :

/* USER CODE BEGIN Includes */


#include "stdio.h"
#include "string.h"
/* USER CODE END Includes */

/* USER CODE BEGIN PFP */


void Log(void);
void fill_mic_buffer(void);int
io_putchar(int);
/* USER CODE END PFP */

/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
Log();
/* USER CODE END WHILE */

/* USER CODE BEGIN 3 */


}
/* USER CODE END 3 */
}

/* USER CODE BEGIN 4 */


int io_putchar(int ch){
HAL_UART_Transmit(&huart2, (uint8_t *)&ch,1,0xFFFF);
return ch;
}
void fill_mic_buffer(){
for(int i=0; i<DATA_INPUT_USER; i++){
mic_buffer[AXIS_NUMBER * i] = mic;
HAL_Delay(3);
}
}
void Log(){
fill_mic_buffer();
for(int i=0; i<DATA_INPUT_USER;i++){
printf("%.2f",mic_buffer[AXIS_NUMBER * i]);printf(" ");
}
printf("\r\n");
}
/* USER CODE END 4 */

Output :
Create a Command shell console to print the contents on the console.

Set the connection Type to be Serial Port.


Give the connection name as audio.

Observe the output in the serial port connection in the command shell console.
4. Configuration of UART in polling method to send data from STM32 MCU to PC
Overview: This experiment features the Serial Communication peripheral also known as
UART. This lab forms the basis of designing dataloggers. Here, learns the technique to send
text or numeric data from the STM32 board to the PC.
Procedure: This experiment features the Serial Communication peripheral also known as UART. This
lab forms the basis of designing dataloggers. Here, we learn the technique to send text or numeric
data from the STM32 board to the PC.

Steps followed :

1. Create a New Project in STM32 .

2. Select the Board in the Board Selector as NUCLEO L476RG .


3. Assign a Project Name :

4. Make all the necessary pinout adjustments as instructed in the DigiToad Technology
Instruction Manual.

5. Press Ctrl+S to generate your code.

Code :
// Type in all the below code snippets in your main.c file
#include "main.h"

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes


---*/
void SystemClock_Config(void); static void
MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);

int main(void)
{

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_USART2_UART_Init();
/* USER CODE BEGIN 2 */

/* USER CODE END 2 */

/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
if(HAL_UART_Transmit(&huart2, " HELLO ",7,100) != HAL_OK)
{
Error_Handler();
HAL_Delay(100);
}
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}

Output :
Create a Command shell console to print the contents on the console.
Set the connection Type to be Serial Port.
Give the connection name as uart.

Observe the output in the serial port connection in the command shell console.
5. Design of a coherent sensor signal sampling methodology to implement a data logger
to send audio sensor data from STM32 to NanoEdge AI Studio on PC
Overview: This is a follow up experiment from the previous lab. Here, we design an audio
datalogger. This datalogger can collect real time audio samples and store it into a PC as a
CSV file. The audio csv files are later used for classification applications.

Instructions : To design an audio datalogger. This data logger can collect real-time audio samples and
store it into a PC as a CSV file. The audio CSV files will be later used for classification applications.

Procedure:
1. Open Nano Edge AI and create a New project.
2. In the Next step add the signals and name them as Train horn , baby cry and ambulance .
3. Take 100 samples of each audio you are trying to train the model for further classification,
4. In the next step go to Bench mark . Run the new Bench mark. Run the Bench Mark such that the
score will be greater than 90% .
5. In the next step go to the Emulator stage and initialize the emulator with different signals which
are added previously.

Output :
Fig 5.1 Audio data logging of Baby Cry Fig 5.2 Audio data logging of Ambulance
6. Audio Recognition: Design of keyword recognition (ON & OFF) model to control the
status of an LED using voice commands
Overview: This experiment deals with the implementation of machine learning to detect two
keywords from the audio samples. These keywords are: ON & OFF, so, if the user utters the
word ON, the corresponding LED will be turned on and vice versa.

Objective :
The main objective of this experiment is to interface an audio sensor to
an STM32 microcontroller and deploy the machine learning model built
using the nanoedge AI studio into the microcontroller .this will give the
microcontroller the ability to make decision on the device itself based on
classification on real time audio sensor data
Circuit diagram:

Requirements :
1. STM32 Cube IDE software.
2. Audio Sensor (Analog).
3. STM32 Microcontroller.
4. USB Cable for the microcontroller.
5. Jumper Wires.
6. PC or Laptop.
Data classification Code :
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/


/* USER CODE BEGIN Includes */
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "string.h"
#include "knowledge.h"
#include "NanoEdgeAI.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/


/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/


/* USER CODE BEGIN PD */
#define DATA_INPUT_USER 256
#define AXIS_NUMBER 1
#define CONFIRMATIONS_NB (uint32_t)(3)

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/


/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/


ADC_HandleTypeDef hadc1;

TIM_HandleTypeDef htim2;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

volatile uint32_t buffer_index = 0;


float mic_x =0.0;
float mic_buffer[DATA_INPUT_USER*AXIS_NUMBER]={0};
float output_class_buffer[CLASS_NUMBER];
const char *id2class[CLASS_NUMBER+1]={
"babycry",
"ambulance",
"Noise",
};
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/


void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_ADC1_Init(void);
static void MX_TIM2_Init(void);
/* USER CODE BEGIN PFP */
void Inference(void);
void fill_mic_buffer(void);
int __io_putchar(int);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/


/* USER CODE BEGIN 0 */
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc){
if(hadc->Instance==ADC1){
mic_x = HAL_ADC_GetValue(&hadc1);
mic_buffer[buffer_index]=mic_x;
buffer_index++;

if(buffer_index>=DATA_INPUT_USER){
buffer_index=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();
enum neai_state error_code;
/* USER CODE BEGIN Init */
error_code = neai_classification_init(knowledge);
if(error_code !=NEAI_OK)
{
printf("Knowledge inititalization ERROR");
printf("%d",error_code);
}
else
{
printf("Knowledge initialization done");
}

/* 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_USART2_UART_Init();
MX_ADC1_Init();
MX_TIM2_Init();
/* USER CODE BEGIN 2 */
HAL_ADC_Start_IT(&hadc1);
HAL_TIM_Base_Start(&htim2);
/* USER CODE END 2 */

/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
Inference();
/* USER CODE BEGIN 3 */
}
/* 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


*/
if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
{
Error_Handler();
}

/** 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.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 8;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
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_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV2;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)


{
Error_Handler();
}
}

/**
* @brief ADC1 Initialization Function
* @param None
* @retval None
*/
static void MX_ADC1_Init(void)
{

/* USER CODE BEGIN ADC1_Init 0 */

/* USER CODE END ADC1_Init 0 */

ADC_MultiModeTypeDef multimode = {0};


ADC_ChannelConfTypeDef sConfig = {0};

/* USER CODE BEGIN ADC1_Init 1 */

/* USER CODE END ADC1_Init 1 */

/** Common config


*/
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
hadc1.Init.Resolution = ADC_RESOLUTION_10B;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
hadc1.Init.LowPowerAutoWait = DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.NbrOfConversion = 1;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T2_TRGO;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_FALLING;
hadc1.Init.DMAContinuousRequests = DISABLE;
hadc1.Init.Overrun = ADC_OVR_DATA_PRESERVED;
hadc1.Init.OversamplingMode = DISABLE;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}

/** Configure the ADC multi-mode


*/
multimode.Mode = ADC_MODE_INDEPENDENT;
if (HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode) != HAL_OK)
{
Error_Handler();
}

/** Configure Regular Channel


*/
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_2CYCLES_5;
sConfig.SingleDiff = ADC_DIFFERENTIAL_ENDED;
sConfig.OffsetNumber = ADC_OFFSET_NONE;
sConfig.Offset = 0;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */

/* USER CODE END ADC1_Init 2 */

/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM2_Init(void)
{

/* USER CODE BEGIN TIM2_Init 0 */

/* USER CODE END TIM2_Init 0 */

TIM_ClockConfigTypeDef sClockSourceConfig = {0};


TIM_MasterConfigTypeDef sMasterConfig = {0};

/* USER CODE BEGIN TIM2_Init 1 */

/* USER CODE END TIM2_Init 1 */


htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 999;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */

/* USER CODE END TIM2_Init 2 */


}

/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{

/* USER CODE BEGIN USART2_Init 0 */

/* USER CODE END USART2_Init 0 */

/* USER CODE BEGIN USART2_Init 1 */

/* USER CODE END USART2_Init 1 */


huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */

/* USER CODE END USART2_Init 2 */

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

/* GPIO Ports Clock Enable */


__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();

/*Configure GPIO pin Output Level */


HAL_GPIO_WritePin(led_GPIO_Port, led_Pin, GPIO_PIN_RESET);

/*Configure GPIO pin : B1_Pin */


GPIO_InitStruct.Pin = B1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

/*Configure GPIO pin : led_Pin */


GPIO_InitStruct.Pin = led_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(led_GPIO_Port, &GPIO_InitStruct);

/* USER CODE BEGIN MX_GPIO_Init_2 */


/* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */


int __io_putchar(int ch){
HAL_UART_Transmit(&huart2,(uint8_t *)&ch,1,0xFFFF);
return ch;
}
void fill_mic_buffer(){
for(int i=0;i<DATA_INPUT_USER;i++){
mic_buffer[AXIS_NUMBER*i]=mic_x;
HAL_Delay(3);
}
}

void Inference()
{
uint16_t i,id_class_t0,id_class_tn;
fill_mic_buffer();
neai_classification(mic_buffer,output_class_buffer,&id_class_t0);
for(i=0;i<CONFIRMATIONS_NB-1;i++)
{
fill_mic_buffer();
neai_classification(mic_buffer,output_class_buffer,&id_class_tn);
if(id_class_t0!=id_class_tn)
{
break;
}
if(id_class_t0 ==id_class_tn)
{
printf("Detected Class");
printf(id2class[id_class_t0]);
// printf("i=%d \n",i);
// printf("t0=%d\n",id_class_t0 );
// printf("tn = %d \n",id_class_tn);
if(id_class_tn == 1 ){
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);
//printf("police siren");
}
else
{
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);
}
printf("\r\n");
}
else
{
printf("?");
printf("\r\n");
}
}
}
/* 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 */
7. Street Light Control using Light Sensor (BH1750)
Overview: Street lighting control is crucial for urban areas to optimize energy consumption
and ensure adequate lighting for pedestrians and vehicles. Implementing BH1750 on the
STM32 to adjust streetlight brightness based on real-time light intensity and time of day.

Steps followed :

1. Create a New Project in STM32 .

2. Select the Board in the Board Selector as NUCLEO L476RG .


3. Assign a Project Name :

4. Make all the necessary pinout adjustments as instructed in the DigiToad Technology
Instruction Manual.

5. Press Ctrl+S to generate your code.

Code :
Include all the below code snippets inside you main.c file.

#include "main.h"
/* USER CODE BEGIN Includes */
#include "bh1750.h"
#include "stdio.h" #include
"string.h"
/* USER CODE END Includes */

void SystemClock_Config(void); static void


MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);static
void MX_I2C1_Init(void);

int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_I2C1_Init();
/* USER CODE BEGIN 2 */
BH1750_Init(&hi2c1);
/* USER CODE END 2 */

/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */

/* USER CODE BEGIN 3 */


float my_lux = BH1750_ReadLux(&hi2c1);
printf("Lux = %.2f\r\n", my_lux); // @suppress("Float formattingsupport")
if(my_lux>100)
{
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_5,0);
}
else
{
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_5,1);
}
HAL_Delay(1000);
}
/* USER CODE END 3 */
}

/* USER CODE BEGIN 4 */


int io_putchar(int ch){
HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
return ch;
}
/* USER CODE END 4 */

Output :

a) Light sensor is not obstructed, LED(OFF) b) Light sensor is obstructed, LED(ON)

You might also like