STM32 Serial Communication in Polling Mode

USART is the acronym for Universal Synchronous-Asynchronous Receiver-Transmitter, and is the advancement of the old UART that was unable to handle synchronous communications; in computers, it deals with the management of communication via the RS-232 interface.

Generally, in the communication between devices, there is a transmitter and receiver that can exchange data bidirectionally, thus it happens for example in the communication between the microcontroller and third-party peripherals.

Where To Buy?
No.ComponentsDistributorLink To Buy
1STM32 NucleoAmazonBuy Now

What is Serial Communication?

In serial communications, the transmitting device sends information (bitstream) through a single channel one bit at a time. Serial communications are distinguished from parallel communications where the bitstream is sent over several dedicated lines altogether. Over the years, serial communication has become the most used as it is more robust and economical. On the other hand, serial communication requires, compared to the parallel case, a more complex management and control architecture, think for example how a trivial loss of a bit during a communication could irreparably corrupt the content of the final message. To this end, various communication protocols have been introduced over the years in order to improve speed, reliability and synchronization. In detail, three different communication modes can be found: synchronous, asynchronous, and isochronous.

Synchronous Mode

  • In synchronous communication, the transmitter sends the data one bit at a time at a certain frequency (constant frequency), so you have the channel on which the data travels and another on which a clock signal travels. Thanks to the clock signal, the receiving device (receiver) knows when one bit ends and another start, or rather a bit starts and ends on a rising or falling edge of the clock signal.

Asynchronous Mode

  • In asynchronous communication, there is no channel dedicated to the clock signal so there is no type of synchronization between receiver and transmitter.
  • When the transmitter is ready it starts to send the bits serially which are read directly by the receiver.
  • The sent packet always contains a start bit, which signals the start of transmission to the receiver, the start of transmission.
  • Generally, the sent packet is made up of 8 bits plus any parity bit which has the purpose of verifying the correctness of the data transmitted and of the stop bits that signal the end of the packet to the receiver.
  • In the case of sending a large flow of data, this type of communication is less efficient than synchronous as bits that do not contain information such as start and stop bits are sent several times.

Isochronous Mode

  • Isochronous mode is a hybrid mode, that is obtained by making a synchronous device communicate with an asynchronous one, this can only happen under certain conditions.

UART communication on STM32 Microcontrollers using HAL

The microcontrollers from the ST family are equipped with at least one USART, for example, the NUCLEO-L053R8 Board has two (USART1 and USART2). It is possible to configure the dedicated pins easily directly from the STCUBE tool, as we will see in the example, and the dedicated HAL libraries allow you to easily write functions and algorithms to transmit or receive data. There are three ways to exchange data via serial port in STM32, which are:
  1. Polling Mode
  2. Interrupt Mode
  3. DMA Mode
Let's discuss these serial communication modes of STM32 in detail:

Polling Mode

  • In polling mode, also called blocking mode, the application waits for the data transmission and reception. This is a simple way to communicate between devices when the bit rate is not very low, for example when we can debug the board and we want to display the result on screen console.
HAL library provides the following functions to transmit and receive in polling mode:
  • HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout);
  • HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData,uint16_t Size, uint32_t Timeout).

Interrupt Mode

  • In interrupt mode, also called non-blocking mode, in this way the application waits the end of transmission or reception. it is used when the transmission is not used continuously with respect to the activity of the microcontroller.
HAL library provides the following functions to transmit and receive in polling mode:
  • HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout);
  • HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData,uint16_t Size, uint32_t Timeout).

DMA Mode

  • DMA mode is the best way the exchange data, especially when we want to exchange data fastly and continuously that often require access to memory.
HAL library provides the following functions to transmit and receive in polling mode:
  • HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout);
  • HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData,uint16_t Size, uint32_t Timeout).
In the next example, we will see the polling mode communication using NUCLEO-L053R8.

Using USART in Polling Mode for STM32

In this example, we will write a project using USART in a polling mode to transmit text on the laptop monitor. To do that we need:
  • NUCLEO-L053R8 board.
  • Windows Laptop
  •  The ST-Link USB connector needs both for serial data communications, and firmware downloading and debugging on the MCU.
  •  A Type-A to mini-B USB cable must be connected between the board and the computer.
The USART2 peripheral is configurated to use PA2 and PA3 pins, which are wired to the ST-Link connector. In addition, USART2 is selected to communicate with the PC via the ST-Link Virtual COM Port. A serial communication client, such as Tera Term, needs to be installed on the PC to display the messages received from the board over the virtual communication Port.

Creating New Project in STM32CubeMX

Now we create a new STM32CubeMX project with the following steps:
  • Select File > New project from the main menu bar. This opens the New Project window.
  • Go to the Board selector tab and filter on STM32L0 Series.
  • Select NUCLEO-L053R8 and click OK to load the board within the STM32CubeMX user interface.
  • Then the tool will open the pinout view.
  • Select Debug Serial Wire under SYS, for do it click on System Core (on the top right) and then select SYS and finally flag on “Debug Serial Wire”.
  • Select Internal Clock as clock source under TIM2 peripheral. To do this click on Timers and then select TIM2. Now go to clock source and select through the drop-down menu “internal clock”.
  • Select the Asynchronous mode for the USART2 peripheral. Click on connectivity and select USART2. Now go to Mode and select through the drop-down menu “asynchronous”.
  • Check that the signals are properly assigned on pins :
    • SYS_SWDIO on PA13
    • TCK on PA14
    • USART_TX on PA2
    • USART_RX on PA3
  • Go to the Clock Configuration tab and no change the configuration in order to use the MSI as input clock and an HCLK of 2.097 MHz.
  • Come back to Pinout&Configuration and select Connectivity -> USART2 to open the peripheral Parameter Settings window and set the baud rate to 9600. Make sure the Data direction is set to “Receive and Transmit”.
  • Select Timers -> TIM2 and change the prescaler to 16000 and the Counter Period to 1000.
  • Go to NVIC Settings tab and flag TIM2 global interrupt to enable the interrupt related to TIM2.
  • In the Project Manager tab, configure the code to be generated and click OK to generate the code.
  • Our project has been initialized by STCubeMX. In  /UsartEx/Core/Src/main.c we will find our main where we will write the main body of our program.

Understanding STM32 Code for Serial Communication

Now let’s see what the code generator did:
  • First of all, we find the “Include” section we can add the library needed.
  • In our case, we can add also a string.h library to handle and send text data.
  • In “Private variables” has been defined two private variables htim2 and huart2; - htim2 as the first parameter an instance of the C struct TIM_HandleTypeDef; -huart2 as first parameter an instance of the C struct UART_HandleTypeDef.
/* Private variables ---------------------------*/ TIM_HandleTypeDef htim2; UART_HandleTypeDef huart2;
 
  • In “Private function prototypes” we find the prototype of function to initialize the System Clock, GPIO, timer and peripheral:
/* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_TIM2_Init(void); static void MX_USART2_UART_Init(void);
  • This function has been generated automatically by STCubeMx with the parameter selected as shown below:
  • It is important to highlight that the WordLength parameter of huart2 is UART_WORDLENGTH_8B, since we are sending 8-Bit ASCII chars.
  • We can easily adjust the baud rate with the BaudRate parameter.
  • Now we are ready to write our code in main():
  • As shown in the code below, two strings, str1 and str2, are declared. Then the string concatenation function ( strncat() ) is used and finally, the HAL_UART_Transmit function is used to display them on the monitor through UART2.
Now we are ready to compile and run the project:
  1. Compile the project within IDE.
  2. Download it to the board.
  3. Run the program.
In order to show the text on display needs to Configure serial communication clients on the PC such as Tera Term software, CoolTerm, Putty etc. In our example, we will use CoolTerm, but not change the aim if you will use another one.
  • On the computer, check the virtual communication port used by ST Microelectronics from the Device Manager window.
  • To configure Tera Term to listen to the relevant virtual communication port, adjust the parameters to match the USART2 parameter configuration on the MCU.
You must be careful to configure the correct com port and use the same setting which has set the USART2. After that we click on connect and run the program.
  • The CoolTerm window displays a message coming from the board at a period of a few seconds.
So, that was all for today. I hope you have enjoyed today's lecture. In the next tutorial, we will discuss Serial Communication using Interrupt Method. Till then take care and have fun !!!

First Project using STM32 in STM32CubeIDE

We will use for our examples STM32CubeIDE released by ST and completely free. STM32CubeIDE is a development tool and supports multi operative system (SO), which is part of the STM32Cube software ecosystem. STM32CubeIDE allows using a single platform to configure peripherals, to generate/compile/debug the code for STM32 microcontrollers and microprocessors. The framework used is Eclipse®/CDT, as tool-chain for the development is used GCC toolchain and GDB for the debugging.

To start the project, you must first select the MCU and then initialize and configure the peripherals the user wants to use. At this point, the initialization code is generated. At any time, the user can go back and change initializations and configurations, without affecting the user code. We will dive into these steps with a simple example in the next paragraph.

Where To Buy?
No.ComponentsDistributorLink To Buy
1STM32 NucleoAmazonBuy Now

First Project in STM using STM32CubeIDE

  • First of all, you have to install on your PC the STM32CubeIDE. In order to do it, you have to go on the ST site and after registered in it you can navigate to "https://www.st.com/en/development-tools/stm32cubeide.html" to download it.
  • At this point, you can install it, if you'll find problems you can check the "UM2563 - STM32CubeIDE installation guide".
  • STM32 Nucleo board (in our example we will use NUCLEO-L053R8, but you can use the one you prefer, as already said all Nucleo boards are pinout compatible);
  • USB 2.0 Cable - A-Male to Mini-B Cord to connect PC to ST-LINK;
  • Breadboard to hold and connect the simple electrical components;
  • Jumper Cables Kit to connect the Nucleo board to breadboard or other components;
  • Various basic electrical components such as Resistors (THT), Capacitors (THT), Buzzers, LEDs, etc.
Now let’s start!

Blinking LED using STM32 Nucleo Board

  • Turning a LED on and off is a basic and classical experiment when dealing with NUCLEO for the first time.
  • First, let's turn on the led, to do this we have to connect the LED to the power supply (on Nucleo we can find 3.3V and 5V).
Assuming:
  • the power supply 5V;
  • LED forward voltage of LED 7 Volt;
  • LED maximum forward current 20mA;

We must connect in series to LED a resistor. What resistance value must be considered to limit the current to 20 mA (see the formula below)?

R > 5 - 1.7/0.02 , where R > 165 ?

A good value of R is 220 ?.

Now we must be able to turn off the led, to do it we need a switch to connect and disconnect the power supply as shown below.

In this case when the switch is closed the Led is ON, when the switch is open the Led is OFF. This can be easily done with a Nucleo board by configuring a GPIO (General Purpose Input Output) pin.

The steps required to configure a core board are explained below. Obviously, this is a very simple practical example, but peripherals, communication protocols and anything else can be configured in a similar way.

Steps to generate the config. files from STM32CubeMX

As already said, we will use for our examples a NUCLEO-L053R8 board. For our examples, so also a Windows PC is required. The ST-Link USB connector is used both for serial data communications, and firmware downloading and debugging on the MCU. A Type-A to mini-B USB cable must be connected between the board and the computer. The USART2 peripheral uses PA2 and PA3 pins, which are wired to the ST-Link connector. In addition, USART2 is selected to communicate with the PC via the ST-Link Virtual COM Port. A tool that emulates the serial communication terminal is necessary to view received messages and send them. You can download many open-source tools as Tera Term. In this way, you can display on PC the messages received from the board over the virtual communication Port and the other way around.

In this paragraph, we will initialize the peripherals using STM32CubeMX. The STM32CubeMX tool to create the necessary config. files to enable drivers of peripheral used (for more detail read “UM1718 - User manual STM32CubeMX for STM32 configuration and initialization C code generation.”).

Steps to Follow

  • Select the NUCLEO-L053R8 board looking in a selection bar within the New Project menu.
  • Select the required features (debug, GPIOs, peripherals, timer) from the Pinout view: peripheral operating modes as well as assignment of relevant signals on pins.
  • Configure the MCU clock tree from the Clock Configuration view.
  • Configure the peripheral parameters from the Configuration view.
  • Configure the project settings in the Project Manager menu and generation of the project (initialization code only).
  • Update the project with the user application code corresponding to the Led blinking example.
  • Compile, and execute the project on the board.

Creating a new STM32CubeMX project

  • Select File -> New project from the main menu bar to open the New Project window.
  • Go to the Board selector tab and filter on STM32L0 Series.
  • Select NUCLEO-L053R8 board and then click on OK button to confirm. In this way the board is loaded within the STM32CubeMX user interface.
  • Insert the project name, in this case, "BlinkLed" and click finish.
  • Then the tool will open the pinout view.

Selecting the features from the Pinout view

  • Select Debug Serial Wire under SYS, for do it click on System Core (on the topo right) and then select SYS and finally flag on “Debug Serial Wire”.
 
  • Select Internal Clock as clock source under TIM2 peripheral. To do this click on Timers and then select TIM2. Now go to clock source and select through the drop-down menu “internal clock”.
  • Select one of the available pins (basically anyone!) as GPIO output, for example PA9 (the last pin of CN5)
Check that the signals are properly assigned on pins:
  • SYS_SWDIO on PA13
  • SYS_SWCLK on PA14
  • GPIO OUTPUT on PA5

Configuring the MCU clock tree

  • Go to the Clock Configuration tab and in this project, there is no need to change the configuration.

Configuring the peripheral parameters

  • Come back to Pinout&Configuration and select System Core -> GPIO to open the peripheral Parameter Settings window and in this case no change the configuration.
  • Select Timers -> TIM2 and change the Prescaler to 16000 and the Counter Period to 1000.
  • Go to the NVIC Settings tab and flag TIM2 global interrupt to enable the interrupt related to TIM2.

Configuring the project settings and generating the project

  • In the Project Manager tab, configure the code to be generated and click OK to generate the code.

Updating the project with the user application code

  • Our project has been initialized by STCubeMX.
  • In /BlinkLed/Core/Src/main.c we will find our main where we will write the main body of our program.

STM32 Programming Code for Led Blinking

The user code must be inserted between the "USER CODE BEGIN" and "USER CODE END" so that if you go to regenerate the initializations that part of the code is not deleted or overwritten. As shown in the code below, the simplest way is to use the function:

  • HAL_GPIO_TogglePin(GPIOx, GPIO_Pin) in the infinite loop ( while (1) ) with a chosen delay, for example of 1 second. To do this we use the function HAL_Delay(Delay). The declarations of these two functions with their parameters are described below
  • HAL_GPIO_TogglePin(GPIOx, GPIO_Pin): Toggles the specified GPIO pins.
  • GPIOx: Where x can be (A..E and H) to select the GPIO peripheral for STM32L0xx family devices. Note that GPIOE is not available on all devices. All port bits are not necessarily available on all GPIOs.
  • GPIO_Pin: Specifies the pins to be toggled.
  • HAL_Delay(Delay): This function provides minimum delay (in milliseconds) based on variable incremented. In the default implementation, SysTick timer is the source of time base. It is used to generate interrupts at regular time intervals where uwTick is incremented.

Note This function is declared as __weak to be overwritten in case of other implementations in a user file.

- Delay: specifies the delay time length, in milliseconds.

So, in our case GPIOx is GPIOA and the GPIO_PIN is GPIO_PIN_9 (see below).

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_TIM2_Init(); /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_9); HAL_Delay(1000); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ }

Now we are ready to compile and run the project:

  • Compile the project within IDE.
  • Download it to the board.
  • Run the program.

Another simple way is to use the function

  • HAL_GPIO_WritePin(GPIOx, GPIO_Pin, PinState).
  • HAL_GPIO_WritePin(GPIOx, GPIO_Pin, PinState): Sets or clears the selected data port bit.

Note This function uses GPIOx_BSRR register to allow atomic read/modify accesses. In this way, there is no risk of an IRQ occurring between the read and the modified access.

  • GPIOx: where x can be (A..E and H) to select the GPIO peripheral for STM32L0xx family devices.

Note that GPIOE is not available on all devices.

  • GPIO_Pin: specifies the port bit to be written.

This parameter can be one of GPIO_PIN_x where x can be (0..15).

All port bits are not necessarily available on all GPIOs.

  • PinState: specifies the value to be written to the selected bit.

This parameter can be one of the GPIO_PinState enum values:

  • GPIO_PIN_RESET: to clear the port pin
  • GPIO_PIN_SET: to set the port pin

So, in our case GPIOx is GPIOA and the GPIO_PIN is GPIO_PIN_9 and the pin state changes between 0 (LOW or CLEAR) and 1 (HIGH or SET).

In this case, the code is the following:

while (1) { HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9,0); HAL_Delay(1000); HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9,1); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ }

There are many other ways to blink an Led such as PWM, Interrupts etc. and will discuss it in the upcoming lectures. Thanks for reading.

Introduction to Nucleo Development Board

To become familiar with the world of microcontrollers it is necessary to have a development board (also known as a kit), which generally allows you to start working on it easily. Fortunately, the ST provides a wide portfolio of development boards. In this guide, we will describe and use the Nucleo board.

The Nucleo has been introduced a few years ago and its line is divided into three main groups:

  • Nucleo-32;
  • Nucleo-64;
  • Nucleo-144.
Where To Buy?
No.ComponentsDistributorLink To Buy
1STM32 NucleoAmazonBuy Now

Nucleo-32 Development Board

The number of pins available, so the package, gives the name to the board: Nucleo-32 uses an LQFP-32 package; Nucleo-64 and LQFP-64; Nucleo-144 an LQFP-144. The Nucleo-64 was the first line introduced and counts 16 different boards.

The Nucleo boards have interesting advantages compared to the Discovery. First, is the cheaper cost, you can buy it for around 15-25 dollars. Now in 2021 due to the lack of processed semiconductors, it is very difficult to find them on the normal distribution channels and costs are rising. A return to normal is expected from 2023. Furthermore, Nucleo boards are designed to be pin-to-pin compatible with each other. It is a very important advantage, in fact, if I start to develop my firmware on generic Nucleo later then I can adapt my code to another one.

In the next paragraphs, we will see the main structure of STM32-64

STM32 Nucleo-64 parts

The Nucleo-64 is composed of two parts:

  • ST-LINK part
  • MCU part

The part with the mini-USB connector is an ST-LINK 2.1 integrated debugger. It needs to upload the firmware on the target MCU and run the debugging. Furthermore, the ST-LINK interface provides a Virtual COM Port (VCP), which can be used to exchange data and messages with the host PC. The ST-LINK interface can be used as a stand-alone ST-LINK programmer, in fac,t can be easily cuttable to reduce board size.

To program the STM32 on board, simply plug in the two jumpers on CN4, as shown in the figure below in pink, but do not use the CN11 connector as that may disturb communication with the STM32 microcontroller of the Nucleo.

However, the ST-LINK provides an optional SWD interface which can be used to program another board without detaching the ST-LINK interface from the Nucleo by removing the two jumpers labeled ST-LINK (CN4).

The rest of the board, MCU part, contains the target MCU (the microcontroller we will use to develop our applications), a RESET button, a user-programmable push button (switch), and an LED. It is possible to mount an external high-speed crystal (HSE) through X3 pads (see figure below). Generally, the Nucleo boards, especially the most recent ones, provide a low-speed crystal (LSE).

Finally, the board has several pin headers we will look at in the next paragraph.

STM32 Nucleo-64 connectors

The STM32 Nucleo-64 board has 8 connectors:

  • CN2: ST-LINK USB connector on ST-LINK (already described in the previous paragraph);
  • CN11: SWD connector in ST-LINK part (already described in the previous paragraph);
  • CN7 and CN10: ST morpho connectors;
  • CN5, CN6, CN8, and CN9: ARDUINO® Uno V3 connectors;

The CN7 and CN10 ST morpho connectors are male pin headers (2x19, 2.54mm male pin headers) accessible on both sides of the STM32 Nucleo-64 board (see the figure below). All signals and power pins can be probed by an oscilloscope, logical analyzer, or voltmeter through the ST morpho connectors. They are two. They are called Morpho connectors and are a convenient way to access most of the MCU pins.

  • The figure below is shown the CN7 pinout (the STM32 peripherals and GPIOs associated with the Morpho connector) for NUCLEO-L053R8.
  • In the next figure, is shown the CN10 pinout for NUCLEO-L053R8.
  • The previous figure showed the pinout for NUCLEO STM32L053R8, but I remember you the Nucleo is pinout compatible with each other.
  • Another important feature of the Nucleo board is the compatibility with ARDUINO® Uno V3 through the CN5, CN6, CN8, and CN9 connectors (see figure below).
  • CN6 and CN8 are directly connected to CN7 and CN5 and CN9 to CN10.

Setting-Up the Tool-Chain

The first step in developing an application on the STM32 platform is to fully set up the tool-chain. A tool-chain is a set of programs, compilers, and tools that allows us:

  • to write our code and to browse the source files of our application;
  • to browse inside the application code, in order to examine variables, definitions, function declarations, and etc;
  • to compile our code using a cross-platform compiler;
  • to upload and debug our application on the development board (or a custom board).

To carry out these activities we basically need:

  • an IDE with integrated source editor and navigator;
  • a cross-platform compiler able to compile source code for our platform;
  • a debugger that executes the debugging of firmware on our board;
  • a tool that interacts with the ST-LINK interface.

There are several complete tool-chain for the STM32 Cortex-M family, both free and commercial. The most used tools are: IAR for Cortex-M, ARM Keil, and AC6 SW4STM32.

They can integrate everything necessary for the development of applications on STM32 to simplify and accelerate their development. The first two are commercial solutions and therefore have a price to the public that may be too high for those approaching the first time.

So, that was all for today. I hope you have enjoyed today's lecture and have understood this Nucleo Development Board. In the next lecture, we will design our first project in STM32CubeIDE. Thanks for reading.

Introduction to STM32 Family

In this guide, we will explain step by step to start programming on the STMicroelectronics (STM) platform, especially the STM32 family.

The term, "STM32" refers to a family of 32-bit microcontroller integrated circuits based on the ARM® Cortex®M processor. The architecture of these CPUs (Central Processing Unit) is ARM (Advanced Risk Machine) which is a particular family of Reduced Instruction Set Computing (RISC). RISC architecture differs from Complex Instruction Set Computing (CISC) for its simplicity that allows you to create processors capable of executing instruction sets with shorter times. Why use STM32? The advantages are many, and now we will list a part of them:

  1. ST offers a wide portfolio of solutions depending on the developer's needs. We can find products that combine different advanced features while maintaining a high level of integration. In fact, we can choose products with high performance, real-time processing, digital signal processing, and low consumption.
  2. Thanks to the availability of different development tools and available support material, the development of a simple or complex project is quite simple and fast, reducing the time to market if you want to develop a product.
  3. Each microcontroller has an integrated processor core, static RAM, flash memory, debug interface, and various peripherals such as GPIO, ADC, DAC, Timer, SPI, UART-USART, I2C, etc.
  4. For every MCU, ST provides the STM32 Nucleo Board that helps anyone who wants to fastly build and test prototypes for new projects with any STM32 MCU. STM32 Nucleo boards share the same connectors and can be easily expanded with many specialized application hardware add-ons (Nucleo-64 includes ST Morpho and Arduino Uno Rev3 connectors, while Nucleo-32 includes Arduino Nano connectors). Another and not insignificant advantage is the cheap cost of these development boards.

In the next paragraph, it will be illustrated how the STM32 is divided to easily identify the one used for your purposes.

Where To Buy?
No.ComponentsDistributorLink To Buy
1STM32 NucleoAmazonBuy Now

STM32 Family

  • To date, the STM32 family has 16 series of microcontrollers divided into four groups in order to cover all the needs of developers.
  • The four groups are Mainstream, Ultra-Low-Power, High-Performance Wireless.

STM32 Mainstream

The STM32 Mainstream has been designed to offer solutions for a wide range of applications where costs, time to market, reliability, and availability are fundamental requirements. They are widely used in real-time control signal processing applications.

There are 5 series in this group:

  1. STM32F1 are microcontrollers based on the ARM Cortex-M3 core. It was launched in 2007 and evolved over time in terms of maximum clock rate, memory depth, and peripherals. In fact, the maximum clock rate has gone from 24 MHz to 72 MHz, static RAM up to 96 kB, and Flash up to 1024 kB. It also supports Thumb-1 and Thumb-2 instruction sets.
  2. STM32F0 are microcontrollers based on the ARM Cortex-M0 core. It was launched in 2012. The maximum clock rate is 48 MHz and includes the SysTick timer. Static RAM up to 32 kB, and Flash up to 256 kB. It also supports Thumb-1 and Thumb-2 instruction sets.
  3. STM32F3 are microcontrollers based on the ARM Cortex-M0 core. It was launched in 2012. The maximum clock rate is 72 MHz and includes the SysTick timer. Static RAM up to 40 kB, and Flash up to 256 kB. It also supports Thumb-1, Thumb-2, Saturated, DSP, FPU instruction sets.
  4. STM32G0 are microcontrollers based on the Cortex-M0/M0+ core. It was launched in 2018. The maximum clock rate is 64 MHz. Static RAM up to 128 kB, and Flash up to 512 kB. It also supports Thumb-1 and Thumb-2 instruction sets. Compared to the older F0 series, it presents improvements in terms of efficiency and performance.
  5. STM32G4 are microcontrollers based on the Cortex-M4F core. It was launched in 2019. The maximum clock rate is 170 MHz. Static RAM up to 128 kB, and Flash up to 512 kB. Thumb-1, Thumb-2, Saturated, DSP, FPU instruction sets. Compared to the older F3/F4 series, it presents improvements in terms of efficiency and performance and higher performance compared to the L4 series.

STM32 Ultra-Low-Power

The STM32 Ultra-Low-Power has been designed to meet the need to develop devices with low energy consumption (such as portable and wearable devices) but maintaining a good compromise with performance.  There are 6 series in this group:

  1. STM32L0 are microcontrollers based on the ARM Cortex-M0+ core. It was launched in 2014. The maximum clock is 32 MHz, static RAM is of 8 kB, and Flash is up to 64 kB. It also supports Thumb-1 and Thumb-2 instruction sets.
  2. STM32L1 are microcontrollers based on the ARM Cortex-M3 core. It was launched in 2010. The maximum clock rate is 32 MHz, static RAM up to 80 kB, and Flash up to 512 kB. It also supports Thumb-1 and Thumb-2 instruction sets.
  3. STM32L4 are microcontrollers based on the ARM Cortex-M4 core. It was launched in 2015. The maximum clock rate is 80 MHz, static RAM is of 64 kB, and Flash is of 1024 kB. It also supports Thumb-1 and Thumb-2, Saturated, DSP, FPU instruction sets.
  4. STM32L4+ are microcontrollers based on the ARM Cortex-M4 core. It was launched in 2016. The maximum clock rate is 120 MHz, static SRAM up to 640 kB, and Flash up to 2048 kB. It also supports Thumb-1 and Thumb-2, Saturated, DSP, FPU instruction sets. It has been enriched with advanced peripherals such as a TFT-LCD controller, Camera interface, etc.
  5. STM32L5 are microcontrollers based on the ARM Cortex-M33F core. It was launched in 2018. The maximum clock rate is 110 MHz, static SRAM up to 640 kB, and Flash up to 2048 kB. It also supports Thumb-1 and Thumb-2, Saturated, DSP, FPU instruction sets.
  6. STM32U5 is the last ultra-low-power series launched (in 2021). It is an evolution of the L series and is based on the ARM Cortex-M33F core. the new 40 nm silicon technology allows to further reduce energy consumption, it also includes advanced cyber security features and graphics accelerators. The maximum clock rate is 160 MHz, static SRAM up to 640 kB, and Flash up to 2048 kB. It also supports Thumb-1 and Thumb-2, Saturated, DSP, FPU instruction sets.

STM32 High-Performance

The STM32 High-Performance has been designed for data processing and data transfer. It also has a high level of memory integration. There are 5 series in this group:

  1. STM32H7 are microcontrollers based on the ARM Cortex-M7F core. It was launched in 2017. The maximum clock is 480 MHz, static RAM is up to 1.4 MB, and Flash is up to 128 kB. It includes Ethernet and some advanced features such as dual Octo-SPI, JPEG codec, etc. It supports Thumb-1 and Thumb-2, Saturated, DSP, FPU instruction sets.
  2. STM32F7 are microcontrollers based on the ARM Cortex-M7F core. It was launched in 2014. The maximum clock is 216 MHz, static RAM is up to 1.4 MB, and Flash is up to 128 kB. It is fully pin-compatible with F4-series. It supports Thumb-1 and Thumb-2, Saturated, DSP, FPU instruction sets.
  3. STM32F4 was the first series of microcontrollers based on the ARM Cortex-M4F core. It was launched in 2011. The maximum clock is up to 180 MHz. It is the first series to have DSP and FPU. It also has faster ADCs, full-duplex I2S and an improved real-time clock. It supports Thumb-1 and Thumb-2, Saturated, DSP, FPU instruction sets.
  4. STM32F2 are microcontrollers based on the ARM Cortex-M3 core. It was launched in 2010. The maximum clock is 120 MHz, static RAM is up to 128 kB, and Flash is up to 1024 kB. It is fully pin-compatible with the F2 series. It supports Thumb-1, Thumb-2 and Saturated instruction sets.

STM32 Wireless

With STM32 Wireless ST adds in the portfolio a platform for wireless connectivity to the portfolio. It has a broad spectrum of frequencies and is used in various industrial and consumer applications.

It has features compatible with multiple protocols which allows it to communicate with different devices in real-time. Now, only two series belong to this group:

  • STM32WB provides Bluetooth®LE 5.2 and IEEE 802.15.4 communication protocols, Zigbee® and Thread, which can work simultaneously or individually.
 
  • STM32WL is the first series that support LoRa® communication.

So, that was all for today. I hope you have enjoyed today's lecture. In the next lecture, I am going to focus on the Nucleo Development board, as we are going to use that in our upcoming tutorials. Thanks for reading. Take care !!! :)

How to Increase EF Core Performance for Saving Multiple Entities?

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to Increase EF Core Performance for Saving Multiple Entities? EF Core works well for simple CRUD operations but for saving multiple entities EF Core provides poor performance. So, today we will use a third-party EF Core extension named "Z.EntityFramework.Extensions.EFCore", designed by ZZZ Projects, which will increase the EF Core performance significantly. I will be using a BulkSaveChanges Method of this library which is specifically designed for saving bulk data in an SQL database.

ZZZ Projects is a trusted company and has designed numerous .NET libraries, a few having downloads in millions. So, you can completely trust this extension library.

  • Here's a video for this tutorial, which will give you a practical demonstration of this project i.e. How to add this Library to your project and how to use this extension method BulkSaveChanges:

Before starting with the actual process, let's first have a look at What is EF Core?

What is EF Core?

EF Core is an Object Relational Mapper(ORM) and is used as a bridge between the ASP.Net Core application & its database. Thanks to EF Core, now there's no need to write complex SQL queries for database-related operations, instead, developers can easily perform all database CRUD operations in C# language(using EF Core). Although designed by Microsoft, but EF Core is a separate module and we can add it to our .NET application from the Nuget library.

Low Performance of EF Core

  • ORM(i.e. EF Core) provides a simple instructions-set for database CRUD operations and proves very friendly to developers, but it has few drawbacks as well.
  • One of the main disadvantages of EF Core is its low performance, which not only slows down your application but also increases the database interactions(cloud providers may charge extra).
  • Moreover, as the number of data(you want to save in the database) increases, the EF Core performance decreases.

EF Core Performance for multiple Entities

  • In a professional .NET application development, there come many scenarios where the developer needs to save multiple entities in the database i.e. user notifications, real-time messages etc.
  • When multiple entities are saved using EF Core, it doesn't save them in a single SQL session.
  • Instead, it takes multiple round-trips to the database, which increases the overall time for the data-saving process.

So, now let's have a look at How to increase the EF Core Performance for multiple entities by using BulkSaveChanges(provided by Z Extension), instead of SaveChanges(provided by EF Core):

What is BulkSaveChanges Method?

  • BulkSaveChanges is a simple function, automatically generated by EF Core Extension Library and is used for saving multiple entities in the database.
  • BulkSaveChanges increases the performance of EF Core by 3 to 4 times and its performance is exponential to a number of entities.
  • First of all, you need to download this project designed in ASP.NET Core:
Download Asp.Net Core Project
  • Open it in Visual Studio and first run the Migration commands for setting up the SQL database.

How to add EF Core Extension Library

  • If you check the NuGet packages in the above project, you will find these four packages installed in it, shown in the below figure:
  • You must be familiar with the first 3 NuGet packages, as they are used to add EF Core libraries in the .Net project.
  • The fourth one is the NuGet package of EF Core extension Library, designed by ZZZ Projects.
  • If you click on the Browse tab and make a search for "Z.EntityFramework", you will find results, as shown in the below figure:

Methods offered by Z Extension Library

  • After adding this NuGet package of ZZZ Projects, its methods will become readily available under the instance of DbContext class.
  • I am going to discuss BulkSaveChanges Method only(in today's lecture) but it has a wide range of methods for improving the performance of DBContext class, used in different scenarios, depending on requirements.
  • Here's a list of few other methods, offered by this EF Core Extension Library:

BulkSaveChanges Method to improve performance of EF Core

Now, let's have a look at the implementation of the BulkSaveChanges Method in our Asp.Net Core Application:
  • In the Models folder, open the SubjectRepository.cs file and here you will find two methods, named:
    • Add1() Method: It will use the default SaveChanges() Method of EFCore.
    • Add2() Method: It will be using the new BulkSaveChanges() Method of EF Core Extension Library.
  • Both of these methods are shown in the below figure:
  • As you can see in the above code, it's too easy to use the BulkSaveChanges() method, as it's called on the same instance of DBContext class, on which I have called the default SaveChanges() method.
  • Moreover, I have placed a stopwatch function around these methods to calculate the time taken by them, for saving 5000 entities in the database.
Now, let's save 5000 entities using these two methods, and look at the results:

SaveChanges vs BulkSaveChanges

  •  I have tested these methods three times each and created a comparison table.
  • In each of these testing trials, I have saved 5000 entities in the underlying SQL database.
  • Here's the result of the comparison, SaveChanges vs BulkSaveChanges: (all these readings are in milliseconds)
  • As you can see in the above comparison table, the BulkSaveChanges method is 3 to 4 times faster than the SaveChanges method.

For a practical demonstration of this project, watch the above video, where I have completely demonstrate How to add this Z extension Library to your project and how to use the BulkSaveChanges method to improve the performance of EF Core. So, that was all today, if you have any questions, please ask in the comments. Thanks for reading!!! :)

How to use IF Else in Python

Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to use IF Else in Python. It's our 5th tutorial in python series. In our previous lectures, we have covered the detailed Introduction to Python and then we have also discussed Data Types in Python & How to use Strings in Python. So, now it's time to move on a little further. In today's tutorial, we will cover If else statement in python and its not that difficult to understand but quite an essential one as its use a lot in programming projects. So, let's get started with How to use IF Else Statement in Python:

How to use IF Else Statement in Python

  • IF Else Statement in python takes a Boolean Test Expression as an input, if this Boolean expression returns TRUE then code in IF body will get executed and if it returns FALSE, then code in ELSE body will be executed.
  • You can understand it better by looking at its Flow Chart in right figure.
  • Here's the syntax of IF Else statement in python:
if number == 10: print(number) else: print('Number is not equal to 10"
  • We use if, in our daily life, it is part of our conversation, most of the time.
  • For example, I say, If I win a lottery then I will go to a world tour! If I clear the test then I will throw a party.
  • Here's another example, that if you are working late hours let say, overtime duty then you will get extra money, else you will not get the extra money.
Let's work with an example:
  • Suppose, we have a food chain and our customer has a voucher for it.
  • He has a voucher number (which is a code) written on it, by showing it, he can get a discount or he can get a free meal.
  • If he is providing a correct secret code, then he will get a free meal offer. Otherwise, he will not be able to avail any offer.
  • So, let's design this simple code using If Else statement:

Offer = 500 (This is, by default, price of a meal)

  • We will take the input from the user.

voucher_number = input("please enter your voucher number: ")

  • Whatever the number he will enter, it will get stored in that "voucher_number".
  • Now let's check if the code, that he has entered is correct or not.
  • We will need to use the IF statement here and first let's add this condition:

if voucher_number=="9753":

  • If the voucher number is matching with the company generated number, then the offer will be:

offer -=300

  • If the code is correct then deduct the amount as a discount.
  • Then print("congratulations, you have got a discount")
  • Then print("your remaining offer has " + str(offer))
  • Run the program
  • See the image, it says to enter the voucher number in the output window:
Suppose I put the wrong code. It will exit the program. Now what error he will face, if he put the wrong Voucher number, Let’s see what will be the next task.
  • We will use else statement for this, if the condition is not correct.
  • I have simply printed the message in else body, as shown in below figure:

Relational Operators in Python

As we are discussing IF Else statement, so we should also have a look at relational operators in python:
  • Relational Operators are used to find a relation between two variables or data packets.
  • We use relational operators in test expressions of IF Else statements.
  • We have five types of Relational Operators i.e.
    • Greater than >
    • Less than <
    • Greater than equals to >=
    • Less than equals to <=
    • Equals to ==
  • Let's understand them with an example. Now I have to check which number is greater so I will write it as:
if first_number > second_number:          print(" First number is greater than second number.") else:        print(“second number is greater than first number.") So, that was all about How to use IF Else statement in Python. If you have any questions, ask in comments. In the next, lecture, we will have a look at How to design a simple calculator in python. Till then take care & have fun !!! :)

How to use Arithmetic Operators in Python

Hello friends, I hope you all are ding great. In today's tutorial, I am going to show you How to use Arithmetic Operators in Python. It's our fourth tutorial in Python series. Arithmetic operators are required in mathematical problem solving. We will first have a look at the arithmetic operators and after that, we also discuss different builtin arithmetic functions in Python Math module. So, let's get started:

Arithmetic Operators in Python

  • Arithmetic operators ( +, -, *, /, ^ etc. ) are used to perform simple arithmetic operations in python.
  • So, let's open up your PyCharm and perform a simple task using these operators, as shown in below figure:
  • I used a single star for multiplication and a double star for the square power.
  • It is showing the results of the operations, which it is performing respectively.
Now let's design a simple calculator using these arithmetic operators but before that let's have a look at How to take input from user in python.

Getting Input from users in Python

  • If we want to work dynamically, we will learn how we get values from users.
  • It quite simple in python, you will just need to use an input method here.
  • It will take input from the user and store it in the assigned variable.
  • If you want to take the full name, age, and qualification of the player, you will write it as shown in the image:

Now I will talk about type conversion and we will make a simple program that will calculate the salary of an employee so that we can learn to perform basic calculations: Type conversion in Python In this part, I will tell you, what is Type Conversion in Python? And why it is required? Let's follow the step.
  • Suppose we want to count the salary of an employee. See the steps in the image.
  • Here I put int. before the fourth string, which is basic pay, but I have put the bonus in the whole numbers and it will be unable to do the concatenation because it is allowing it as a string. So, I typed the data and run it, see the results.

  • You can also use the second method as you can put int. where you are performing calculations, as shown in the image.
  • You can convert it by using three major data types i.e. int, float, string.

Simple Calculator in Python

Now we will design a simple calculator in which the user will enter 1st & 2nd number and our code will perform these operations with those operators like addition, subtraction, division, and multiplications. I typed the following strings below:
  • first_number = float(input("Enter first number : "))
  • second_number = float(input("Enter second number : "))
  • print("All Arithmetic Operations are as under.")
  • print(first_number + second_number)
  • print(first_number - second_number)
  • print(first_number * second_number)
  • print(first_number / second_number)
  • print(first_number ** second_number)
  • I converted the type of first and second strings.
  • Run the program
  • You can see in the printed screen all the arithmetic operations are performed respectively.
  • All the values are in floating points because we converted it into the float.
  • You can also convert it in integer and check it.
  • I wrote 9 and 5 and enter it, results are shown in above figure.

Operator Precedence in Python

Let's suppose, we have a variable here.
  • Profit = 15 + 30 * 25
  • Now let's print it using: print(profit)
  • Run the program.
  • The answer will be 765 in the output window.
Python follows the standard order of precedence. First, it will perform multiplication and then it will perform the addition. However, we can change the order using parenthesis.
  • Suppose, we want to operate the addition method first.
  • So, I will place parenthesis before and after both terms.
  • Then it will perform the addition method first then multiplication.
  • I will write it as:

profit = (15 + 30) * 25

  • Run the program and answer will be 1125.
Now I will expand the equation and will do subtraction with it, let’s see what happens.

profit = (15 + 30) * 25 - 10

  • Run the program and answer will be 1115.
  • If we add parenthesis to it as:

profit = (15 + 30) * (25 - 10)

  • Run the program and we will get 675.
Numbers and Importing Math’s Function in Python In this part of the lecture, I will discuss predefined functions about numbers in Python and I will also show you, how to import math modules for the advanced predefined function and methods, predefined for numbers. So let's get started. round()
  • Suppose we have a variable as, number = 3.7.
  • I want easily round it using:

print(round(number))

  • Run the program and it will round the figure to 4.
abs()
  • Suppose I have negative value -8 and I want to find the absolute value of it.
  • I will use abs() and it It will return 8, as shown in below figure:
min()
  • If I want to find the minimum value among the two numbers. I will write it as:

 print(min(9, 4.5)

  • It will return the minimum value as, 4.5.
max()
  • You can do the exact opposite of min, if you want to find out the maximum value among the two numbers.

print(max(9, 4.5)

pow()
  • If I want to calculate the multiples of itself i.e. square, cube etc. then I will write it as:

print(pow(5, 3)

  • The first number will be base and the second one will be the power.
  • Run the program & it will show the answer, 125.

Import a Math Module in Python

Now let's have a look at How to import a math module in python code:
  • Python Math library has a lot of builtin functions, which we can easily import by writing this statement at the top of our code.

from Math import *

  • By writing this statement we are simply saying that get access to all the functions of Math Library.
Now, let's have a look at few of its functions: sqrt()
  • Suppose I want to take the square root of number = 72
  • I write it as

print (sqrt(number))

  • Run the program and it will return as 8.4 something, as shown in below figure:
Here's the complete list of functions in Python Math Module:
List of Functions in Python Math Module
Function Description
ceil(x) It returns the previous integer value.
copysign(x, y) It will assign sign of y to x.
fabs(x) It returns the absolute value.
factorial(x) It returns the factorial value.
floor(x) It returns the next integer value.
fmod(x, y) It divides x by y and returns the remainder.
frexp(x) It returns the mantissa and exponent as pair value.
fsum(iterable) It returns an accurate floating point sum of values in the iterable
isfinite(x) It returns TRUE, if the number is finite i.e. neither infinite nor NaN.
isinf(x) It returns TRUE, if the number is infinite.
isnan(x) It returns TRUE, if the number is NAN.
ldexp(x, i) It returns x * (2**i).
modf(x) It returns the fractional and integer values.
trunc(x) It returns the truncated integer value.
exp(x) It returns e**x
expm1(x) It returns e**x - 1
log(x[, base]) It returns the logarithmic value to the base e.
log1p(x) It returns the natural logarithmic value of 1+x.
log2(x) It returns the base-2 logarithmic value.
log10(x) It returns the base-10 logarithmic value.
pow(x, y) It returns x raised to the power y.
sqrt(x) It returns the square root of x.
acos(x) It returns the arc cosine of x.
asin(x) Returns the arc sine of x.
atan(x) Returns the arc tangent of x.
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Returns the Gamma function at x
lgamma(x) Returns the natural logarithm of the absolute value of the Gamma function at x
pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...)
e mathematical constant e (2.71828...)
So that was all about arithmetic operators in Python. I hope now you got the clear idea of how powerful python is. So, that was all for today. In the next lecture, we will have a look at How to create IF Loop in Python. Till then take care and have fun !!! :)

How to use String in Python

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to use String in Python. It's our 3rd tutorial in Python series. We have discussed strings in our previous lecture How to use Data Types in Python. String is a most commonly used data type in python that's why I have created a separate lecture on it. Python has many built-in string operations, which we will discuss today in detail. So, let's get started with String in Python:

How to use String in Python

  • String Data Type is used to store or collect one or more characters or sequence of characters, we can place any alphanumerical or special character in a string.
  • Let's create a string in python, it has a simple syntax, as shown below:

first_var = "Hello World"

  • There are two sorts of strings, we can use in python:
    • Single Line.
    • Multiple Lines.
  • The above-given example is for a single line, like if you want to write an email or product name, etc.
Multiple Lines String in Python
  • If you want to write an essay, story, report etc. then you will need to use Multiple Lines string, which is created by placing triple quote around the data, as shown in below figure:
  • As you can see in above figure, we have written multiple lines in welcome string.

Strings Operators

  • If you are using an apostrophe, you will need to use use double quotes, otherwise, the interpreter will not be able to understand it and will give you a syntax error, as shown in below figure:
  • But if I write in double-quotes, then it will work fine, as shown in below figure:

Escape sequences in Python

  • If you are using double quotes in the same string, then you will need to use a backward slash ( \ ), as shown in the image.
  • Run the program and see the result in the console window:
Now I have another escape sequence ( \n )
  • If I want to add a new line break then I will use escape sequence ( \n ).
  • As you can see in below figure, I have printed the name & age of Richard in separate lines using escape sequence ( \n ).
Tab escape sequence is \t
  • I wrote it with tab escape sequence ( \t ) and run the program, see the six spaces in the printed window:
Some useful points before I move further:
  • You can use backward slash and forward slash \/ like this.
  • You cannot use the backward slash at the end of the string before the end of the quote.
  • You will use double backward slash ( \\ ), if you want to print one.

Concatenation in Python

  • In concatenation, we connect multiple strings together, we use ( + ) sign in order to concatenate strings.
  • Let's understand it with an example, as shown in below figure:
  • As you can see in above figure, I have printed multiple strings in a single line using ( + ) sign.

 String Formatting In Python

When we use multiple strings, it gets harder to concatenate those strings, and it is difficult to remember each string format and codes. In such cases, we need to format those strings. Let's understand it with an example:
  • In String Formatting, we simply place our variables in curly brackets, as shown in below figure:
  • No need to add multiple quotes and + symbol, instead simply use curly brackets for variables.

String Indexes in Python

In python, when we store a string, it goes with an index for each of its element one by one, because it is a sequence of characters. Let's understand it with an example:
  • For example, I saved the name "Ali Haider" in a string then each of its character has an index assigned with it.
  • I have shown the string and the index starting with a comment # in below image:
  • So, that means index of  A=0, L=1, I=2, (for blank space, it is also a character and its index is 3), H=4, a=5, i=6, d=7, e=8 and r=9.
  • After that, I have printed first three characters of that string by writing a range of [0:3], it eliminates the ending index and shows the result as from 0 to 2, which makes the word Ali. (see above image )
  • If you want to print till the final value, then you wont need to write the last index, you will just write it as [0: ].
  • If I write in this way, print(player_name[:]), then it will print the whole string again.
  • You can also write negative indexes like print(player_name[-1]) and it will print from the right side.
Before moving further, I will tell you a magical feature that only Python allows.
  • Type print("a" * 30) and check the magic in print window:

Builtin String Functions in Python

Python has numerous excellent builtin string functions, which we can access using  DOT ( . ) operator. These builtin functions are quite helpful, so let's have a loot at few of them: string.upper()
  • This upper() function will make characters of the string uppercase, as shown in below figure:
  • If, I write print(Precaution.isupper()), It will check the string, whether its uppercase or not.
  • If string will be in uppercase it will return True and if it's not in uppercase, it will return False.
string.lower()
  • Now let's convert string characters to lowercase by using lower() function.
  • When I type print(precaution.lower()), It will print the whole string in lowercase, as shown in below figure:
string.replace()
  • Now if we want to replace any word, then we need to use print(precaution.replace("WEAR", 'BUY')), It will replace the WEAR word with BUY, as shown in the image:
So, that was all about How to use Strings in Python. I have tried to cover all the main points and rest we will keep on covering in coming lectures. In the next lecture, we will have a look at How to use Arithmetic Operators in Python. Till then take care & have fun !!! :)

How to use Data Types in Python

Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to use Data types in Python. It's our 2nd tutorial in Python series. In our first tutorial, we have seen a detailed introduction to python and we have also installed PyCharm IDE to work on python. Today, we will understand data types in detail as in order to design an efficient program, you need to select correct data types. Incorrect selection may cause memory loss and may slow your application. So, let's get started with data types in Python:

Data types in Python

  • Data Types are used for the classification or categorization of similar data packets. There are numerous data types available in python, which we can use depending on our projects' requirement.
  • Let's understand data types with an example: Suppose you have some digital data i.e. ON & OFF then you can save this data in Boolean data type but what if your data ranges from 1 to 10, then you need to use integer data types instead of Boolean.
  • You can save Boolean data in integer data type but that will be a redundant i.e. we are allocating more space to our data by specifying integer, when we can easily assign Boolean to it.
  • Here's the flow chart of available data types in Python language:
Now let's have a look at these data types one by one:

Numeric in Python

  • Numeric data types are used to deal with all types of numerical data packets i.e. integer, float etc.
  • Numeric data types are further divided into 3 types, which are:
    • Integer.
    • Float.
    • Complex Number.
Integer in Python
  • Integer (int) data type only holds integer numbers, it could be positive or negative.
  • We can't save decimal numbers in integer data type.
  • Here's a declaration of a variable x and it is assigned a value a of integer 20:

x = int(20)

Float in Python
  • Float data types are used to hold decimal numerical values i.e. 2.13, 3.14 etc.
  • We can also save whole numbers in float data types.
  • Here's a declaration of a variable x and it is assigned a value a of float 20.5:

x = float(20.5)

Complex Numbers in Python
  • Complex Number data types is used to keep complex numbers in it. Complex numbers are those numerical values which have real & imaginary part.
  • That's the versatility of python language, I haven't seen complex number data type in any other programming language.
  • Here's a declaration of a variable x and it is assigned a complex number 1+3j:

x = complex(1+3j)

Dictionary in Python

  • Dictionary data type is sued to save data in key -> value  form. The data is unordered but the value is paired with its key.
  • Dictionary data is placed inside curly brackets i.e. {1:"Jones", 2:"IronMan", 3:"Football", 4: "Mosque"}.
  • Here's a declaration of a variable x and it's assigned a dictionary data type:

x = dict(name="John", age=36)

Boolean in Python

  • Boolean is the simplest data type of all and has just two values assigned to it i.e. True or False.
  • Although it's quite simple but its too handy as we have to use it a lot in IF statements. ( We will cover that later )
  • Here's a declaration of a variable x, assigned a Boolean data type and it's TRUE:

x = bool(1)

Sequence Type in Python

  • Sequence Type data types are used to save data in characters form.
  • We can't save numerical data in sequence type but we can convert the two. ( We will discuss that later )
  • Sequence Types are further divided into 3 types, which are:
    • String.
    • List.
    • Tuple.
Strings in Python
  • A string is used to save one or more characters and it's the most commonly used data type.
  • Let's understand it with a simple example: You must have seen greeting messages on different projects, we save such data in strings.
  • We will discuss strings in detail in our next lecture, where we will perform different operations using strings.
  • Here's a declaration of a variable x, which is assigned a string "Hello World":

x = str("Hello World")

List in Python
  • List data type is used to collect an ordered data, not necessarily of the same type.
  • List data is displayed with square brackets.
  • We will discuss this in our upcoming lectures in detail, here's a declaration of list:

x = list(("apple", "banana", "cherry"))

Tuple in Python
  • Tuple data type is used to arrange ordered data, it's quite similar to list but the data is displayed with small brackets.
  • Here's a Tuple declaration:

x = tuple(("apple", "banana", "cherry"))

So, we have discussed all these data types in python and if you are not understanding any of them yet then no need to worry as we are going to use them a lot in our coming projects, so you will get them. Before moving to next lecture, let's discuss variables in python a little:

Variables in Python

  • Variable is a temporary location in computer's memory, which is used to save the data.
  • As the name implies, we can change its value using different operations or information given to the program.
  • Typically, a program consists of commands that instruct the computer what to do with variables.
  • Variables are assigned with tag name, using which we call the value saved in it.
  • For examples: x = 5, here x is the name of the variable and 5 is its value.
  • In python, we can use special characters, letters, and any number as a variable name.
  • Wide spaces and signs with meanings like "+" and "-" are invalid in python.
  • You should remember that the names of variables are case sensitive. As the uppercase letter "A" and lowercase letter "a" are considered as different variables.
  • As variables are used to save data thus they also assigned a data type. So, a variable could be of int, float or string. (as we seen above)
  • In python, it's not necessary to define variable data type, python sets it dynamically.
  • There are some variables, which are reserved and we cannot use them.
  • We can also change the variables later and assign it to a new variable.
  • For example, I have set a value 10 in a variable eat.

eat=100

  • Then I added and stored the value of eat+10 in a variable cot.

cot = eat + 10

  • So, now cot will be 110.
Types of Variables Here I have set some examples of Variables and their types.
  • X = 456 #integer
  • X = 456L #Long integer
  • X = 4.56 #double float
  • X = "world" #string
  • X = [1, 2] #list
  • X = (0, 1, 2) #tuple
  • X = open('world.py' , 'r') #file
You may assign a single value to multiple variables at the same time.
  • Variable x, y, and z are assigned with the same memory location with the value of 1.

x = y = z = 1

  • Let's create few variables in python, I have created first_name, date_of_birth & last_name, as shown in below figure:
  • I have printed first_name and its appeared in the output panel.
So, that was all about Python Data Types & variables. I hope you have enjoyed today's lecture. In our next lecture, we will have a look at Strings in Python. Till then take care & have fun !!! :)

Introduction to Python

Hello Engineers! Hope you all are doing great. In today's tutorial, I am giving you a detailed lecture on Python programming language. As I am writing this tutorial for beginners, that's why I will discuss each & everything in detail, so it's going to be a very lengthy tutorial and I have divided it in parts.

We will start from basic concepts in Python and will slowly move towards advanced concepts. It's going to be a quite long bumpy ride but I will try my best to make it as smooth as I can. So, let's get started with basic Introduction to Python Language:

Introduction to python

  • Python is a multi-purpose, object-oriented High-Level Programming language, with applications in multiple areas, including scripting, machine learning, data sciences, scientific learning, cloud computing and artificial intelligence.
  • It is the most popular language of 2019, and it is going to flourish exponentially in upcoming years because of its versatility & flexibility.
  • Organizations like Google, NASA, and CIA are using it already.
  • Python processes at RUNTIME by the INTERPRETER, so you don't need to compile your program before executing it.
  • There are three major versions of Python programming language are available i.e. 1.X, 2.X and 3.X. They have sub-versions such as 2.2.3 and 3.3.1.

So, the IDE (Integrated Development Environment) which I am going to use is PyCharm Community Edition.

  • PyCharm Community Edition is free of cost and open-source. You can use it easily.
  • Jetbrains developed this for professional developers.

Prerequisites for Python

As I have told you earlier, I will start from the very basics and will cover almost everything about Python, so if you follow & practice this tutorial completely then you will surely learn Python, even if you are a beginner and know nothing about programming. But still, it would be better if you have:

  • knowledge of some basic concepts like loops, control statements, variables, etc.
  • It is not required to learn any other programming language before you learn python.
  • It is not required to have an engineering background to learn this language.
  • If you are from any other discipline like Sciences, Social sciences or any other academic field, you can still learn it.

Uses of Python

  • As I have mentioned earlier, Python is used in various areas like Machine learning, scripting, scientific computing, Artificial Intelligence, cloud computing etc.
  • So many communities are forced to use python these days, such as:
    • Network Engineers.
    • Software Engineers.
    • Data Analysts.
    • Mathematicians.
    • Scientists.
    • Accountants.
    • Website & App Developers.
  • A wide range of jobs are using this multi-purpose language, namely:
    • Desktop application development.
    • Mobile application development.
    • Web application development.
    • Automation Scripts.
    • Algorithmic and high-frequency trading.
    • Machine learning.
    • Artificial intelligence.
    • Software testing.
    • Hacking.
    • Mathematics.
    • Networks.
I hope now you have the idea of Python's importance these days. So, let's move on to the next step.

DATA SCIENCE AND MACHINE LEARNING

Data science and machine learning are the main reasons, why programmers are learning this language.
  • Python offers different frameworks and libraries, for example, PyBrain, PyMySQL, and NumPy.
  • Python experience allows you more than R Language.
  • You can create scripts to automate material and go with web developments, and so on, respectively.
  •  If you want to work in machine learning, you can easily work with Python.
  • Some of the examples of machine learning are, google chatbots. They answer your questions and queries through python algorithms.

Download & Install Python

Enough with the theoretical stuff, now let's get our hands on Python software:
  • First of all, you need to download Python, they have provided Python for Windows, Linux/UNIX, Mac OS X etc.
  • At the time of this writing, Python 3.8.3 is the latest version, so download & install it.
  • Make sure you check the Python path when you continue, otherwise, it will not work in the future.
  • Next, we need to download PyCharm, which is the IDE for professional developers.
  • You will find two versions on its download page i.e. Professional and Community.
  • We are going to download the community version for now, as we are in the learning phase.
  • You can download PyCharm for Windows, Mac & Linux.
  • After downloading the PyCharm, simply install it.
  • During installation, you need to check on the
    • 64-bit launcher.
    • Add launcher dir to the PATH.
    • Create Associations .py
  • I have ticked these 3 options, as shown in the below image:
  • Now click on the Next button and then click on Install and PyCharm will be installed on your computer.
  • You need to restart your computer for adding launcher dir to the PATH.

Creating First Python Project on PyCharm

  • Click the PyCharm icon and open the IDE.
  • On its first run, it will ask for the UI theme, which I am going to select Dracula, as I like the dark one.
  • Now, click on "Create New Project, select the location where you want to save your file and then click close.
We have created our first project in PyCharm and next, we need to add python files to this project. So let's start with the first Python program.
  • In the left window titled Project, we have a tree structure of our files.
  • These are library files that are necessary for running the project successfully, we will discuss them later.
  • So, in this Project Panel, we need to right-click on our Project Folder and then New and then select Python File, as shown in the figure on the right side.
  • Give a name to your file, as I have named it myy.py.
  • Now let's write our first line of code:

print("my world, my rules")

  • Click on Run in the top menu bar then select Run. You can also use the shortcut key (Alt+shift+F10).
  • IDE will ask you to select the file for execution, so we need to select our python file.
  • Once you select your python file, a new dialog box will open up at the bottom, and you will find your string printed there i.e. my world, my rules.
  • Here's the screenshot of our first Python code in Pycharm:
  • So, we have successfully executed our first Python code in PyCharm. :)

So, that was all for today. I hope now you have a better understanding of what python is and why its so popular. If you have any questions, please feel free to as kin comments. In the next lecture, we will have a look at datatypes in python. Till then take care and have fun !!! :)

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir