How to use ADC with STM32?

An Analog to Digital Converter (ADC) converts a continuous signal (usually a voltage) into a series of discrete values ??(sequences of bits). The main features are:

  • Resolution (in analog terms): It is the minimum variation of the analog input voltage that can determine the variation of the LSB, that is of the least significant bit of the output code. Since the quantization step Q corresponds to the LSB, it can be said that the resolution coincides with the quantization step Q (and therefore is measured in Volts). We can say that the quantization step Q corresponds to the LSB because two contiguous quantization bands, each of amplitude Q, are identified by codes that differ only for the least significant bit.
  • Resolution (in digital terms): It is the number n of bits present at the converter output, that is the number of bits with which the converter encodes a sample of the analog input signal. As the number of bits of the converter increases, the number of quantization bands increases and (with the same full-scale value VFS) their amplitude decreases, an amplitude which is nothing more than the step Quantization Q. If the quantization step narrows, the smaller the voltage variation necessary to determine the variation of the LSB, i.e., of the least significant bit of the code, becomes the exit. So, saying that a converter has many bits is equivalent to saying that the voltage variation necessary to make the LSB vary is small. The image below shows the 3 bits ADC input-output characteristics.
  • Full-scale voltage: It is the range, that is the maximum excursion, of the input voltage. Typical dynamic values are between 10 Vpp ( pp peak to peak) and 20 Vpp, unipolar or bipolar.
  • Types of response: in general, ADCs have a response of a linear theoretical type of response, but there are also types with a logarithmic response.
  • Accuracy: indicates the goodness of the conversion depends on it. The error made by the ADC is usually measured. This error consists of two components: a quantization error and a non-linearity error.
  • Sampling frequency: A sampling is an operation with which the input signal is discretized over time, transforming it into a succession of values, samples in fact, which will subsequently be digitized. The simplest way to extract values is to use a switch, in series with the signal, which closes and opens at defined and equidistant intervals. The smaller this interval, called the sampling step (Ts), the more faithful the reconstruction of the signal will be starting from its samples. Likewise, too small a sampling step leads to a waste of resources (measurement time, memory for data storage). A sampling of the signal generally indicates not only its discretization over time but also its maintenance until the next closing of the circuit-breaker. These two phases are realized by special circuits called Sample & Hold (S / H).

There are different types of ADCs, the most common are listed below (illustrating their operation is not the purpose of this article):

  • A direct conversion ADC (Flash ADC)
  • A Successive Approximation Register (SAR) ADC
  • One dual ramp ADC (Dual Slope or integration)
  • A pipeline ADC
  • A tracking ADC (delta-coded)

Generally, STM32 microcontrollers have at least one ADC (a SAR ADC) with the following characteristics:

  • Resolution: ADCs have a resolution of up to 12 bits with a maximum conversion frequency of 2.5 MHz, with 18 multiplexed channels among which 16 can be available for measurements of external signals, the other two are for internal measurements (temperature and voltage).
  • Conversion Time and Conversion Groups: The conversion time can be individually programmed for each channel. There are 8 discrete times conversions for each ADCCLK clock frequency (Fc), these times range from 1.5 to 239.5 cycles.

Fc = ADCCLK / (12.5 + Number of cycles)

Each ADC has two conversion modes: “regular” and “injected”.

  • The "regular" mode allows you to specify a channel or a group of channels to be converted in turn one after the other. The conversion core can consist of more than 16 channels, and the order in which the channels must be converted can also be programmed. The conversion can be initiated by software or by a hardware event consisting of a series of timer signals or by line 1 of the EXTI. Once the conversion has started, you can carry out continuous conversions, or you can operate discontinuously by converting a selected number of channels and then stopping the conversion pending the triggering of the next core. At the end of a conversion the result is stored in a single register (result register) and an interrupt can be generated. The ADC1 has a dedicated DMA channel that can be used for transferring the converted value from the result register to a memory buffer. Through this method, an entire conversion cycle can be copied into memory, eventually obtaining a single interrupt generated by the DMA. To further speed up the conversion, a double-sized buffer can be used to generate two interrupts: one when the first half has been filled (first conversion cycle) and the other when the second half is filled (second conversion cycle). This mode can be combined with the "DMA circular buffer mode" to handle multiple conversions with hardware.
  • The second conversion mode is called the “injected group”. It is able to carry out the conversion sequence up to a maximum of four channels, which can be triggered by a software or hardware event. Once triggered, it will stop the conversion of the regular group, carry out its sequence of conversion and then will allow the regular group to continue the conversion. A conversion sequence can be configured in this mode. Unlike the regular group, in this mode, each result has its own register (result register) and its own offset register. This last register can be programmed with a 16-bit value automatically deducted from the ADC result.

Furthermore, the "Dual Conversion Modes" can be active:

In the STM32 with almost two ADCs and it is, therefore, possible to perform different conversion modes: in these types of conversion the ADC2 acts as a slave while the ADC1 acts as a master allowing 8 different types of conversion.

  • Injected Simultaneous Mode and Regular Simultaneous Modes: These two modes synchronize the regular and injected group conversion operations on two converters. This is very useful when two quantities (current and voltage) have to be converted simultaneously.
  • Combined Regular / Injected Simultaneous Mode: This mode is a combination of both the regular and injected modes and allows us to have a synchronized conversion sequence.

We are now ready to write a first simple example using the ADC peripheral. The goal is to measure the voltage in a voltage divider composed of a fixed value resistor and a potentiometer (so that by moving the potentiometer cursor, the voltage to be read varies) we begin by configuring our peripheral with STCube Tool. For this project, we will use the NUCLEO STM32L053R8. This board has only one ADC with 16 channels and a resolution of up to 12bit.

Now we’ll see the configuration step by step:

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

ADC channel selection

We have to flag IN0 to activate Channel 0, then we can configure the peripheral. Channel 0 is on GPIO PA0 as we can see in the picture below:

ADC setting

We select the ADC_prescaler equal to 4, resolution to 12bit (maximum of a resolution, we can choice between 6, 8, 10 and 12 bits), “right data alignment” (we can choose between right and left alignment), and “forward” as scan direction (we can choose between forward and backward).

For this first example we’ll hold disabled Continuous, Discontinuous conversion and DMA mode. Furthermore, the ADC sets, at the end of single conversion, the EoC (End of Conversion) flag.

 

ADC Regular conversion mode

We select 12.5 Cycles as sampling time (in this way the sampling frequency is 320 kHz obtained from the formula described above), the start of conversion is triggered by software. Furthermore, for this application the watchdog is disabled.

After the generation of the initialization code with STCube, we can find in our project the ADC configuration. As for every peripheral, the HAL library defines the dedicated C structure, for the ADC defines “ADC_HandleTypeDef”.

 

In our case the “ADC1” is the instance that points to our ADC. The structure “ADC_InitTypeDef” is used to handle the configuration parameters. In our example is generated as follow:

static void MX_ADC_Init(void) { /* USER CODE BEGIN ADC_Init 0 */ /* USER CODE END ADC_Init 0 */ ADC_ChannelConfTypeDef sConfig = {0}; /* USER CODE BEGIN ADC_Init 1 */ /* USER CODE END ADC_Init 1 */ /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) */ hadc.Instance = ADC1; hadc.Init.OversamplingMode = DISABLE; hadc.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; hadc.Init.Resolution = ADC_RESOLUTION_12B; hadc.Init.SamplingTime = ADC_SAMPLETIME_12CYCLES_5; hadc.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD; hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT; hadc.Init.ContinuousConvMode = DISABLE; hadc.Init.DiscontinuousConvMode = DISABLE; hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START; hadc.Init.DMAContinuousRequests = DISABLE; hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV; hadc.Init.Overrun = ADC_OVR_DATA_PRESERVED; hadc.Init.LowPowerAutoWait = DISABLE; hadc.Init.LowPowerFrequencyMode = ENABLE; hadc.Init.LowPowerAutoPowerOff = DISABLE; if (HAL_ADC_Init(&hadc) != HAL_OK) { Error_Handler(); } /** Configure for the selected ADC regular channel to be converted. */ sConfig.Channel = ADC_CHANNEL_0; sConfig.Rank = ADC_RANK_CHANNEL_NUMBER; if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN ADC_Init 2 */ /* USER CODE END ADC_Init 2 */ }
The function HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) needs to initialize the peripheral and define the clock and the GPIO ( in our case PA0).
void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(hadc->Instance==ADC1) { /* USER CODE BEGIN ADC1_MspInit 0 */ /* USER CODE END ADC1_MspInit 0 */ /* Peripheral clock enable */ __HAL_RCC_ADC1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**ADC GPIO Configuration PA0 ------> ADC_IN0 */ GPIO_InitStruct.Pin = GPIO_PIN_0; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN ADC1_MspInit 1 */ /* USER CODE END ADC1_MspInit 1 */ } } /** * @brief ADC MSP De-Initialization * This function freeze the hardware resources used in this example * @param hadc: ADC handle pointer * @retval None */
The function HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) needs to de-initialize the peripheral.
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) { if(hadc->Instance==ADC1) { /* USER CODE BEGIN ADC1_MspDeInit 0 */ /* USER CODE END ADC1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_ADC1_CLK_DISABLE(); /**ADC GPIO Configuration PA0 ------> ADC_IN0 */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_0); /* USER CODE BEGIN ADC1_MspDeInit 1 */ /* USER CODE END ADC1_MspDeInit 1 */ } }

Before describing the code let's see how to make the connections on the development board.

We need a 10kOhm potentiometer and a 2kOhm resistor. The potentiometer is connected between 3.3V and 2kOhm resistor, the common point is connected to PA0, and finally, the other end of the 2k Ohm resistor is connected to the ground pin.

Acting on the potentiometer we will see the read voltage vary from 3.3 Volt to about 0 Volt.

Now let's dive into the code: In the Includes section we add the header file of main.
/* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */

In “Private variables” section we find “ADC_HandleTypeDef hadc” as previous said is an instance to C structure to handle the ADC peripheral. Then, we add three variables:

  • Resolution defines the number of steps used by ADC (12bit = 2^12 -1= 4095) is a constant integer;
  • vs defines the maximum voltage to read, is a constant float;
  • volt is the variable where the voltage value read by the ADC is store ( is a float variable)
/* Private variables -----------------------*/ ADC_HandleTypeDef hadc; /* USER CODE BEGIN PV */ const int Resolution = 4095; const float Vs =3.300; float volt; /* USER CODE END PV */

Then, we can find the protype of function to handle the peripherals and resources initialized (system timer, GPIO, and ADC).

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

Finally, the main starts.

In the first part we call functions to initialize the peripherals and resources used:

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_ADC_Init(); /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */

In the second part, that is, inside an infinite loop (while (1)) there is the function to start the conversion of the ADC, read the data and save it in the variable volt and finally stop the conversion wait for a second and start with the conversion and so on.

while (1) { /* USER CODE END WHILE */ HAL_ADC_Start(&hadc); if(HAL_ADC_PollForConversion(&hadc,10)==HAL_OK) { volt=HAL_ADC_GetValue(&hadc)*Vs/Resolution; } HAL_Delay(1000); HAL_ADC_Stop(&hadc); /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ }

Now, once our code has been compiled, we can debug it in real-time, just press the "spider" icon (see figure below) and see how the volt variable varies by acting on the potentiometer.

Once we have clicked on the debug button, at the top right, we can select the "live expression" window and add (by writing the name in the table) the variable to be monitored.

Now we can start the debug by clicking on the “Resume” button (on the top right) or by pressing the F8 key (on our keyboard).

We are now ready to read our voltage value. We will see that by acting on the potentiometer we will read the voltages in the whole range considered.

Some measures are shown below:

  1. First reading volt=1.3188 Volt
 
  1. First reading volt=3.29919 Volt
  1. First reading volt=1.02158 Volt
So, that was all about How to handle ADC in STM32 Microcontrollers. In the next tutorial, we are going to work on STM32 DAC operations. Till then take care !!!

STM32 SPI Communication

The SPI (Serial Peripheral Interface) protocol, or rather the SPI interface, was originally devised by Motorola (now Freescale) to support their microprocessors and microcontrollers. Unlike the I2C standard designed by Philips, the SPI interface has never been standardized; nevertheless, it has become a de-facto standard. National Semiconductor has developed a variant of the SPI under the name Microwire bus. The lack of official rules has led to the addition of many features and options that must be appropriately selected and set in order to allow proper communication between the various interconnected devices. The SPI interface describes a single Master single Slave communication and is of the synchronous and full-duplex type. The clock is transmitted with a dedicated line (not necessarily synchronous transmission that has a dedicated line for the clock) and it is possible to both transmit and receive data simultaneously. The figure below shows a basic connection diagram between two peripherals that make use of the SPI interface.

From the figure, it is immediately possible to notice what has just been said, namely that the communication generally takes place between a Master and a Slave. The interface presents 4 connection lines (excluding the ground however necessary), for which the standard SPI is also known as 4 Wire Interface. The Master starts the communication and provides the clock to the Slave. The nomenclature of the various lines in the SPI interface is normally as follows:

  • MOSI: Master Output Slave In. Through this line the master sends the data to the selected slave;
  • MISO: Master Input Slave Output. Through this line the slave sends the data to the master;
  • SCLK: Serial Clock is generated by the master device, so it is the master starts the communication and the clock synchronizes the data transfer over the bus. The SPI clock speed is usually several MHz (today up to 100 MHz);
  • SS: Slave Select or CS (Chip Select) generated by the master to choose which slave device it wants to communicate with (it must be set to a low logic level). SS (or CS) is not indispensable in all applications.

In addition to this standard nomenclature, there are other acronyms.

For example:
  • The MOSI line is also called: SDO (Serial Data Out), DO (Data Out), DOUT and SO (Serial Out)
  • The MISO line is also called: SDI (Serial Data In), DI (Data In), DIN and SI (Serial In)
  • The Clock line is also called: CLK, SCK (Serial Clock).
  • The Enable line is also called: CS (Chip Select), CE (Chip Enable)

The first advantage in SPI communication is faster communication, instead, the first disadvantage is the presence of the SS pin necessary to select the slave. It limits the number of slave devices to be connected and considerably increases the number of lines of the master dedicated to SPI communication as the connected slaves increase.

To overcome these problems, the devices in the daisy chain can be connected (output of a device connected to the input of the next device in the chain) as shown in the figure below where a single slave selection line is used.

The disadvantages, however, are the lower updating speed of the individual slaves and signal interruption due to the failure of an element.

We can use this communication to put in communication our micro-controller with different peripherals as Analog-Digital Converters (ADCs), Digital-Analog Converters (DACs), EEPROM memories, sensors, LCD screen, RF module, Real Time Clock, etc.

The STM32 micro-controllers provide up to 6 SPI interfaces based on the type of package that can be quickly configured with STCube Tool.

STCube Tool initializes the peripherals with HAL (Hardware Abstraction Layer) library. The HAL library creates for SPI (as all peripherals) an C structure:

  • struct SPI_HandleTypeDef
It is so defined: Where the main parameters are:
  • Instance: is the pointer variable it describes the SPI that we want to use. If we use SPI1, the name of the instance is SPI1.
  • Init: is an instance that points to the structure ( SPI_InitTypeDef) used to initialize the device. We will discuss the structure SPI_InitTypeDef shortly.
  • pTxBuffPtr, pRxBuffPtr: are pointer variables that point to an internal buffer. They are used to store the data during the communication when the programmer handles the SPI in interrupt mode (we will see forward)
  • hdmatx, hdmarx: are the pointer variable to instances of the DMA_HandleTypeDef struct. They are used when the programmer handles the SPI in DMA mode (will see forward).

As just said to initialize the SPI peripheral to be used, it is necessary to use the struct SPI_InitTypeDef. It is defined as follow:

When we use the STcubeMX to initialize the SPI peripheral we are modifying this structure

In details:
  • Mode specifies the SPI operating mode, and Direction specifies the SPI bidirectional mode state. It is very easy to configure in STCubeMx. If we want to configure the SPI1. We can find SPI windows in Pinout&Configuration -> Connectivity. Here we can select between the SPI available. Now is possible to select the communication mode (Master, Slave, half-duplex, full-duplex, etc.) as follow:

If the slave supports, the full-duplex communication can be enabled.

  • DataSize indicates the SPI data size. The user can select 8bit or 16bit.
  • CLKPolarity defines if the serial clock steady state is LOW or HIGH.
  • CLKPhase defines if the bit capture (trigger) takes place when the clock is on the falling edge or rising edge.
  • NSS: if selected "Output Hardware" the slave select signal is managed by hardware otherwise is managed by software using the SSI bit.
  • BaudRatePrescaler can be select the Baud Rate prescaler value.
  • FirstBit indicates if data transfers start from Most Significant Bit (MSB) or Last Significant Bit (LSB).
  • TIMode specifies if the TI mode is enabled or not.
  • CRCCalculation: to enable to activate the CRC calculation.
  • CRCLength: to define the length of CRC data.
  • CRCPolynomial specifies the polynomial (X0+X1+X2) used for the CRC calculation. This parameter is an odd number 1 and 65535.

By enabling the SPI and the chip select pin, the pins available on the microcontroller are automatically chosen to manage this interface (but they can be changed by looking for the alternative functions of the different pins of the microcontroller). For example, in our case the following pins are selected:

  • PA4 SP1_NSS
  • PA5 SP1_SCK
  • PA6 SP1_MISO
  • PA7 SP1_MOSI

Now you can generate the initialization code. Before being able to write the first code to manage this communication interface, it is necessary to understand the functions that the libraries provide and the different communication modes.

As for other communication interfaces, the HAL library provides three modes to communicate: polling mode, interrupt mode, and DMA mode.

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

STM32 SPI Communication in Polling Mode

Using the SPI in Polling Mode is the easiest way, but it is the least efficient way as the CPU will remain in a waiting state for a long time. HAL library provides the following functions to transmit and receive in polling mode:

  • HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)

Master receives data packets in blocking mode (polling mode).

The parameters are:

  • hspi is a pointer to a “SPI_HandleTypeDef” structure. “SPI_HandleTypeDef” structure includes the configuration information for SPI module.
  • pData is a pointer to data buffer
  • Size is the amount of data to be sent
  • Timeout is the timeout duration
  • HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)

Master transmits data packets in blocking mode (polling mode).

If the slave device supports, the full-duplex mode:

  • HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout)

Master transmits and receives data packets in blocking mode (polling mode).

The parameters are:

  • hspi is a pointer to a “SPI_HandleTypeDef” structure. “SPI_HandleTypeDef” structure includes the configuration information for SPI module
  • pTxData is a pointer to transmission data buffer
  • PRxData is a pointer to reception data buffer
  • Size is the amount of data to be sent
  • Timeout is the timeout duration

STM32 SPI Protocol in Interrupt Mode

Using the SPI in Interrupt Mode, also called non-blocking mode. In this way, the communication can be made more effective by enabling the interrupts of the SPI in order to receive, for example, signals when the data has been sent or received. This improves CPU time management. In applications where all the management must be deterministic and it is not known when an interrupt can arrive, these can potentially manage the time management of the CPU, especially when working with very fast buses such as SPI. We can enable the SPI interrupts directly during the initialization with STCube Mx.

HAL library provides the following functions to transmit and receive in interrupt mode:

  • HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
Master receives data packets in non-blocking mode (interrupt mode). The parameters are:
  • hspi is a pointer to a “SPI_HandleTypeDef” structure. “SPI_HandleTypeDef” structure includes the configuration information for SPI module
  • pData is a pointer to data buffer
  • Size is the amount of data to be sent
To handle the interrupt needs to write our code in the callback:
void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef * hspi) { // Message received .. Do Something ... }
  • HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)

Master transmits data packets in blocking mode (interrupt mode).

To handle the interrupt needs to write our code in the callback:

void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef * hspi) { // Message transmitted.... Do Something ... }

If the slave device supports, the full-duplex mode:

  • HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)

Master transmits and receives data packets in non-blocking mode (interrupt mode).

To handle the interrupt needs to write our code in the callback:

void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef * hspi) { // Message transmitted or received.. .. Do Something ... }

STM32 SPI Communication in DMA Mode

Using the SPI in DMA Mode the SPI bus can be used at its maximum speed, in fact, since the SPI must store the received and transmitted data in the buffer to avoid overloading it is necessary to implement the DMA. In addition, use by DMA mode frees the CPU from performing "device-to-memory" data transfers. We can easily configure the DMA during the initialization using STCubeMx :

In this case, the DMA is enabled in normal (we can use it in circular mode) mode both in transmission and reception

HAL library provides the following functions to transmit and receive in DMA mode:

  • HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)

Master receives data packets in non-blocking mode (DMA mode).

The SPI device receives all bytes of data in the buffer one by one until the end in DMA mode. At this point, the callback function will be called and executed where something can be done.

void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef * hspi) { // Message received .. Do Something ... }
  • HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)

Master transmits data packets in non-blocking mode (DMA mode).

The SPI device sends all bytes of data in the buffer one by one until the end in DMA mode. At this point, the callback function will be called and executed where something can be done.

void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef * hspi) { // Message transmitted….. Do Something ... }

If the slave device supports, the full-duplex mode:

  • HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size,)

Master transmits and receives data packets in non-blocking mode (DMA mode).

The SPI device sends or receives all bytes of data in the buffer one by one until the end in DMA mode. At this point, the callback function will be called and executed where something can be done.

void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef * hspi) { // Message transmitted or received.... Do Something ... }

We are now ready to handle an SPI communication with STM32.

Write and Read an I2C EEPROM with STM32

EEPROMs (Electrically Erasable Programmable Read-Only Memories) allow the non-volatile storage of application data or the storage of small amounts of data in the event of a power failure. Using external memories that allow you to add storage capacity for all those applications that require data recording. We can choose many types of memories depending on the type of interface and their capacity.

EEPROMs are generally classified and identified based on the type of serial bus they use. The first two digits of the code identify the serial bus used:

  • Parallel: 28 (for example 28C512) much used in the past but now too large due to having many dedicated pins for parallel transmission
  • Serial I2C: 24 (for example 24LC256)
  • Serial SPI: 25 (for example 25AA080A)
  • Serial - Microwire: 93 (for example 93C56C-E/SN)
  • Serial – UN I/O: 11 (for example 11LC040-I/SN)

Now we will see how to write or read data on an I2C EEPROM like 24C256C. This serial EEPROM is organized as 32,768 words of 8 bits each. The device’s cascading feature allows up to eight devices to share a common 2-wire bus. It is available in various 8-pin packages

The device can be used in applications consuming low power. The device is available in all standard 8-pin packages. The operating voltage is comprised of between 1.7V and 5.5V.

  • Serial Clock (SCL) is an input pin used to control data flow. On the positive-edge clock, the data is inserted into the EEPROM device, while on the negative edge clock, the data is processed out of the EEPROM module.
  • Serial Data (SDA) is a bidirectional input-output for serial data transfer. It is an open-drain pin.
  • Device Addresses (A2, A1, A0) are input pins to set the device address. These pins allow you to customize the address of the device within the I2C bus. They must connect directly to GND or to VCC (hard wired). If these pins are left floating, the A2, A1, and A0 pins will be internally pulled down to GND. When using a pull-up resistor, it recommends using 10kOhm or less.
  • Write Protect (WP) is an input pin. We can perform normal writing operations, by connecting it to GND; When connected directly to VCC, all write operations to the memory are restricted. If this pin is left open/floating, it will be pulled down to the GND(internally). When using a pull-up resistor, it recommends using 10kOhm or less.
  • Device Power Supply (VCC)
  • Ground (GND)

In our example, we connect A0, A1, A2 directly to VCC in this way the device address is 1010111 (in general A0, A1, A2 identify the last three significant bits of the device address 1 0 1 0 A2 A1 A0) is 0x57 in Hexadecimal. The 4 most significant bits are preset (Control Code), the A0, A1, A2 are Chip Select Bits.

Now we start with our project using STNucleoL053R8 and STCube to generate the initialization code. Below is shown the connection

  • A0, A1, A2 are connected directly to VCC in this way the device address is 1010111 (in general A0, A1, A2 identify the last three significant bits of the device address 1 0 1 0 A2 A1 A0) is 0x57 in Hexadecimal.
  • WP is connected to the ground to allow the normal write operation
  • SCL and SDA are connected to PA8 and PA9 respectively of STM32L053R8

So, we configure the I2C1 using STCube and leave all configuration as it is and we will operate in polling mode.

In GPIO setting select PA9 (SDA) and PA8 (SCL).

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 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 and enable in “Connectivity” the I2C1 and left all configuration as it is and we will operate in polling mode.
  • Configure in GPIO setting PA9 (SDA) and PA8 (SCL) to manage the I2C communication.
  • Check that the signals are properly assigned on pins:
    • SYS_SWDIO on PA13
    • TCK on PA14
    • SDA I2C1on PA9
    • SCL I2C1on PA8
  • 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.
  • Select Timers -> TIM2 and change the Prescaler to 16000 and the Counter Period to 1000.
  • 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 the /Core/Src/main.c we will find our main where we will write the main body of our program.

Now let’s see what the code generator did:

First of all, we find the “Include” section we can add the library needed.

 
/* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h"
In our case we can add also “stm32l0xx_hal.h” library to be able to use HAL library (I2C HAL library included)
#include "stm32l0xx_hal.h " #include "Var.h " #include "Funct.h "
In “Private variables” has been defined two privates variable htim2 and hi2c1;
  • - htim2 as first parameter an instance of the C struct TIM_HandleTypeDef;
  • - hi2c1 as first parameter an instance of the C struct UART_HandleTypeDef.
/* Private variables ---------------------------------------------------------*/ TIM_HandleTypeDef htim2; UART_HandleTypeDef hi2c1; unsigned short int address; // eeprom address unsigned char EEP_pag = 0x00 // EEPROM page unsigned char EEP_pos = 0x00 // EEPROM position unsigned char rdata = 0x00 // to store the data read from EEPROM
In “Private function prototypes” we find the protype 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_I2C1_Init(void);

This function has been generated automatically by STCubeMx with the parameter selected.

The main contains the initialization of the peripherals and variables, before the while loop the code call the function Write_EEPROM() and Read_EEPROM() to write and read a data in a specific address of the EEPROM. these functions were written in EEPROM.c, a C file added to our project in the src folder.

  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(); MX_I2C1_Init();   /* USER CODE BEGIN 2 */ address = 0x00 << 8 | 0x00 // eeprom page 0 , position 0 // Now we want to store 10 in page 0x00 and position 0x00 of EEPROM Write_EEPROM(address, 10, 0) // Now we want store in rdata variable the content of cell memory 0x0000 rdata = Read_EEPROM(address, 0)   /* USER CODE END 2 */   /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ } /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ }
Furthermore, we have added two header files and one c file:
  • Var.h contains the declaration of global variables:
/** Var.h * Created on: 27 ott 2021 * Author: utente */ #ifndef INC_VAR_H_ #define INC_VAR_H_ extern unsigned char buf[20]; extern int i; #endif /* INC_VAR_H_ */
  • Funct.h contains the prototype of the user function
/** Funct.h * Created on: 28 ott 2021 * Author: utente */ #ifndef INC_FUNCT_H_ #define INC_FUNCT_H_ extern unsigned char Read_EEPROM(unsigned int, unsigned char); extern void Write_EEPROM(unsigned int, unsigned char, unsigned char); #endif /* INC_FUNCT_H_ */
  • EEPROM.c contains the function written by the user to handle the writing and reading operation with EEPROM:
  • unsigned char Read_EEPROM(addr, device) reads from cell memory address (addr)and store the content in dato.
  • void Write_EEPROM(addr, dato, device) writes data (dato) to memory address (addr).
/** Serial.c * Created on: Oct 29, 2021 * Author: utente */ #include "stm32l0xx.h" // Device header #include "stm32l0xx_hal_conf.h" #include "stm32l0xx_hal.h " #include "Var.h " #include "Funct.h " extern I2C_HandleTypeDef hi2c1; unsigned char Read_EEPROM(unsigned int addr, unsigned char device) { unsigned char page; uint8_t dato; page=0xAF; // due to chip select bits setting HAL_I2C_Mem_Read(&hi2c1,page, addr, I2C_MEMADD_SIZE_16BIT, &dato,1,5); return dato; } void Write_EEPROM(unsigned int addr, unsigned char dato, unsigned char device) { unsigned char page; page=0xAF; //due to chip select bits setting HAL_I2C_Mem_Write(&hi2c1,page, addr, I2C_MEMADD_SIZE_16BIT, &dato,1,5 ); while(HAL_I2C_IsDeviceReady(&hi2c1, 0xA0, 1, HAL_MAX_DELAY) != HAL_OK); HAL_Delay(10); }
Now we are ready to compile and run the project:
  1. Compile the project within IDE.
  1. Download it to the board.
  2. Run the program.
So, that was all for today. I hope you have enjoyed today's lecture. In the next tutorial, we will have a look at How to perform SPI Communication with STM32. Till then take care and have fun !!! :)

Designing Logic Gates in PLC Simulator

Hello friends, I hope you all are doing great. In today's tutorial, we are going to design logic gates in PLC Simulator. It's our 4th tutorial in Ladder Logic Programming Series. We come today to elaborate the logic gates with comprehensive details for their importance in PLC programming. you can consider logic gates as the building blocks of ladder logic programming. Like every time we start with telling what you guys are going to have after completing this session? For those who like to buy their time and calculate for feasibility, I’d like to say by completing this article, you are going to know everything about what types of logic gates, how they are designed and how they work, how you can translate the logic in your head into the logic gate and some about logic calculation which is so-called logic algebra, and for sure the connection with examples between logic gates and the Ladder logic programming. In our previous tutorial, we have Created First Project using Ladder Logic, where we designed a simple logic by using contact and coil. Today, we are going to extend that code and will design different logic gates in ladder logic.

We are discussing these logic gates because they are the main building block of complicated logic. Normally, complex logic is designed using multiple logic gates. So, today, we will simulate the basic logic gates i.e. AND, OR, and NOT, while in the next lecture, we will simulate NAND, NOR, XOR and XNOR in PLC Simulator. So, let's get started:

Logic gates

In very simple language, it is a Boolean decision that has one of only two values either “TRUE” or “FALSE”, not both. For instance, the decision to run or shut down a motor, open or close a valve etc. Well! For deciding such Boolean nature thing, there are two things, inputs and logic to apply on those inputs. On the other way, logic gates apply some sort of logic to the inputs to determine the state of the output.

Truth table

It’s a table that lists all possible combinations of the inputs and the state of the output for each record. For example, a gate with two inputs has four possible combinations of the inputs and four states of the output. inputs.

Basics of logic gate

There are seven basic logic gates. Some of them have only one input while others have two inputs. There are seven basic logic gates which are “AND”, “OR”, “NOT”, “NOR”, “XOR”, “XNOR”, and “NAND”. So let us enjoy a short journey with them having a fast stop at each one’s station. Our trip will include, how they work, design, timing diagram, and connection with ladder logic programming.

Simulating ANR, OR, and NOT logic

  • The AND, OR, and NOT logic are considered the basic building block logic for designing the complicated logic to decide the output status.
  • By using two switches A and B and one output representing lamp or MOTOR, we can design and program these logics and simulate them on the PLCSIM simulator.
  • Table 1 lists the truth table of the three logic AND, OR, and NOT.

Table 1: Truth table of the AND, OR, NOT logic

Switch A Switch B Motor
AND LOGIC
0 0 0
1 0 0
0 1 0
1 1 1
OR LOGIC
0 0 0
0 1 1
1 0 1
1 1 1
NOT LOGIC
Switch Output
0 1
1 0

The “AND” Logic Gate

The “AND” logic gate has two inputs and one output. Like its name, the only condition for having the output become true, is by having both inputs, input A and input B are true. Table 1 lists the truth table of the “AND” gate and Fig. 1 images the symbol of the “AND” gate. In addition, Fig. 2 shows a sample of ladder logic rung that uses “AND” gate logic. It decides the status of the motor based on two switches. The two switches must be in true status for running the motor. ‘to sum up, the logic of the “AND” gate, is that, the output comes to true when and only when both inputs A and B are true.

Table 1: the truth table of “AND” logic gate

Input A Input B Output
False False False
True False False
False True False
True True True

Fig. 1: symbol of “AND” logic gate [1]

In the ladder logic rung shown in Fig. 2, there are two contacts I1 and I2, they are of normally open (NO) type, these two contacts are connected in series, so the only way to set the output to true is that both contacts I1 and I2 must set to true. For full imagination, please notice the timing diagram of the inputs and output signals shown in Fig. 3. It shows the output is only high when both inputs are high.

Fig. 2: sample ladder logic rung for “AND” logic [2]

Fig. 3: The timing diagram of the “AND” logic gate

AND logic in PLC simulator

  • Let us once more enjoy learning further by validating and practicing on the simulator, here you can see in figure 19, on the right the AND logic has been programmed by connecting two switches A and B in series.
  • The motor status is the result of the AND logic between the two switches.
  • On the left, you can see the results of the simulation by setting the status of switches to simulate all truth table conditions and see the motor status changed accordingly.
  • In addition, you can see the truth table of the AND logic on the most right of the figure. So you can review and validate what is going on in the simulator.

Figure 19: Simulating AND logic

The “OR” Logic Gate

This logic gate has two inputs and one output like the “AND” gate. Like its name, the output comes true when either input A or input B comes true as shown in Fig. 4.

Fig. 4: The symbol of “OR” logic gate [1]

Table 2 lists the truth table of the “OR” gate. It lists all possible combinations of inputs and the output status as well. It shows that the output comes to true when input A or input B comes to true.

Table 2: The truth table of the “OR” gate

Input A Input B Output
False False False
True False True
False True True
True True True
 

Figure 5 shows an example of a ladder logic rung that implements the “OR” logic. We can implement this by connecting two inputs I1 and I2 in parallel branches and to the output. like this way of connection, the output can be set to true by simply setting I1 or I2 or both true. Once more, let us see the timing diagram in fig. 6, it is clearly shown that the output goes high as long as either one or both of the inputs are true.

Fig. 5: sample ladder logic rung for “OR” logic [2]

Fig. 6: the timing diagram of the “OR” logic gate

OR logic in PLC Simulator

  • You can see in figure 20, on the right the OR logic has been established and programmed by connecting two switches A and B in parallel.
  • The motor status is the result of the OR logic between the two switches.
  • On the left, you can see the results of the simulation by setting the status of switches to simulate all truth table conditions of the OR logic and see the motor status charged accordingly.
  • In addition, you can see the truth table on the most right of the figure. So you can review and validate what is going on in the simulator.

Figure 20: Simulating OR logic

The “NOT” logic gate

This logic gate has only one input and one output. In a very simple language, the output is the invert logic of the input. So when the input is true, the output would come to false and vise versa as shown in Fig. 7.

Fig. 7: The symbol of the “NOT” logic gate [1]

Table 3 lists the truth table rows of all possible combination of input and output.

Table 3: the truth table of the “NOT” logic gate

Input Output
True False
False True
 

Figure 8 depicts a very simple example of a ladder logic rung that shows the output Q1 is the reverse logic of the input I1. In addition, Fig. 9 shows the timing diagram of input and output of the “NOT” logic gate. It shows clearly that, the output is the reverse of the input.

Fig. 8: Sample of the ladder logic rung representing “NOT” logic [2]

Fig. 9: The timing diagram of the NOT logic gate

Before going further with the logic gates, I want to let you know the good news that, you can implement any logic by using the aforementioned three logic gates “AND”, “OR”, and “NOT”. However, for simplification, the other logic gates are designed based on using these three logic gates in different topologies to perform a specific logic functions.

Not logic in PLC Simulator

  • Also, the NOT logic is one of the primary logic functions, you can see in figure 21, on the right the NOT logic has been designed and programmed by connecting switches A in negative logic in series with the motor.
  • The motor status is the result of the NOT logic of switch A. On the left, you can see the results of the simulation by setting the status of the switch to simulate the two-state of the NOT logic truth table and see the motor status charged accordingly.
  • In addition, you can see the truth table on the most right of the figure. So you can review and validate what is going on in the simulator.

Figure 21: simulating Not logic

Now! I appreciate your follow-up to our PLC tutorial. I am very happy to feel that, by moving further in our plc tutorial our experience is getting increasing bit by bit. However, some questions may come to our mind like does the operator needs to keep pressing input like the push button to keep the motor running? What happens if he released it, does the motor stop? Well! By asking such questions, I can affirm you start your way to master PLC programming and its logic. And let me say the answer to your questions is yes the operator needs to keep pressing the input push-button until the motor has done its task. But that is not the best practice in the real life. There are other techniques to keep the motor running by one touch of the push button, thanks to latching, setting, and resetting techniques as we will show you in the next sections.

Latching output

  • Figure 22 depicts the latching technique that we simply use to keep the motor running by pressing the input push button and having it keep running even after releasing the button.
  • As you can see, I have used the Output as a Virtual Input and placed it in parallel with actual input.
Figure 22: Latching output
  • Table 2 lists the First three scan cycles to show the sequence of operations and how the latching process works when someone will press the Input.
  • In the first scan cycle, when the input gets HIGH, the plc will scan the input "Run (I0.0)" and will find it pressed/ON and thus will make the output "Motor (Q0.0)" HIGH.
  • In the second scan cycle, the input "Run (I0.0)" turned off after being released, but the motor contact is still ON from the previous scan cycle.
  • So, the compiler won't change the status of the OUTPUT and we can say it's latching the output.

Table 2: The first three scan cycles of latching operation

Scan cycle Run (I0.0) Motor status (Q0.0) Motor coil (Q0.0)
1 1 0 1
2 0 1 1
3 0 1 1
  • Now let’s add a way to terminate the latching and stop the motor as per request.
  • Well! Simply figure 23 shows a stop button is added for terminating the latching condition.
  • So in table 2, the RLO for letting the motor running will be unfulfilled by hitting the stop push button in the third scan cycle.
Figure 23: latching with stop button

Simulation of the latching in ladder logic

We may be sure of the logic we wrote for coding the ladder logic of the latching technique. However, at this point how about going to the simulation lab to work out our latch ladder logic program to enjoy validating our ladder code by putting it in the simulator and see how far it match what it is designed for.

Latching Ladder code simulation

  • Now let’s try our latching ladder program in the PLCSIM simulator, by entering our ladder logic and starting the simulator.
  • Figure 24 shows the first four scan cycles. Notice on the left we can set the inputs on and off and see the effects on the right part.
  • In the first scan, every single input and output is at its initial state, so the output is not energized.
  • In the next scan cycle, you can notice we switch on input at I0.0 which is the start push button.
  • Therefore, the motor has been started and running. In the third scan cycle, the start button is switched back off.
  • However, the motor still runs thanks to the latching technique. WOW, we can see our logic is working as we designed for.
  • In the last scan cycle, we tried to test stop latching by hitting the stop pushbutton and indeed it stopped latching and the motor stop running.

Figure 24: simulation result of the first ladder program

We will concentrate on moving forward with ladder coding which is our target. However, we just tried to show you at any time you can validate your ladder at any point to enjoy and confirm you are on the right track as long as you are working on your project.

Latching using set and reset

Let’s use another approach for latching which is based on using set and reset coil. Figure 25 shows the set and reset methods.

  • By hitting set_valve at address I0.2, the valve at Q0.0 will be set ON until a reset command is present by hitting the reset_valve pushbutton at I0.3.
  • It is very easy but you need to take extra care while using set and reset as the last set/reset command will overwrite the previous commands.
  • But wait, what’s if an operator keeps pressing the rest or set button for a long time or if the pushbuttons are the stuck and same thing for the stop button.

Well! The rational expectation is that the motor won’t be able to start. However, the good thing is there is a magic solution to differentiate between the situation of this is a normal stop request by the operator or the button is hold pressed unintentionally or due to an issue with the switches. The one-shot technique can magically recognize the event of pressing or releasing the pushbuttons. Therefore, when it is held for a long time or forever that is only one button press event and for triggering it needs to release and pressed once again. That’s amazing but how does it work? Well! Let’s go demonstrate the concept of how it works, implementation using ladder logic, and give an example to understand it consistently and enjoy the magic of one-shot action.

Figure 25: set and reset for easy latching output

The signal edges

Two edges happened when a pushbutton pressed and released which are falling edge and rising edge as shown in figure 26. It depicts the rising edge when the button is pressed and the falling edge when it has been released. Now, let's move to ladder logic, there are two equivalent rising and falling edge contacts that can be used to tell the PLC this is a one-shot signal. Figure 27 shows how the use of the rising edge of the reset pushbutton |P| at address I0.3. it shows that despite the reset being pressed, its effect in the moment of pressing and then it needs to be released and pressed again to reset the valve at Q0.1. in the next section, let’s get to business and work out one practical example which represents a real problem in the industry just to harvest the fruit of what we have learned so far.

Figure 26: The rising and falling edge [2]

Figure 27: The effects of one-shot technique in ladder logic

So, that was all for today. I hope you have enjoyed today's lecture. In the next tutorial, we will simulate Advance Logic Gates using Ladder Logic Programming. We will design NAND, NOR, XOR and XNOR gates in the next lecture. Thanks for reading.

Creating the First Ladder Logic Program in PLC Simulator

Hello friends, I hope you all are doing great. In today's tutorial, I am going to create the first Ladder Logic Program in PLC Simulator. It's 3rd tutorial in our Ladder Logic Programming Series. In our previous tutorial, we have installed PLC Simulator and now we can say our lab is ready to learn and practice. So let us get to work and get familiar with the ladder logic components.

After this article, you will have a complete understanding of PLC contact and coil including their types and possible causes. Because they are the building block of any rung of a ladder logic program. So let us start with ladder logic rung components.

Ladder Logic Contact/Input

  • In ladder logic programming, a contact represents the input of the system and it could be a button press by the operator or a signal from the sensor.
  • Examples of contacts are toggle switches, pushbuttons, limit switches, sensors like level, pressure, proximity switches et cetera.
  • There are two types of contacts normally used, which are:
    1. Normally Open Contact.
    2. Normally Closed Contact.

1. Normally Open Contact

  • A normally open contact is Open/LOW by default and it gets Closed/HIGH by pressing or getting signal from any external source i.e. sensors.
  • As shown in the first row of figure 1, the contact is open or disconnected by default and then the operator turns it to closed or connected status, shown in the second row.

Figure 1: Normally Open (NO) contact [1]

  • Let's understand it with its equivalent electrical circuit, imagine you wire a switch in series to a lamp as in figure 2.
  • After you complete wiring and connect L1 to the hotline and L2 to the neutral.
  • See that at the start the lamp is off until you come and press the pushbutton then it is turned on.
  • So, here the switch is acting as a normally open switch.

Figure 2: Normally open contact or switch in a circuit [2]

 

2. Normally Closed Contact

  • A normally closed contact is at HIGH/Closed state by default and gets Low/Open if pressed by the operator.
  • Figure 3 shows the symbol of normally close contact.
  • So it flows current at the very beginning and disconnects the current flow by being pressed by the operator to become like an open circuit or contact.

Figure 3: Normally Closed (NC) contact

  • For elaborating the behavior, let us wire a circuit that is depicted in figure 4.
  • The contact is connected in series with a lamp to convey the current and let it turn on.
  • So initially, the lamp started in ON status when the contact is not activated by the user.
  • And, when the operator activates the contact it turns off.
  • So, the switch is acting as a normally closed switch.

Figure 4: Normally close contact or switch in a circuit [2]

 

Ladder Logic Coil/Output

  • The coil in ladder logic represents the actuator or the equipment we aim to turn on or off.
  • A good example of a coil is a lamp and motor.
  • Typically it is located at the most right side of the ladder logic rung.
  • Same as contact has two types based on the initial state and the next state after user activation, also the coil comes in two forms which are:
    1. Normally Active Coil
    2. Normally Inactive Coil as shown in figure 5.
  • An inactive coil is normally not energized until it gets connected by connecting the left side to the hot wire thanks to a contact.
  • In contrast, active or negated coil type comes initially On status or energized and turned off when the left side is connected to the hot wire.

Figure 6: active and inactive coil

 

Create First Ladder Logic program

To our fortune we no longer need wires and devices to practice what we have been learning together, thanks to the simulator, which we have installed in the previous lecture. Let's create a new project on TIA portal software and test it with the PLCSIM simulator.

Creating a new project on TIA Portal

As this is the first time to use our software to write and simulate a ladder logic code, let us go step by step creating our very first project on the TIA portal software.

  • You now get in the Lab by opening the TIA portal and hitting create a new project as shown in Figure 7.
  • On the right, you just need to name your project like “new project” and you may leave the default location of projects or alter the data to the project file location as you prefer.

Figure 7: Creating a new project on TIA portal software

  • You will have to select a PLC controller whom we are going to use. So you simply select one PLC controller as shown in figure 8 and click okay.

Figure 8: adding PLC controller

  • The wizard now goes on asking you to add a program block.
  • You can see in Figure 9, the default program block is the Main block which has the main program and other blocks are additional blocks.
  • So for now let us go with the essential requirements for our program which is the main block and you just double click on the Main block to go to the next step.

Figure 9: adding program block

I just want to say well done! And congratulate you that you are now all set to start writing your first ladder logic rung as shown in Figure 10. It shows on the left the project components including hardware i.e. devices and controllers, networking devices, configurations, program blocks etc. The most important thing you need to know for now is the program blocks which contain the only main block and other blocks as the project needs. Now! please stare your eye toward the right to see the icon bar that contains every ladder symbol. You can see the contact of normally open and normally closed. Furthermore, you should see the coil and more which we are going to go into detail later in our upcoming articles of PLC tutorial.

Figure 10: starting writing ladder code

Writing First program on the TIA Portal

  • WOW! You are a superb learner as I can see you can follow figure 11 and by dragging a contact and dropping it on the blue line, you added a start button of normally open (NO) contact type.
  • For identifying contacts and coils, the compiler assigns a unique name & address to each component and can recognize it anywhere in the program.
  • Therefore, you just set the address and name for every component you add to your rung.
  • The address of components has a specific format that is very logical and easy to understand.
  • For example, the contact address “I0.0”, the first character is “I” which denotes input and it is followed by the number of the input module in the rack that holds all inputs and outputs modules.
  • Then a number of the input channel as each input module has many channels.
  • For instance, an eight channels input module can have numbers from 0 to 7 while 16 channels input module can have numbers from 0 to 15.
  • A period is used to separate between the number of input modules and the channel number.
  • So by set address I0.0, this refers to the very first channel in the first input module in a PLC rack.
  • In addition, a name is used as a tag to easily identify the input i.e. “start” to refer to a start switch.
  • Similarly, you add a stop button of the type normally closed (NC) with address I0.1 which means the second input channel in the first input module.
  • Furthermore, you double-clicked the coil for the motor and set address Q0.0 which means the first output channel in the first module.
  • I know you wonder what is “Q”? Yes! “Q for denoting output like “I” is denoting an input. Well done!. Now let us enjoy simulating the very first code you just have done yourself.

Figure 11: writing the first ladder logic program

 

Compiling Ladder Logic Program

  • Like any programming language, the first thing to do after writing a program is to compile, to make sure it is free of error and ready to be downloaded into the PLC controller to run.
  • Figure 12 shows the very simple steps to compile your program by clicking the compile icon in the toolbar which is highlighted in yellow.
  • And you can notice in the lowest window below the results of compilation in blue showing that the code is free of error and warnings.

Figure 12: compiling ladder logic program

  • To let you imagine how the compiler can help you to find the error location and type, we have done one mistake in the code and compiled as shown in figure 13.
  • You can notice that compiler is telling the rung that has the issue which is network 1.
  • In addition, the message clarifies the error by telling, you missed the required data for operand which is the address of input is missing.

Figure 13: Example of an error in compilation

Simulating First ladder logic program

  • After compiling our program successfully, now the next step is to download it to the PLC controller.
  • Yes for sure our simulator will act as the plc controller.
  • So, by clicking the simulator button on the toolbar, the simulator window comes out and also another window to download the program to the controller as shown in figure 14.

Figure 14: calling simulator and downloading program

  • You simply hit the “start search” button to search for the connected PLC controller.
  • In our case, the simulator will appear in the search results.
  • So, you just select it and click load to proceed with the wizard of downloading your program as shown in figure 15.

Figure 15: the wizard of downloading the ladder program to plc controller

  • By reaching the last screen and clicking finished you have downloaded your first program to the simulator.
  • Well done! And let's move forward with simulating our first program to validate our code and enjoy tracing the logic behavior same as a real-time plc controller.

But wait! Will you continue pressing the push button for our motor to keep running? For sure No, there should be a way to let it keep running by just hitting the button thanks to the latching technique.

Simulating our first PLC Program

  • After downloading the program and pressing the run button on the very small window of the PLCSIM simulator, we can notice the run/stop indicator turned on in green showing the running status of the PLC as shown in figure 16.
  • Now, click on the monitor icon on the toolbar highlighted in yellow on the most right of figure 16, you can notice the rung shows every status of each contact and coil in our program.
  • I am very happy to reach this point at which you can see the normally closed contact is showing a green connection as we described above and the normally open contact showing disconnect status and can not wait until the operator press it down to connect and energize the output.
  • But how do we press the buttons or switches when we are simulating? There is no physical switches or button to press!!! No friends that are not the case. Let us see how that can happen thanks to the great simulator that we have between our hands.

Figure 16: Simulating the first PLC code

Simulating the operator behavior

  • This section is more than exciting, it shows you how the simulator not only does imitate the PLC controller but also it has the facility to imitate devices, switches, push buttons besides showing outputs’ status and values.
  • In addition, we will go further in plc programming to show the series and parallel connections of contacts in branches and utilize simple logic AND, OR, NOT to form simple and complicated logics.
  • The first way to set inputs on and off is by right-clicking on any contact and modifying the status to 0 or 1 as shown in figure 17.

Figure 17: forcing the inputs on and off

  • The other way is to go to the expert mode of the full functional simulator, by hitting the which icon on the very small simulator window.
  • A full version of the simulator control window will open up, where you can add inputs and outputs on the right as you can see in figure 18(left side).
  • You can notice the inputs have an option in form of a check button to set it on or off.
  • As a result, the contact will be turned into the selected status and the program perform according to the new status and the designed logic of your program as shown in figure 18 on the right side.
  • It shows the output coil is turned to true status and highlighted in green.
  • At this point, I would like to thank you my friends to follow up on our PLC tutorial series and let us move forward to learn further and do more practice with our simulating lab.

Figure 18: operating using simulator full control window

 

What’s next

Now, how do you see your progress so far? I can see you have just completed the most basics of ladder logic programming. You are now very familiar with the ladder basic components, using the editor to write a ladder logic program, simulate your work for verifying your logic correctness. So you are doing progressively and that’s great to hear that. However, we still have a lot to learn to master ladder logic programming. For example, using blocks like timers, counters, mathematical blocks, data comparison etc. So we hope you have enjoyed what we have reached so far in our PLC tutorial and please get yourself ready for the next part. In the next part, you will learn about types of Timers and how you set their configuration and how you utilize them to achieve the timing-based tasks accurately.

Installing PLC Simulator for Ladder Logic Programming

Hello friends, I hope you are doing very well! In today's tutorial, we will set up a simulation environment for Ladder Logic Programming. It's our second tutorial in Ladder Logic Programming Series. In our previous tutorial, we have seen a detailed Introduction to Ladder Logic Programming and we have seen that this programming language is used for PLC controllers.

As PLC is an Industrial Controller, it comes with built-in relays/transistors(with protection circuitry) and thus is quite expensive as compared to microcontrollers/microprocessors i.e. Arduino, Raspberry Pi etc. Moreover, if you are working on a real PLC, you need to do some wiring in order to operate it. So, in order to avoid these PLC issues at the beginning, instead of buying a PLC one should work on a PLC Simulator. Using PLC Simulator, we can program our PLC controller and imitate its real behavior without having the hardware, saving both time and money as now we don't need to buy a new PLC and can start right away.

To sum up, by completing this article you will have a complete lab that includes the software you are going to use, the simulator that plays as the hardware, and certainly, you will be familiar with installing a PLC programming environment by which you can program, configure, moving the program to the PLC hardware, retrieving the program from the PLC to the software environment, and testing your program on the simulator. In addition, we are going to test our environment setup with a very basic program and take the chance to show you how to program, configure, upload, and test your program on the simulator.

Setup PLC Simulator

As I mentioned in the last tutorial, we are going to work on Siemens PLC throughout this tutorial, as it's one of the most common PLC controllers. So, we are going to install PLC Environment designed by Siemens and is called Total integrated automation (TIA). Along with this software, we will also need to install a PLC Simulator called S7 PLCSIM, again designed by Siemens. At the time of this writing, their most stable versions are 15.1, so download these two applications from below links:

Installing TIA Software

After downloading the TIA and the simulator, we extract the package by double click on the file we downloaded, and then it will be self-extracted and initiate the setup wizard as shown in the below figure. The image shows many steps. Moving our eyes from left to right, on the first part, the downloaded package has been extracted. In the next part of the picture in the middle, the setup wizard gets started by general settings in which you can set the preferred language and select the preferred installation location. The third part shows the setup goes on progressively and takes you to the end of the installation of the software IDE. Congratulation! You know have the programming software IDE installed on your computer and the good news is, all packages of Siemens go with the same scenario, you download the software package files. Click them to be extracted. And then, the installation wizard is launched by the end of file extraction which is a very systematic and easy way.

Figure 2: TIA portal version 15.1 setup wizard

 

Installing the PLC simulator

Well done so far! After having the programming software IDE completed, the next step is to install the simulator package which is PLCSIM version 15.1. Download PLCSim from the above link and then double-click the downloaded file of the simulator package as shown in Figure 3 to start extracting the packed file. You will be asked for the language and the location you prefer to have the installation folder. So you can leave it as the default or go with your preferences.

Figure 3: PLC simulator PLCSIM version 15.1 package extraction

After file extraction has been completed, the setup wizard will start automatically as shown in Figure 4 with the general setting screen by which you can set the preferred language and the location to install the simulator software. So you can use the default setting or update with your preferred choices.

Figure 4: the simulator setup general settings

Figure 5 shows the simulator setup configurations screen which helps you to configure and customize your installation. In this configuration screen, you can go with the typical options of installation in which all software components are selected to be installed or you can customize your installation to select or deselect components of the package. And by hitting the next button of this window, the installation will go on as shown in figure 6 until the end of the installation. During the installation progress, Siemens show off the features you may find in the software and the facilities you will enjoy by using this software. At the end of the installation, the wizard will request you to restart your computer now or later for completing the setup wizard by saving settings and registry values related to the installed software as shown in figure 7. That’s great! As for now, you have everything is ready and you are all set to get started and enjoy practice and learning the ladder logic programming and simulating your work.

Figure 5: the simulator setup configurations

Figure 6: the simulator installation screen

Figure 7: Simulator setup completion screen

Checking the setup environment

Before going any further let us check the successfulness of the installation process of the software and PLC simulator. Simply go to start and open TIA portal 15 and S7-PLCSIM you will see the software opening with no problem as shown in Figures 8 and 9. In figure 8, you can see options to create a new project or open an existing project. Also, there is an option to migrate projects from one version to another version by upgrading or downgrading the version of the projects. In addition, you can enjoy the welcome tour to know about the software programming tools and be familiar with its components. In addition, there is an option to check the installed software to validate the packages you select to include within your installation. for any further information you can click help to search and inquiry about any doubts.

Figure 8: Opening the TIA 15 software for testing installation successfulness

Moving to the S7 PLCSIM simulator software, as you can see in Figure 9, it is a very smart and simple interface. It shows a power button by clicking it you can shutdown the PLC controller or turn it on. Also, all indicators like the real PLC controller are included. You can see the RUN/STOP indicator. In addition, the ERROR indicator blinks red for any faults with the CPU of the PLC. In addition, you can see the run and stop buttons to start and stop the controller. Also, the MRES button to reset the PLC to the default values at any time. In addition, there is a detailed interface of the S7 PLCSIM simulator as shown in Figure 10. You can launch the detailed or maximized interface of the simulator by hitting the top-right icon on the shortcut window version of the simulator.

Figure 9: Opening the PLC simulator PLCSIM 15 for testing installation successfulness

The shortcut or the small version of the simulator shows the basic functions of the simulator like starting and stopping the controller or resetting the PLC and showing the status of the controller i.e. Run, stop, in fault status. But, the maximized or the detailed window simulator interface shows more options and facilities of the simulator. For example, you can create a simulation project to link it with a PLC project. Showing status of all input and output channels on the Input and output modules. In addition, it enables you to set and reset any of the inputs as we will elaborate in detail later in the next articles.

Figure 10: Opening the PLC simulator PLCSIM 15 in detail mode

Validating the PLC Simulator

After completing the installation successfully of the programming tools software TIA version 15.1 and the simulator PLCSIM version 15.1, it should be validated to make sure all components are installed and working properly. Let us validate by going through the functions and wizard. You now get in the Lab by opening the TIA portal and hitting create a new project as shown in Figure 11. On the right, you just need to name your project like for example let it be “first_ladder_prog” and you may leave the default location of projects or alter the data to the project file location as you prefer.

Figure 11: Creating a new project on the TIA portal

By hitting create, the creating project wizard comes out as shown in figure 12. As you can see you have many options to do on this screen like configuring the hardware, designing visualizations by designing and programming a human-machine interface (HMI) screen, motion control, or writing a ladder logic program. As for now do not worry about all these options as they are all not our scope in this series except those are relating to ladder logic programming like writing program option and configuring PLC device and network which we will come to them later in the next articles. For testing the installed software, you can simply select write a plc program for now.

Figure 12: creating project wizard

By choosing to write a PLC program, the wizard takes us to add the controller on which we are going to run the designed program as shown in Figure 13. If you are not familiar with the type of PLC controller models and hardware for now. That is not an issue because we are here to learn Ladder logic programming which is general for most PLC controllers of all brands i.e. Siemens, Schneider, Rockwell Automation, Allen Bradley, Beckhoff, WAGO, et cetera. So, for now, let us for testing purposes select S7-1200 which is one of Siemens PLC controllers to use in our project. By hitting the yellow small cross icon to add a device. You will see the list of the Siemens controllers that have appeared. For each controller, you can see many versions. Each version represents firmware for example, by selecting S7-1200 CPU 1211C AC/DC/RLY, you will see three versions. Each version represents a specific controller CPU in the market i.e. the selected one if of firmware ver 4.2 as shown in figure 14. By seeing this long list of CPUs and models, that means the software has been installed successfully and is ready to be used in our projects. So congratulation for successfully setting up the working environment for our Lab of ladder logic programming and being ready for utilizing this environment including programming software TIA 15.1 and simulator S7 PLCSIM version 15.1 in our learning and practice.

Figure 13: adding PLC controller wizard

Figure 14: selecting S7-1200 CPU v4.2

What’s next?

We are now all set to write our first ladder program on the TIA software and enjoy simulating our work on the S7 PLCSIM. In our next tutorial, we will write our first ladder logic program on the PLC simulator. Thanks for reading.

Everything You Need To Know About Anodizing Aluminum Colors

Manufactured parts need a quality surface finish and visual appeal before releasing them to the client or market. Although there are different methods of applying the surface finish, anodizing aluminum colors produce the best results.

There is a wide range of aluminum anodizing colors to choose from; therefore, product developers need to know how to color match before releasing the end product. Let’s examine more on anodizing aluminum parts, how to color anodized aluminum and the common anodized aluminum colors.

What is Aluminum Anodizing?

Anodizing is an electrolytic process that produces excellent mechanical properties to enhance aluminum parts' durability and visual appeal. Manufacturers use the anodizing process for corrosion resistance to prevent surface scratches and improve surface hardness, making it an ideal foundation for painting or coating.

The aluminum parts are coated using a wear-resistant oxide layer which meets the aesthetic requirement of most users.

What are The Types of Anodizing Processes?

Manufacturers use three common types of anodizing processes, Type 1, Type 2, and Type 3. Each method differs due to the coating intensity.

  • Type 1

This anodizing process is a “lighter” alternative. It uses chromic acid as the electrolyte. During the electrochemical process, the positive particles from the aluminum part form microscopic grooves, which are oxidized to form an oxide layer. Aluminum parts made via this process have better corrosion and heat resistance.

  • Type 2

This is the most common method of anodizing aluminum parts. Instead of chromic acid, this process uses sulfuric acid, which is more potent and produces better positive aluminum particles than Type 1. The oxide layer becomes thicker; therefore, the parts have better paint retention properties.

The common color options for this process include blue, red, brown, purple, green, gold, black, and grey.

  • Type 3

Type 3 is the ideal one for hard coating and making heavy aluminum products. It uses a higher voltage and sulfuric acid.

How to Color Aluminum Parts Using Anodizing

The anodizing aluminum colors are very different from the ones used in powder coating or painting. The colors will depend on the grade, size, and finish tapes. Here's the process.

  • Cleaning and Etching

The anodizing process begins with cleaning the aluminum part with detergent and rinsing tanks. The part is then etched to give a matte, polished and shiny surface finish. The etching and brightening are done to remove any trace amounts of metal. The material removed depends on the size, shape, temperature, and solution pH.

  • Build the Film Layer

After cleaning, you need to build the oxide layer on the aluminum part. Depending on the coating intensity you want to achieve, you can use Type 1, 2, or 3 anodizing processes. Once the piece is suspended in the electrolyte, you need to keep in mind that the shape and size of pores depend on the metal alloy.

In addition, the depth of the pores will depend on the electric voltage, tank temperature, time in the tank, and solution concentration.

  • Adding the Color

Manufacturers add anodized aluminum colors in four ways, dip coloring, electrolytic coloring, interference, and integral coloring.

With dip coloring, the part is placed in a tank containing a dye. Once the dye is absorbed into the pores, the surface is boiled in de-ionized water to stop further reactions. Although there are many coloring variants, they are not UV resistant.

On the other hand, with electrolytic, the part is immersed in a solution containing metallic salts. These salts fill the pores to form a UV-resistant layer. However, the colors are limited to brown and black.

Interference coloring works by enlarging the pore structure. The metals are then deposited, which results in blue, green, and yellow to red colors. These colors form because of optical interference effects. Integral coloring combines coloring and anodizing by adding bronze and black shades.

  • Sealing Off

Once the aluminum part is completely dyed, the last step is sealing it off to preserve the color. This sealing process protects the part from absorbing undesired molecules.

How Do You Color Match With the Aluminum Parts

There are several possible colors for anodizing aluminum. For effective results, the product developer needs to understand the concept of color matching. Let’s take a look at some of the critical factors you should look out for when matching colors.

  • The Finish Type

To achieve the best aluminum reflective properties, the part of the film is essential. Use a sample with the same finish when color matching.

  • The Aluminum Grade

When anodizing aluminum parts, looks out for the grade. Each aluminum grade has a different color variant and shade, which could affect the color matching.

  • The Part’s Crystalline Structure

The crystalline structure affects the reflective properties of the aluminum part. Therefore, before you color match, check that the reflective angle is the correct one.

  • The Number of Dyes Used

The dyes affect the color variation. When product developers use more dyes, there’s an increase in color variation. During layering, this variation also differs.

Benefits of Anodizing Aluminum Parts

If you anodize your parts, here are some advantages.

  • Aesthetic Value

Anodized aluminum parts have a visually appealing look. This makes them popular with users because they are market-ready.

  • Corrosion Resistance

The oxide layer from the anodizing process protects the aluminum parts from corrosion. This makes them durable than other parts which have had powder coating or painting.

Summary

After manufacturing is done, it’s essential to have a quality surface finish. There are different anodizing processes that product developers can use. It’s also vital to choose the best anodizing aluminum colors according to the aluminum part. This makes it easier to color match and get the best end product.

Anodizing has benefits such as boosting the product's aesthetic value, enhancing the surface finish, and increasing durability. Therefore, it's an essential step in manufacturing aluminum parts for any industry.

A detailed Guide on PCB Fabrication Process

Hello friends, I hope you all are doing great. Today, I am going to share the 10th chapter in the PCB learning series. So far, we have studied the basics of PCB i.e. What is PCB? Main Types of PCB, techniques to mount components on PCB etc. Now, we are ready to have a look at the complete PCB Fabrication Process.

So, in today's tutorial, I am going to share a detailed guide on PCB Fabrication Process. We will discuss everything related to it i.e. How PCB boards are manufactured? Which material is used to fabricate printed circuit boards? etc. But before starting the Fabrication PRocess, we first have to understand a few terms/features. So, let's get started:

  • PCB of DVD player:

RoHS-compliant PCB

  • RoHS stands for Restriction of Hazardous Substances.
  • EU ban the use of lead under the legislation RoHS. So, in PCBs, lead can't be used.
  • RoHS-compliant PCB means that PCB is free from lead, Mercury and other heavy toxic metals.

PCB Lamination

  • Laminates are prepared, first controlling pressure and temperature for cloth or paper with a thermoset resin and then a final integral piece of uniform thickness is formed.
  • Its size can be up to 4×8 feet.
  • Desired thickness can be achieved by controlling cloth weaves, thickness and resin percentage.
  • Some important characteristics of the laminate are:
  1. strength of fire retardant
  2. dielectric constant(e) of the laminate
  3. the loss factor of laminate
  4. tensile and shear strength of the laminate
  5. the glass transmission temperature and
  6. the z-axis expansion coefficient.
Different dielectrics are used to obtain different insulating values depending on the requirement, which are:
  1. Polytetrafluoroethylene(Teflon)
  2. FR-1, FR-2, FR-3, FR-4, FR-5,and FR-6
  3. CEM-1, CEM-2, CEM-3, CEM-4, andCEM-5.

Here are a few of the factors affecting the laminate quality: 

  1. Size of the board.
  2. Increasing frequencies.
  3. Uneven distribution of fiberglass glass or other filler.
  4. Bubbles and thickness variation in resin.
  5. Variations in the dielectric constant.

Key Substrate parameters

  • The circuit board substrates are made up of dielectric composite materials.
  • The composites contain
  1. matrix(epoxy resin)
  2. reinforcement(glass fibers, paper etc.)
  3. filler (ceramics)
Reinforcement has two major classes of materials
  1. woven: these are cheaper but have a high dielectric constant that is not suitable for many applications.
  2. non-woven: these are expensive but suitable for RF and analog applications.

Key parameters of substrates are:

  1. thermomechanical(tensile and shear strength, glass transition temperature and thermal expansion)
  2. electrical(tracking resistance, dielectric constant, dielectric strength, breakdown voltage etc.)
  3. others(moisture absorption)
  • At a transition temperature, thermal expansion increases because the resin in the composite becomes soft. Below transition temperature, thermal expansion decreases and matches with copper and glass. Above transition temperature, a very high thermal expansion exerts mechanical overload on the board components.
  • Expositions to high temperatures and repeated soldering can be the reason for the failure of the plating, especially with thick boards.
  • Dielectric substrate constant depends upon the material used and the frequency(decreases with the increase in frequency). Signal propagation speed depends upon dielectric and phase distortion depends upon frequency. So flat dielectric constant vs characteristics frequency is important. The transmission line impedance is inversely proportional to the frequency therefore faster edges of signals reflect more than the lower edges of the signal.
  • At maximum voltage gradient, material suffers from breakdown is determined through dielectric breakdown voltage.
  • Tracking resistance means how the material resists high-voltage electrical discharges creeping over the surface of the board.
  • The amount of electromagnetic energy from the signals in the conductor, that is absorbed in the board material is called loss tangent. It is important for high frequencies. The cost of the board increases by choosing low-loss material(expensive) in high-frequency digital design.
  • When the material is exposed to high humidity or water, moisture absorption occurs. Both resin and reinforcement absorb water. Absorbed water can cause degradation of key parameters. It affects tracking resistance, dielectric parameters and dielectric constant. Absorbed water can cause cracks during heating and soldering.

Common Substrates

  • FR-2, FR-4, aluminum or insulated metal substrate( IMS) and flexible substrates(Kapton and parallax) are the commonly used materials as the substrate.
  • FR-1, FR-3, FR-5, FR-6, G-10, G-11, CEM-1, CEM-2, CEM-3, CEM-4, CEM-5, PTFE(Teflon), RF-35, alumina and polyimide are rarely used as a substrate.

Copper thickness

  • Copper thickness is the weight of copper per area. Its unit is ounce/square foot. (1 ounce/ square foot = 34 micrometers thickness).
  • A heavy copper layer means 3 ounces of copper per foot. It is used for high currents and to dissipate heat.
  • In FR-4 substrate 1oz copper/feet is the common thickness. Other options are also available.
  • Metal core boards use thicker copper(35 micrometers) for high-power devices.

PCB Circuit properties

  • Trace is made up of a flat but narrow copper foil and its resistance should be low. Its resistance is determined by its length, width, and thickness.
  • In multilayer PCB, one layer is made up of solid copper that is used for power and shielding return.
  • In microwave circuits, to attain consistent impedance stripping or microstrips of transmission lines are used.
  • HDI PCBs have vias or tracks with a diameter of under 152 × 10^6 m.

Safety measurements

Some safety measurements should be considered, i.e.
  1. flammability
  2. electrical tracking
  3. maximum operating temperature
  4. heat deflection

Old Technique for PCB Manufacturing

In the beginning, PCBs are designed on a clear mylar sheet having a photomask.

  • First, component pins/pads are laid out on the mylar and then traces are routed to connect with the pads.
  • Self-adhesive tape is used to make traces.
  • In mylar layout, pre-printed non-reproducing grids are used.
  • The final photomask is produced onto blank copper-clad boards having photoresist coating using a photolithographic technique.

Modern PCBs are produced by adopting the following steps.

PCB Fabrication Process

PCB manufacturing consists of many complex steps.

1. PCB Computer-aided Design(CAD):

  • CAD software are used to create the software image of the PCB design.
  • Commonly used PCB design software are Eagle, Altium Designer, OrCAD, KiCAD, Proteus etc.
  • Online CAD software are also available i.e. EasyEDA.
  • Once the design is finalized, the CAD software generates the Gerber files, which include detailed information about drill drawings, copper tracking layers, component notations apertures, components labeling etc.

2 Panelization:

  • Panelization is the process of adding a PCB design multiple times in a single PCB board.
  • If you want mass production, the best practice is to create a panel of your PCB design.
  • It reduces the cost and manufacturing time. (We will cover PCB panelization in our next chapter)

3 Copper Pattern Printing

  • On the copper foil layer, the PCB design generated from CAD software is printed using black ink, it acts as a protective mask for the copper under design traces/pads.
  • The remaining unwanted copper has no black ink and a process called etching removes it, as it's unprotected by the design mask.
  • Some other techniques used to create copper patterns:
  1. Silkscreen printing
  2. Photoengraving
  3. PCB milling
  4. Laser resist ablation
  5. Laser etching

4 Chemical etching:

  • The process of submerging the board into the ferric chloride solution is called chemical etching.
  • The function of etching is to remove copper from all the surfaces not protected by the resist.

5 Lamination:

  • Note the via, visible as a bright copper-colored band running between the top and bottom layers of the board.
[TEPImg9]
  • A stack of material is laminated in a press by applying heat and pressure for a certain time. Multi-layer PCBs have trace layers inside the board.

6 Drilling:

  • Drill bits are used to drill holes through PCB. It is made up of solid-coated tungsten carbide.
  • Holes can be made conductive by electroplating. These conductive holes are used to electrically connect the layers of PCBs.

7 plating and coating:

  • PCBs are plated with solder, tin or gold over nickel.

8 Solder Resist

  • Areas that do not need to be soldered are covered with solder resistance.

9 legend printing:

  • After the solder resists is done, a legend is printed on both sides of the PCB.
  • Silkscreen printing, liquid photo imaging, and inkjet printing are the three methods to print legends on PCB.

10 Bare board test:

  • Boards without components are tested for shorts and open. It is called the bare board test.

11 Assembly:

  • Assembly is the process of stuffing bare boards with electrical components.
  • After assembling, many tests are performed on the PCB. If it fails any test, means it needs rework.

12 Protection and Package

  • For protection, a conformal coating is done to avoid leakage of current and corrosion.
  • After all the protection checks, the final product is placed in a package.

Precautions

  1. Based on the required circuit, the PCB board dimensions are decided.
  2. Components and heat sinks are also positioned carefully.
  3. Decide the no of layers, ground and power planes as a power plane acts to encounter a ground plane, so shouldn't be together.
  4. Signal planes should be on external layers, especially if both AC and DC involve in the circuitry.
  5. High-frequency signals are routed in the internal layers between ground & power planes for attaining optimal EMI performance.
  6. Routes copper thickness, dielectric layer thickness and trace width are used to determine the line impedance. To route signals, normally three striplines are used named: microstrip, stripline and dual stripline.
  7. During components and vias placing on the PCB board, heat effects and geometry should be taken into account.
  8. If you are placing an order on a PCB manufacturing company, make sure you provide the final Gerber files.

How to order for PCB Manufacturing?

There are many online PCB Fabrication Houses available, offering PCB & PCBA manufacturing services. We are going to take the example of JLCPCB Fabrication House. Let's see How to place an online PCB Fabrication order on JLCPCB company.

  • First of all, open the official website of JLCPCB Fabrication House.
  • They have placed an online Quote Calculator, where you need to enter all your PCB requirements and it will give you the cost and time required to design it.
  • As you can see in the above figure, I have placed an order of 5 PCBs and the size of each PCB is 100x100mm, and I am getting a price of $2.
  • As you increase the quantity of PCB boards, the price per board reduces.
  • JLCPCB is a well-renowned PCB Manufacturing House and always provides quality work at a nominal price.

APPLICATIONS OF PCB:

  • In electronics: used in computers, home appliances, communication systems etc.
  • In industry: used in power, measuring and industrial equipment.
  • In medical: used in scanning, monitoring and surgery equipment.
  • In the automotive industry: used in navigation, media devices, control systems and proximity monitors.

ADVANTAGES OF PCBs:

  • Inexpensive/ cheaper.
  • High volume production.
  • Hold the components easily.
  • Highly reliable.
  • Automated soldering is possible.

So, that was all for today. In the next lecture, we will have a look at the PCB Panelization Process. I hope you have enjoyed today's lecture. Thanks for reading.

Why Flexible PCBs are expensive than other PCB types?

Hello friends, I hope you all are in good health. Today we will discuss a detailed overview of flexible PCB, its definition, types, advantages and manufacturing. We will also discuss why we need flexible PCB? We will discuss its uses and the reason for its high price, as it's expensive than other PCB types. I will try to deliver you my best knowledge about flexible PCB so you will clear understanding of flexible PCB. So let’s try to absorb everything about flexible PCB.

Flexible PCB overview

  • For irregular-shaped locations, it was difficult to place hard substrate PCBs. So, as necessity is the mother of invention similarly difficult locations and irregular surfaces are the mother of flexible PCB invention.
  • Before the 1950s flexible PCBs are not in common use but now they are used everywhere like in ATM keypads and smartwatches. Now let us have a look at the proper definition of FPCB.

Flexible PCB definition

  • The board that is made up of flexible plastic substrate usually polyester, polyimide or thin sheets of glass are called flexible printed circuit boards or FPCBs.
  • FPCBs have the ability to change their shape because they can twist and bend easily. In some devices, both rigid and flexible PCBs are incorporated to produce the desired functionality.
  • FPCB should not be so flexible that the board breaks down during folding or twisting.

Flexible PCB Pricing

Let's discuss the pricing of Flexible PCB and here I am going to take the example of an online PCB Fabrication House named PCBWay. It's a well-renowned PCB house and provides competitive rates with a quality product.

  • If you open the PCB Calculator of PCBWay and select Rigid-Flex PCB at the top, you will get a similar result:
  • Now, here I am going to select Flexible PCB and I am going to place an order of 10 PCBs, each of size 10x10mm.
  • In order to get the quote, we need to click on the Calculate Button and here's the price:
  • Now you can see the price for 10 pcs is $125 and it's quite expensive as compared to normal rigid PCB.
  • PCBWay provides the best rates for PCB manufacturing and if you check on any other site, you will get even higher rates.

Types of FPCB

  • FPCB has a few common types listed below:
    1. Single-sided FPCB
    2. Double-sided FPCB
    3. Multi-layer FFPCB
    4. Rigid-flex PCB( RFPCB)
    5. High Density interconnects FPCB.

Single-sided FPCB

  • It contains a conductive layer of copper on only one side of the PCB.
  • They are used in applications that need highly flexible circuits.

Double-sided FPCB:

  • It contains a copper layer on both sides of the PCB. The layers are made connected by vias or by plate through holes( PTH).
  • Double-sided FPCB is popular for its ease of manufacturing.

Multilayer FPCB:

  • In the multi-layer FPCBs, multi-layer PCBs are connected by vias or PTH.
  • It may contain more than 10 conductive layers of copper.
  • They are used in designs that require PCBs with high-density connectors.
  • Using more layers in flexible PCB design adds to the cost of FPCB.

Rigid-flex printed circuit board:

  • In RFPCB, flexible layers are integrated with the rigid layers and PTH technology is used to assemble circuit boards.
  • Small Interconnect areas are created by using both rigid and flexible layers so the chances of failure of PCB are reduced in an application.

High-Density flexible FPCB:

  • HDI are flexible circuit boards having microvias and precise features.
  • They are used to provide more technical solutions interesting of layout, design and construction.
  • HDI are known for their improved usage of ICs, greater reliability and high electrical performance.

Materials used in FPCB

  • We use flexible materials for both substrate and adhesive.
  • The substrate is basically made up of polyimide(PI) film. The PI film does not soften on heating but remains flexible.
  • Normally used PI film does not show the best resistance against humidity and tears but upgraded PI can overcome this problem.
  • To attach layers adhesives are used. This adhesive should also be flexible but it is difficult to attain so now PI without adhesives are used that attach copper layers without any adhesive.
  • Now coverlay film created with PI is used instead of solder mask. To make areas hard staffers are used instead of solder masks.

Manufacturing Process of FPCB

The manufacturing process for FPCB is procedural and structural. that's the main reason for its high cost. The manufacturing process of Flexible PCB is too lengthy, complex and needs a special environment, which makes it too expensive to design. Let us try to understand three major steps involved in the manufacturing of FPCB.

Step 1: Build up flexible PCB

The material used as a substrate is polyimide and in this step, the main focus is to save the base material because it is expensive than FR- 4. So to avoid wastage of polyimide circuits are placed close to each other. It includes the following steps:

  • CAD designing: first of all design is prepared using CAD software.
  • Drilling: holes are drilled and the size of holes is tried to make small.
  • Looping: adding a slight amount of extra material for servicing circuit assembly.
  • Sizing conductor: use the thinnest amount of copper.
  • Etching: To compensate losses especially line width losses etching is done.
  • Routing: the conductor is held perpendicular to the bend and fold. Folding and bending are improved by reducing stress and by helping the conductor perpendicular stress is reduced.
  • Ground planes: creating ground areas will improve the flexibility of the circuit by reducing the weight of the circuit board.

Step 2: FPCB fabrication process:

Depending on the design and application the diameter of the hole in FPCB may vary.
  • Size of the hole: small holes are best for flexible PCBs. Small size holes are difficult to drill. So the no of holes and size of holes determines as the cost control factors.
  • Filleting: filleting is necessary for joining pads and land termination points. By filleting area is multiplied and stress is reduced so flexibility improves.
  • PTH: Nowadays, copper is used for preparing vias and plated through holes.

Step 3: focus on physical constraints/ testing:

  • Layers and coating problems are dealt with in this step. So the testing of these cover layers is necessary.
  • Adhesive-backed films: these films are used for overcoating or at the areas where the adhesive is missing.
  • Screen printable liquid overcoats: these are used with polymer films that are thick.
  • Photo imaginable liquid and film polymer: It is the modern method used for overcoating because it avoids circuiting traces by acting as a solder mask. It avoids external and internal damages to the board.
  • Overlay: After testing, FPCBs are laminated which is called an overlay. For best quality overlay, the budget of flexible PCB increases.
  • Packing: FPCBs are packed and delivery is made.

Advantages or benefits of flexible PCB

  1. It can be twisted, bent, folded, and shaped in various dimensions, unlike rigid PCB.
  2. It overcomes other technologies like wire harnesses, rigid PCBs, and connectors.
  3. It can be arranged in various stacked configurations.
  4. Very easy to install.
  5. For high flexible applications, single-sided FPCBs are used. As the spaces are generated to make them flexible so they are light in weight and small in size.
  6. FPCBs are more durable than PCBs and rigid PCBs.
  7. Using FPCBs the capability of the product is enhanced.

Disadvantages or drawbacks of FPCBs

  1. Their cost is high than other PCBs because of the poor utilization of panels.
  2. They can be damaged easily because of their flexibility and poor handling.
  3. A complex assembly process is used in their manufacturing.
  4. In case of any fault or problem, they can not be repaired easily. High-quality machinery is required to repair them and the repairing price is also very high.
  5. For the manufacturing of FPCB highly professional designers with a lot of time are required.

FPCB Market Costs

  • The market for the flexible printed circuit board is raising day by day.
  • It was $ 200 million in the past and crossed $800 million till 2020.
  • High demand is expected in the future.

Applications of flexible printed circuit boards

  • FPCBs have diverse applications almost in every industry. They are designed in such a way to meet all the requirements of any kind of flexibility.
  • Flexible printed circuit boards are used in both static and dynamic applications based on the requirement.
  • Material use varies in static and dynamic applications. So before the manufacturing, their type and requirement should be confirmed.

Static application:

  • These applications are also known as flex-to-fit or flex-to-install applications.
  • Only a small amount of flexibility is produced in boards for these applications.
  • Inexpensive electrodeposited (ED) copper is used to make minimal flexible boards for static applications.

Dynamic applications:

  • For dynamic applications, the flexibility of built-in boards is set as high as possible.
  • Rolled Annealed (RA) copper is used for making highly flexible printed circuit boards for dynamic industrial applications.

Diverse FPCB industrial applications:

  • The applications of flexible printed circuit boards in different industries are listed below
  • Electronics: flexible PCBs are used in laptops, cameras, calculators, printer heads, flip cell phones, computers keyboards...etc. Moving the print head of printers and plotters uses flexible PCBs to draw prints. Now flexible solar cells are made which can bend easily. Flexible wristwatches are also becoming popular in young generations.
  • Manufacturing: flexible PCBs are also used in robotic arms, sensors equipment, processing machines, bar code equipment, and human-machine interface equipment In the manufacturing industry.
  • Automotive: in the automotive industry, flexible printed circuit boards are used in airbag systems, anti-lock brakes, Global positioning systems( GPS), in engine controls.
  • Medical: in the medical industry, flexible printed circuit boards are used 8n pacemakers, hearing aid devices, heart monitoring devices, and exercise monitors.
  • Miscellaneous: flexible PCBs are also used in resistors, satellites, capacitors, Tower lights, LCD fabrication, light and motion systems.

Development prospects of flexible PCBs

Flexible printed circuit boards should have to be improved in the following aspects:

  • Thickness:

In the future flexible printed circuit board should be thinner and more flexible. They should have the flexibility of complete 360°.

  • Folding resistance

Improved and developed substrates should be used to overcome the folding resistance.

  • Price

At this time flexible printed circuit boards are too much costly. In the future, their price should be reduced to increase their market growth rate.

  • Process level

It is very difficult to make flexible PCBs because they required highly qualified personals, high machinery, and a lot of time. In the future, their process level should be upgraded and minimum line width and minimum aperture must meet higher requirements.

Parameters on which the cost of FPCB depends

Many factors affect the cost of the flexible printed circuit board. But I am here to categorize these parameters into these cost drivers.

  • Physical size:

The size of the flexible PCB is measured in a square inch and the price is calculated as price/ square inch.

So for large flexible printed circuit boards having the vast size, the price will be high than the smaller one.

  • Circuit construction:

When the no of layers increases the price of flexible PCB increases. So double-layer FPCB has high price than the single-layer FPCB and multi-layer FPCB must be high in price than single and double layer FPCB. Price also depends upon the material used in the construction. Price also depends upon the no of pads, for more pads used in flexible PCB price will be high.

  • Volume:

Price also depends upon the volume of flexible PCB. For greater volume price will be high.

  • Finishing

Finishing determines the shelf life of the flexible printed circuit board. With good quality, the finishing price is affected.

  • No. Of the holes and size of the holes

It is difficult to make small holes, and for small holes, which are normally drilled in the flexible printed circuit boards, the price will be high than the big holes.

For more holes price will also be high.

  • Custom or unique specification

When the custom specification is required that will add to the price of the flexible printed circuit board. Examples of custom specifications are contoured edges, side plating, and solder mask clearance.

Conclusion

In the future, flexible printed circuit boards will play a major role in security and entertainment dynamics.

The demand for flexible printed circuit boards is not high till 2016 but now their demand is increasing day by day. In future preference will be given to the flexible products in the market.

In short, the future belongs to flexible products.

ESP32 MQTT

Hello readers, today we will learn about the messaging protocol supported by ESP32(called MQTT protocol), which is used for IoT applications. The communication protocol to be used for data transmission and connectivity in web-enabled devices depends upon the type of IoT application.

The Internet of Things (IoT) is a network of interconnected computing devices like digital machines, automobiles with inbuilt sensors, having unique identifiers and the ability to communicate data over a network without the need for human intervention.

Before implementation, let's first have a look at what is MQTT Protocol?
Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

What is MQTT?

  • MQTT stands for Message Queuing Telemetry Protocol and is a messaging or communication protocol used for IoT applications.
  • In MQTT protocol, a publisher sends a message to the broker with a specific topic tag, and the broker forwards this message to all the Subscribers of that mentioned topic.
  • So, in order to understand MQTT Protocol, we need to discuss these 4 terms:
    1. MQTT Topic
    2. MQTT Publisher
    3. MQTT Broker
    4. MQTT Subscriber
Note:
  • The OASIS technical committee is the in-charge of MQTT specifications. The OASIS or the Organization for the Advancement of Structured Information Standards is a non-profit organization dedicated to the development, convergence, and implementation of electronic business standards.

Fig 1: ESP32 MQTT Protocol

MQTT Topic

  • In MQTT protocol, a Topic is simply a UTF-8 string i.e. "Arduino", "ESP32", "Beginner Tutorials" etc.
  • MQTT Clients can subscribe to these Topics and are called Subscribers to that Topic.
  • MQTT Broker sends messages to the Clients based on their Topic subscription.
  • A topic may have multiple levels, separated by a forward slash.

MQTT Publisher

  • MQTT Publisher(also called MQTT client), as the name suggests, publishes the message on a specific topic and sends it to the broker.
  • In simple words, a publisher sends a message(normally a string) to the MQTT Broker, and this message also contains the Topic information.

MQTT Broker

  • MQTT Broker(also called MQTT server) acts as a coordinator between the subscriber and the publisher in order to create communication.
  • The broker's job description is as follows:
    • Receiving messages from the publisher
    • Filtering received messages based on assigned Topics from the publisher.
    • Determining the interested subscriber in each message based on the assigned Topic
    • Finally forwarding the messages to subscribers

MQTT Subscriber

  • MQTT Subscriber(also called MQTT client), subscribes to the MQTT Topics and receives the messages from the MQTT broker, sent by the Publisher.

How does MQTT Work

This messaging protocol follows the Publish and Subscribe model. The Publisher and Subscribers of the message, communicate via Topics and are separated from one another. The broker is in charge of their communication. The broker's job is to filter all incoming messages and distribute them to the subscribers in the most efficient way possible. The broker pushes the information to the client whenever something new becomes available, so the client doesn't have to pull the information.

Because there are so many ready-to-use brokers and client applications, getting started with MQTT is a breeze.

Fig 2: MQTT Publish and Subscribe architecture

MQTT Features

Light Weight

It is a lightweight and versatile IoT communication and data transfer protocol aimed at IoT developers who want to strike a compromise between flexibility and network resources.

All the MQTT messages have a small footprint which adds a lightweight feature to this protocol.

In MQTT every message has:

  1. 2-byte header (fixed)
  2. A 256 MB message payload
  3. A 2-byte variable header (optional)

Security

MQTT protocol implementation will allow you to use your User name and password for security purposes. If you added the authentication feature while creating the MQTT server then stranger clients can’t communicate to your MQTT server.

Bidirectional communication

There is no direct link between clients in MQTT.

A broker connects the subscriber and the publisher in this messaging protocol. As a result, the subscriber and publisher can converse about any issue that the broker handles.

Eliminate polling

Polling is a procedure in which the controlling devices wait for input from an external device to determine whether the device is ready to broadcast data. MQTT protocol follows instantaneous push-based delivery. So there is no need to continuously check or poll before sending data which results in reduced network traffic.

Storage and forwarding

MQTT supports the storage and forwarding of persistent messages on the broker. Clients can ask for the broker to keep messages after they've been published. When this feature is used, any persisted message will be broadcast to a client who has subscribed to a topic. The most recent persistent message is the only one that gets saved. Unlike typical messaging queues, however, the MQTT broker prevents these persisted messages from being backed up inside the server.

Decouple and scale

It enables changes in communication patterns and functionality without causing a system-wide ripple effect.

Simplifies communication

As we have already discussed that MQTT follows Subscriber and Publisher architecture where the broker acts as an interface between the clients. So there is no need of computer to computer interface hence providing simplified communication.

Dynamic targeting

  • It also supports authentication, publishing, subscribing, keep-alive pings.
  • It runs on top of Internet protocol and TCP.

Quality of service

Quality of service is a kind of indicator which ensures that messages are exchanged between the sender and the receiver. There are three levels of QoS:

  1. just once - this level is not reliable but is the fastest one
  2. at least once - this level is the default mode
just once - this level is the most reliable, but slowest

MQTT Applications

MQTT protocol is mostly used in IoT(internet of things) applications for data transmission. The data can be read from some sensors or some temperature value.

Fig 3: MQTT Applications

Some other applications where you can use it are :

  • Security and surveillance
  • Industries & energy
  • Logistics
  • Medical & healthcare

How to Publish a message using ESP32 MQTT?

  • The MQTT protocol is another functionality supported by the ESP32 module. To implement MQTT, we're utilizing the Arduino IDE.
  • If you're not sure where to begin coding with the ESP32, check out our prior tutorial, Introduction to the ESP32 Microcontroller Series.

Code Description

  • Global Declarations

Adding libraries will be the initial stage.

  • To use ESP32 MQTT to send a message, you'll need two libraries.
#include <WiFi.h> #include <PubSubClient.h>
  • PubSubClient library is not available in ESP32’s library list. You need to download the library first and add the library into Arduino IDE.

Fig 4: Adding library to Arduino IDE.

  • Click on Add. Zip Library.
  • Browse for the downloaded library file and add.
  • PubSubClient library and Wi-Fi library
  • We covered Wi-Fi in detail in our previous tutorial, ESP32 web server.
  • PubSubClient is a client library that may be used with MQTT applications.
  • Add your SSID and Password to create a wi-fi connection. Follow our previous tutorial, ESP32 web server, to learn more about ESP32 Wi-Fi.
const char* ssid = "public"; //add your SSID const char* password = "ESP32@123"; // add your password
  • Add the details about MQTT broker
const char* mqttServer = "m11.cloudmqtt.com"; const int mqttPort = 1883; //12948; const char* mqttUser = "public"; const char* mqttPassword = "ESP32@123";

Arduino setup() Function

  • Initialize the serial monitor.
  • Initialize the Wi-Fi. (follow the previous tutorial for more details about (ESP32 Wi-Fi)
Serial.begin(115200); WiFi.begin(ssid, password);   while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); }
  • Print Wi-Fi status on serial monitor
Serial.println("Connected to the Wi-Fi network");
  • Define the MQTT server's address and port address.
  • To do so, we use the PubSubClient object's setServer function.
  • The address and port, both defined early in global variables declaration, will be passed to this procedure as the first and second arguments, respectively.
  • setCallback method to define a handling function.
  • When a MQTT message is received on a subscribed topic, this handling function is called. This function's code will be saved for later.
client.setServer(mqttServer, mqttPort); while (!client.connected()) { Serial.println("Connecting to MQTT..."); if (client.connect("ESP32Client", mqttUser, mqttPassword )) { Serial.println("connected to MQTT"); } else { Serial.print("failed to connect "); Serial.print(client.state()); delay(2000); } }
  • Publish a topic
client.publish("esp/test", "ESP32");
  • Subscribe for the topic you want to.
client.subscribe("esp/test");
Finally, we'll subscribe to the topic we're interested in. Other clients' communications will be published on that topic, and we will receive them this way. For that purpose, we use the subscribe method, which takes the name of the topic we want to subscribe to as an argument.

Arduino loop() Function

  • The next task will be to connect with the MQTT server which will happen in the main loop
  • Here, the device will keep trying to connect with the server unless it establishes a connection.
  • In order for the client to process incoming messages and maintain the connection to the MQTT server, the function should be invoked on a regular basis.

MQTT Testing

For testing purposes, we will use MQTT_lens which is a Google Chrome application to establish a connection with the broker.

  • Here are some screenshots of the MQTT lens broker:
  • Create a connection after adding the following details:
  • Connection, Hostname, Port etc.

Fig: MQTT_lens broker

 

This concludes today’s tutorial, hope you find it helpful.

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