Silicon ChipTeach-In 2024 – Learn electronics with the ESP32 - July 2024 SILICON CHIP
  1. Contents
  2. Subscriptions
  3. Back Issues
  4. Publisher's Letter: We’ve come a long way
  5. Feature: Techno Talk by Max the Magnificent
  6. Feature: The Fox Report by Barry Fox
  7. Feature: Net Work by Alan Winstanley
  8. Project: Pi Pico-based Thermal Camera by Kenneth Horton
  9. Project: Dynamic NFC Tag by Tim Blythman
  10. Project: Reciprocal Frequency Counter by Charles Kosina
  11. Feature: Circuit Surgery by Ian Bell
  12. Feature: Audio Out by Jake Rothman
  13. Feature: Max’s Cool Beans by Max the Magnificent
  14. Feature: Teach-In 2024 – Learn electronics with the ESP32 by Mike Tooley
  15. PartShop
  16. Market Centre
  17. Back Issues

This is only a preview of the July 2024 issue of Practical Electronics.

You can view 0 of the 72 pages in the full issue.

Articles in this series:
  • (November 2020)
  • Techno Talk (December 2020)
  • Techno Talk (January 2021)
  • Techno Talk (February 2021)
  • Techno Talk (March 2021)
  • Techno Talk (April 2021)
  • Techno Talk (May 2021)
  • Techno Talk (June 2021)
  • Techno Talk (July 2021)
  • Techno Talk (August 2021)
  • Techno Talk (September 2021)
  • Techno Talk (October 2021)
  • Techno Talk (November 2021)
  • Techno Talk (December 2021)
  • Communing with nature (January 2022)
  • Should we be worried? (February 2022)
  • How resilient is your lifeline? (March 2022)
  • Go eco, get ethical! (April 2022)
  • From nano to bio (May 2022)
  • Positivity follows the gloom (June 2022)
  • Mixed menu (July 2022)
  • Time for a total rethink? (August 2022)
  • What’s in a name? (September 2022)
  • Forget leaves on the line! (October 2022)
  • Giant Boost for Batteries (December 2022)
  • Raudive Voices Revisited (January 2023)
  • A thousand words (February 2023)
  • It’s handover time (March 2023)
  • AI, Robots, Horticulture and Agriculture (April 2023)
  • Prophecy can be perplexing (May 2023)
  • Technology comes in different shapes and sizes (June 2023)
  • AI and robots – what could possibly go wrong? (July 2023)
  • How long until we’re all out of work? (August 2023)
  • We both have truths, are mine the same as yours? (September 2023)
  • Holy Spheres, Batman! (October 2023)
  • Where’s my pneumatic car? (November 2023)
  • Good grief! (December 2023)
  • Cheeky chiplets (January 2024)
  • Cheeky chiplets (February 2024)
  • The Wibbly-Wobbly World of Quantum (March 2024)
  • Techno Talk - Wait! What? Really? (April 2024)
  • Techno Talk - One step closer to a dystopian abyss? (May 2024)
  • Techno Talk - Program that! (June 2024)
  • Techno Talk (July 2024)
  • Techno Talk - That makes so much sense! (August 2024)
  • Techno Talk - I don’t want to be a Norbert... (September 2024)
  • Techno Talk - Sticking the landing (October 2024)
  • Techno Talk (November 2024)
  • Techno Talk (December 2024)
  • Techno Talk (January 2025)
  • Techno Talk (February 2025)
  • Techno Talk (March 2025)
  • Techno Talk (April 2025)
  • Techno Talk (May 2025)
  • Techno Talk (June 2025)
Articles in this series:
  • The Fox Report (July 2024)
  • The Fox Report (September 2024)
  • The Fox Report (October 2024)
  • The Fox Report (November 2024)
  • The Fox Report (December 2024)
  • The Fox Report (January 2025)
  • The Fox Report (February 2025)
  • The Fox Report (March 2025)
  • The Fox Report (April 2025)
  • The Fox Report (May 2025)
Articles in this series:
  • Win a Microchip Explorer 8 Development Kit (April 2024)
  • Net Work (May 2024)
  • Net Work (June 2024)
  • Net Work (July 2024)
  • Net Work (August 2024)
  • Net Work (September 2024)
  • Net Work (October 2024)
  • Net Work (November 2024)
  • Net Work (December 2024)
  • Net Work (January 2025)
  • Net Work (February 2025)
  • Net Work (March 2025)
  • Net Work (April 2025)
Articles in this series:
  • Circuit Surgery (April 2024)
  • STEWART OF READING (April 2024)
  • Circuit Surgery (May 2024)
  • Circuit Surgery (June 2024)
  • Circuit Surgery (July 2024)
  • Circuit Surgery (August 2024)
  • Circuit Surgery (September 2024)
  • Circuit Surgery (October 2024)
  • Circuit Surgery (November 2024)
  • Circuit Surgery (December 2024)
  • Circuit Surgery (January 2025)
  • Circuit Surgery (February 2025)
  • Circuit Surgery (March 2025)
  • Circuit Surgery (April 2025)
  • Circuit Surgery (May 2025)
  • Circuit Surgery (June 2025)
Articles in this series:
  • Audio Out (January 2024)
  • Audio Out (February 2024)
  • AUDIO OUT (April 2024)
  • Audio Out (May 2024)
  • Audio Out (June 2024)
  • Audio Out (July 2024)
  • Audio Out (August 2024)
  • Audio Out (September 2024)
  • Audio Out (October 2024)
  • Audio Out (March 2025)
  • Audio Out (April 2025)
  • Audio Out (May 2025)
  • Audio Out (June 2025)
Articles in this series:
  • Max’s Cool Beans (April 2024)
  • Max’s Cool Beans (May 2024)
  • Max’s Cool Beans (June 2024)
  • Max’s Cool Beans (July 2024)
  • Max’s Cool Beans (August 2024)
  • Max’s Cool Beans (September 2024)
  • Max’s Cool Beans (October 2024)
  • Max’s Cool Beans (November 2024)
  • Max’s Cool Beans (December 2024)
Articles in this series:
  • Teach-In 2024 (April 2024)
  • Teach-In 2024 (May 2024)
  • Teach-In 2024 – Learn electronics with the ESP32 (June 2024)
  • Teach-In 2024 – Learn electronics with the ESP32 (July 2024)
  • Teach-In 2024 – Learn electronics with the ESP32 (August 2024)
  • Teach-In 2024 – Learn electronics with the ESP32 (September 2024)
  • Teach-In 2024 – Learn electronics with the ESP32 (October 2024)
  • Teach-In 2024 – Learn electronics with the ESP32 (November 2024)
Teach-In 2024 Learn electronics with the ESP32 by Mike Tooley Part 5 – Sensing the environment I n the previous part of our Teach-In series, we introduced seven-segment and matrix LED displays. We also introduced the SPI interface as a means of interfacing a wide variety of peripheral devices. Coding Workshop showed you how to generate and use random numbers and our Teachin Project featured the design, construction and coding of a simple dice roller using a low-cost motion sensor as a trigger. This month, we will introduce two more interface standards that simplify communication between the ESP32 and external hardware. We begin by introducing a range of low-cost temperature and humidity sensors that can be used in projects that need to sense conditions in the surrounding environment. Coding Workshop looks at maths operators and functions and our Practical Project shows how easy it is to add an LCD display to your designs. The learning objectives for the fifth part of our series are know how to use: n 1-wire and I2C interfaces to connect external hardware n Temperature, humidity and other environmental sensors n Low-cost I2C LCD displays. About Teach-In Our latest Teach-In series is about using the popular ESP32 module as a basis for learning electronics and coding. We will be making no assumptions about your coding ability or your previous experience of electronics. If you know one but not the other, you have come to the right place. On the other hand, if you happen to be a complete newbie there’s no need to worry because the series will take a progressive hands-on approach. There will be plenty of time to build up your knowledge and plenty of opportunity to test things out along the way. We’ve not included too much basic theory because this can be easily found elsewhere, including several of our previous Teach-In series, see: https://bit.ly/pe-ti https://bit.ly/pe-ti-bundle Earch month, there’ll be projects and challenges to help you check and develop your understanding of the topics covered. Unmounted DHT22 (and DHT11) sensors) are supplied in a 4-pin package. They are also available as small, printed circuit modules with a few additional components that enable them to be used in stand-alone applications where only three connections are required to a host microcontroller: positive supply, data and ground (negative supply). The DHT devices use the 1-wire bus for communication between the sensor and a microcontroller. Sensed values of temperature and humidity are sent as serial data using the single wire connection. The sensor remains in a standby (low-power) mode until the host controller generates a start signal comprising a logic 0 (LOW) for at least 0.5ms, followed by a logic 1 (HIGH). When this signal is received, the sensor enters operational mode and responds with a serial stream comprising five bytes (40 bits) of data. This data consists of two bytes of RH data (high byte followed by low byte), two bytes of temperature data (high byte followed by low byte), and a checksum used to verify the data. A typical example of the serial data for a DHT22 sensor is shown in Table 5.1. Fig.5.1. A wide variety of low-cost sensors are available for use with the ESP32. They include sensors for temperature, humidity, barometric pressure, and UV as well as the The checksum is found by adding popular DHT11 and DHT22 types (centre). the preceding four bytes of data. So, in The DHT22 temperature and humidity sensor A variety of temperature and humidity sensors have become available for use in a wide range of situations where there is a need to sense, monitor and control the environment. Typical applications include heating, ventilation and air-conditioning (HVAC), dehumidifiers and humidity regulators, weather stations and data loggers, and vehicle environmental control. We will start this part of Teach-In by introducing some popular temperature and humidity sensors, namely: the DHT11 (RHT01) and DHT22 (RHT02 or AM2302). 58 Practical Electronics | July | 2024 Table 5.1 Data format for a DHT22 sensor Item RH data (16 bits) Temperature data (16 bits) Checksum (8 bits) Binary data 00000010 11101000 00000001 01101111 01011010 Decimal equiv 744 367 Value indicated 74.4% 36.7°C Table 5.2 Data format for a DHT11 sensor Item RH data (16 bits) Temperature data (16 bits) Checksum (8 bits) Binary data 00000000 01011001 00000000 00011001 01110010 Decimal (×1) 89 25 Value indicated 89% 25°C Check it out! The 1-wire interface to HSPI pin no. a DHT22 (or similar) sensor is delightfully 14 simple and requires 13 just three connections, as shown in Fig.5.2. 12 Asynchronous data is transferred via the ESP32’s in-built universal asynchronous receiver transmitter (UART). This is often labelled ‘RX2’ on ESP32 development boards. Representative breadboard and wiring layouts are shown in Fig.5.3 and Fig.5.4. this case, the checksum is determined as follows: 0000 0010 (RH data high byte) + 1110 1000 (RH data low byte) + 0000 0001 (temp data high byte) + 0110 1111 (temp data low byte) ______________ 0101 1010 (checksum) ______________ Note that when the leading bit of the temperature data is set (ie, 1) this signifies a temperature below zero (ie, a negative temperature value). Note also that the data format used for the less accurate DHT11 sensor uses only the two low data bytes (the high bytes are all zero). The value of the low byte is decoded directly to produce integer values – see Table 5.2 for an example. DHT11 and DHT22 (and equivalent) temperature and humidity sensors are laboratory calibrated and calibration data is stored in one-time programmable (OTP) memory. These sensors can be reliably used at distances of up to 20m from the host microcontroller. For an overview of DHT11 and DHT22 specifications see Table 5.3. Fig.5.3. Breadboard layout for testing a DHT22 temperature and humidity sensor. Gotcha! Take care when RH measurements are made in environments where airborne contaminants and gases are present. Fig.5.2. The minimal interconnection required to interface a DHT22 temperature and humidity sensor to an ESP32 development board (serial data is transferred using the ESP32’s UART). Practical Electronics | July | 2024 Fig.5.4. Breadboard wiring for the DHT22. Table 5.3 DHT11 and DHT22 specifications Characteristic DHT11 DHT22 Characteristic DHT11 DHT22 Temperature range 0 to +50°C -40 to +80°C Humidity range 20 to 90% RH 0 to 100% RH Accuracy (temperature) Better than ±2°C Better than ±0.5°C Accuracy (humidity) Better than ±5% RH Better than ±1% RH Sensing period 1s (minimum) 2s (average) Supply voltage 3 to 5.5V DC 3.3 to 6V DC Supply current 2.5mA max. (150µA standby) 1.5mA max. (50µA standby) 59 Listing 5.1 Testing the DHT22 temperature and humidity sensor with an ESP32 /* ESP32 test with DHT22 sensor */ // Include the library file #include <dhtnew.h> DHTNEW mySensor(16); #include <dhtnew.h> // Library file // RX2 input // Define GPIO pins const int HeaterRelay = 22; const int FanRelay = 23; int LowThreshold = 15; int HighThreshold = 25; void setup() { Serial.begin(115200); // Print headings Serial.print(“Temp.(C)”); Serial.println(“Humidity(%)”); } DHTNEW mySensor(16); // UART RXD input void loop() { // Read the sensor and then display the data mySensor.read(); Serial.print(mySensor.getTemperature(), 1); Serial.print(“\t”); Serial.println(mySensor.getHumidity(), 1); delay(5000); // Wait two seconds } Gotcha! There’s some variation in pin connections and marking on temperature and humidity modules. Some boards seem to have no pin markings at all. An inadvertent reverse supply connection can quickly destroy the sensor’s 8-bit processor so it’s important to check pin connections and wiring before applying power! The code for testing the DHT22 is shown in Listing 5.1. Before executing the code you will need to use the IDE’s Library Manager to locate and download the required library, dhtnew.h. We’ve included this library in our code using the following line: #include <dhtnew.h> The code in Listing 5.1 reads temperature and humidity data from the DHT22 module every four seconds. The data is then sent and displayed via the Serial Monitor. Fig.5.5 shows some typical data from the Serial Monitor. A thermostatic controller Now let’s look at a practical application for a DHT sensor in the form of a simple greenhouse controller. Fig.5.5. Typical Serial Monitor data values obtained from Listing 5.1. 60 Listing 5.2 Sample code for the thermostatic controller /* ESP32 environmental controller using a DHT11 temperature and humidity sensor */ void setup() { Serial.begin(115200); // Set relay pins as outputs pinMode(HeaterRelay, OUTPUT); pinMode(FanRelay, OUTPUT); // Initialise relays in off condition digitalWrite(HeaterRelay, HIGH); digitalWrite(FanRelay, HIGH); } void loop() { // First read the sensor mySensor.read(); Serial.print(“Temperature: “); Serial.print(mySensor.getTemperature(), 1); Serial.print(“ deg.C\t”); Serial.print(“Humidity: “); Serial.print(mySensor.getHumidity(), 1); Serial.print(“ %\t”); // Then display the returned data if (mySensor.getTemperature() < LowThreshold) { digitalWrite(HeaterRelay, LOW); Serial.print(“Heat ON “); } else { digitalWrite(HeaterRelay, HIGH); Serial.print(“Heat OFF “); } if (mySensor.getTemperature() > HighThreshold) { digitalWrite(FanRelay, LOW); Serial.println(“Fan ON “); } else { digitalWrite(FanRelay, HIGH); Serial.println(“Fan OFF “); } delay(1000); // Wait for 1 second } Fig.5.6. Circuit for the ESP32 thermostatic controller. Since we don’t need a high order of accuracy and wide temperature range, we will make use of a cheaper DHT11 sensor (see Table 5.3 for a comparison of these two sensors). We will use the ESP32 to control two relays; one will operate a heater when the ambient temperature falls below a pre-determined level (the low threshold) and the other will operate a fan when the temperature exceeds a second predetermined level (the high Practical Electronics | July | 2024 that we’ve defined the low threshold as 15°C and the high threshold as 25°C (a target temperature range of 10°C). These values can of course be changed to suit individual requirements. Fig.5.7. Breadboard layout for the ESP32 thermostatic controller. threshold). The aim of the thermostatic controller is to maintain the environment’s ambient temperature within a range bounded by the two thresholds. The circuit of the ESP32 thermostatic controller is shown in Fig.5.6. The relay modules are interfaced to the ESP32 using GPIO pins initialised for digital operation (see TeachIn Part 2 for further information). The DHT11 sensor module is connected, as before, using the 1-wire interface. A representative breadboard layout is shown in Fig.5.7 and a practical wiring arrangement in Fig.5.8. Note that, to simplify interconnection and aid prototype manufacture, we’ve used a popular low-cost ESP32 expansion board in this arrangement. Expansion boards are relatively inexpensive and can be particularly useful as an interim stage between breadboard and final PCB layout. Sample code for the thermostatic controller is shown in Listing 5.2. You should have already located and installed the required library file (see earlier). For test purposes, we’ve included status messages for the Serial Monitor. These, together with the LED indicators on the two relay modules, will allow you to confirm operation of the controller. Notice Fig.5.8. Wiring for the thermostatic controller based on a popular ESP32 expansion board. Practical Electronics | July | 2024 The I2C bus In Teach-In Part 4 we showed how the serial peripheral interface bus (SPI) allows you to connect a wide variety of external devices to an ESP32. In addition to SPI, the ESP32 supports another useful method of connecting to the outside world using the ‘Inter-Integrated Circuit’ interface (abbreviated variously to IIC, I2C, I2C (spoken ‘I-squared-C’). This is a good point to introduce I2C as we will shortly be using it to attach a low-cost LCD panel to display your temperature and humidity data. I2C is a simple bus system in which bidirectional data appears on a single line (SDA) and a clock signal is sent on a second bus line (SCL). Contrast this with SPI, which offers a point-to-point connection where data is passed in and out on separate lines (MOSI and MISO). SPI is faster and generally easier to use than I2C but there are many situations in which I2C is preferred simply because the interface is built into the chip that you need to use. I2C was the brainchild of Philips, but several of its competitors (including Motorola/Freescale, NEC, Siemens, STM and Texas Instruments) have developed their own I2C compatible products. In addition, Intel’s SMBus provides a stricter definition of I2C intended to improve the interoperability of I2C devices from different manufacturers. A representative SPI bus arrangement is illustrated in Fig.5.9. Note that this system comprises two bus masters and three bus slaves. A microcontroller (eg, an ESP32) takes the role of master, while devices such as sensors and displays assume the role of slave. Since the data line (SDA) is shared between multiple devices, I2C needs a system of addressing to identify the device that it needs to communicate with. Communication is initiated by means of a unique start sequence which involves pulling the data line (SDA) low while the clock line (SCL) is high. This can be achieved by using very simple bus interface logic where each of the bus lines are normally pulled high and driven low when activated by a device connected to the bus (see Fig.5.10). Following the start sequence, transmitted data is only allowed to change when the clock is in its low state. In its basic form, and by virtue of the seven bits available for addressing, the I2C protocol caters for a total of 127 devices. In addition to the seven bits used for addressing, the first byte of an I2C transfer generated by a ‘master’ includes a bit that indicates the Fig.5.9. A representative I2C bus with two bus masters and three slaves present. 61 Table 5.4 A selection of common I2C devices Device Application Manufacturer I2C address ADS1015 4-channel 12-bit ADC Texas Instruments 0x2c to 0x2f ADS1115 4-channel 16-bit ADC Texas Instruments 0x48 to 0x4b ADXL345 3-axis accelerometer Analog Devices 0x1d, 0x53 AHT10 Temperature and humidity sensor Asair 0x38 AHT20 Temperature and humidity sensor Asair 0x38 BMA180 Accelerometer Bosch 0x77 BME280 Temperature, pressure and humidity sensor Bosch 0x76, 0x77 BMP085 Barometric pressure sensor Bosch 0x77 BMP180 Temperature/barometric pressure sensor Bosch 0x76, 0x77 BMP280 Temperature/barometric pressure sensor Bosch 0x77 CCS811 Gas and air quality sensor ScioSense 0x5a, 0x5b D7S Vibration sensor Omron 0x55 DS1307 Real-time clock Maxim 0x68 FS3000 Air velocity sensor Renesas 0x28 HT16K33 LED matrix driver Holtek 0x70 to 0x77 ITG3200 3-axis gyro InvenSense 0x68, 0x69 LTC4151 Voltage and current monitor ST Microelectronics 0x66 to 0x6f MAX44009 Ambient light sensor Maxim 0x4a, 0x4b MCP23017 I2C GPIO expander Microchip 0x20 to 0x27 MCP4728 4-channel 13-bit DAC Microchip 0x60 to 0x67 MPR121 12-point capacitive touch sensor NXP 0x5a to 0x5d SAA1064 4-digit LED driver NXP 0x38 to 0x3b TDA8421 Audio processor NXP 0x40, 0x41 TEA5767 Radio receiver NXP 0x60 TSL2561 Light sensor Texas Instruments 0x39, 0x49 VML6075 UV sensor Vishay 0x10 direction of the data transfer. The address is transferred with the most-significant bit first (see Fig.5.11). Table 5.4 lists just a small selection of currently available devices that support I2C. from the I2C scanner.) Note that I2C applications require the Wire.h (or equivalent) library and so we’ve included it (using #include) at the start of the code. What’s connected? It’s useful to have a means of determining how many I2C devices are present in a system as well as which I2C addresses have been allocated. This is achieved using an application known as an ‘I2C scanner’ along the lines of that shown in Listing 5.3. (Fig.5.12 shows some typical data Practical Project Now let’s move on with an I2C application that will send temperature and humidity data from a DHT22 sensor to a low-cost LCD panel. With only two GPIO pins needed for data transfer this leaves plenty of I/O available for use with other items of external hardware. Fig.5.10. I2C bus interface logic. 62 Practical Electronics | July | 2024 Listing 5.3 A simple I2C scanner /* Simple I2C scanner */ #include <Wire.h> void setup() { Serial.begin (115200); Serial.println (); Serial.println (“Performing I2C scan ...”); byte count = 0; Wire.begin(); for (byte i = 8; i < 120; i++) { Wire.beginTransmission (i); if (Wire.endTransmission () == 0) { Serial.print (“I2C device found at: “); Serial.print (“ 0x”); Serial.println (i, HEX); count++; } } // Scan complete so print total found Serial.print (“Scan completed. Found “); Serial.print (count, DEC); Serial.println (“ device(s).”); } void loop() { // Main code (if any) goes here } Listing 5.4 Sample code for the LCD temperature and humidity monitor * ESP32 with DHT22 and 16 x 2 LCD to display temperature and humidity */ Fig.5.11. I2C bus transaction showing how first an address and then data is placed on the bus. Fig.5.12. Typical Serial Monitor output when using the I2C scanner in Listing 5.3. The circuit arrangement for the LCD and DHT22 application is shown in Fig.5.13. This arrangement is based on a low-cost 16 × 2 LCD panel fitted with an I2C interface (see Fig.5.14). Note that the interface is mounted on the back of the LCD panel and has four connections: GND, VCC, SDA and SCL. SDA is used for data and SCL is used for the clock signal. With the code in Listing 5.4 running, the breadboard wiring for the LCD and DHT22 application is shown in Fig.5.15. If required, the display backlight can be adjusted using the small preset resistor (the square blue component shown in Fig.5.14). You should notice that we’ve included two libraries at the beginning of the code in Listing 5.4 using these lines: #include <dhtnew.h> // To use the DHTxx sensor #include <LiquidCrystal_I2C.h> // To use the LCD // Include the library files #include <dhtnew.h> #include <LiquidCrystal_I2C.h> // Define the LCD parameters int lcdColumns = 16; int lcdRows = 2; // Setup the LCD LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); DHTNEW mySensor(16); // UART RXD input void setup() { Serial.begin(115200); // Initialize LCD lcd.init(); // Turn the backlight ‘on’ lcd.backlight(); } void loop() { // First read the sensor mySensor.read(); // Now display on the LCD lcd.setCursor(0, 0); // First row lcd.print(“Temp: “); lcd.print(mySensor.getTemperature(), 1); lcd.print(“ deg.C”); lcd.setCursor(0, 1); // Second row lcd.print(“Humidity: “); lcd.print(mySensor.getHumidity(), 1); lcd.print(“%”); delay(5000); // Wait for 5 seconds lcd.clear(); } Practical Electronics | July | 2024 Fig.5.13. Circuit arrangement for the LCD and DHT22 application. Fig.5.14. I2C interface mounted on back of a 16 × 2 LCD display. 63 Fig.5.16. Output from the maths operator code. You should have already located and installed the first of these two library files. The other file can be downloaded using the IDE’s Library Manager. Coding Workshop It’s time to do some maths! You’ve already made use of some of the operators that the C++ language Fig.5.15. Breadboard wiring for the DHT22 and 16 × 2 LCD display. provides. They are + (addition), – (subtraction), * (multiplication), and / (division). You will doubtless already be familiar with Listing 5.5 Testing the math operators them – but if not, Listing 5.5 shows some code that might act as a reminder. // Checking math operators +, -, *, and / The Serial Monitor output of Listing 5.5 is shown in Fig.5.16. The code in the main loop executes only once void setup() { and halts at while(1) (where it waits forever). Since we // Start the Serial Monitor don’t actually need a loop that’s repeated we could have Serial.begin(9600); simply placed all of the code in setup() which is only } ever executed once. In this case we would simply have an empty main loop. Notice also that we’ve used the tab void loop() { float x = 12.3; character (\t) to neatly space the Serial Monitor’s output. float y = 45.6; As an example of using maths operators let’s consider Serial.println(“Maths operators!”); temperature conversion from Celsius to Fahrenheit. This Serial.print(“Added: \t\t”); can be easily achieved using these lines of code: Serial.println(x + y); Serial.print(“Subtracted: \t”); degF = (degC * 1.8) + 32; // Convert deg.C to deg.F Serial.println(x - y); degC = (degF - 32) / 1.8; // Convert deg.F to deg.C Serial.print(“Mulitiplied: \t”); Serial.println(x * y); The variables (degF and degC) are both declared as floats, Serial.print(“Divided: \t”); using these lines: Serial.println(x / y); while(1); // Wait forever } float degC; // Temperature in deg.C float degF; // Temperature in deg.C Table 5.5 Some useful maths functions from the Arduino Math library Function Returned value Notation Result (when x = 2 and y = 2) sqrt(x) square root of x √x 1.41 sq(x) square of x x2 4.00 pow(x, y) x raised to the power y xy 4.00 log(x) natural logarithm of x (base e) ln(x) 0.69 log10(x) logarithm of x (base 10) log10(x) 0.30 exp(x) e raised to the power x ex 7.39 sin(x) sine of x sin(x) 0.91 cos(x) cosine of x cos(x) -0.42 tan(x) tangent of x tan(x) -2.19 fabs(x) absolute value of floating point x |x| 2 fmod(x,y) floating point modulo of x divided by y x mod y 0 64 There’s something vrucial to be aware of here. The order in which maths operators are applied is vitally important. The correct order of operations is brackets, orders (powers and roots), division, multiplication, addition and subtraction. You might recall this from your secondary school education as BODMA (or BOMDAS). Failing to use the correct order can produce some very odd results! The Arduino Math library (math.h) includes some useful function for manipulating numbers. Note that this library is part of the language core and it does not have to be installed (unlike other library files that we’ve been using). Some of the most useful functions are summarised in Table 5.5. Now let’s suppose we need to determine the power present in a load resistor from a measurement of the peak Practical Electronics | July | 2024 Listing 5.6 Initial code for this month’s Teach-In challenge /* ESP32 with AHT20, BMP280, and 20 x 4 LCD displaying temperature, humidity, and pressure */ Fig.5.17. Required display format for this month’s Teach-In Challenge. voltage developed across it. The relationship between RMS power, peak voltage and resistance is given by: P = 0.5V2/R Where P is the power in the load (in watts), V is the peak voltage developed across the load (in volts), and R is the value of load resistance (in ohms). We will use floating point variable (floats) for the three variables using the following declarations: float loadR, peakV, loadP; // Declare the variables // Include the library files #include <Wire.h> #include <LiquidCrystal_I2C.h> #include <AHT20.h> #include <BMP280.h> AHT20 aht20; BMP280 bmp280; // Define the LCD parameters int lcdColumns = 20; int lcdRows = 4; // Setup the LCD LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); void setup() { Serial.begin(115200); Wire.begin(); // Use the I2C bus bmp280.begin(); We can then use the next line of code to perform the calculation: //Check if the AHT20 will acknowledge if (aht20.begin() == false) { Serial.println(“AHT20 not present!”); while (1) ; } Serial.println(“AHT20 detected!”); // Initialize LCD lcd.init(); // Turn the backlight ‘on’ lcd.backlight(); loadP = (0.5 * sq(peakV)) / loadR; // Calculate the power If, on the other hand, we just want to print the value returned via the Serial Monitor then we could use this line: Serial.println((0.5 * sq(peakV)) / loadR); // Print the power } void loop() { // If a new measurement is available if (aht20.available() == true) { //Get the new temperature and humidity value float temperature = aht20.getTemperature(); float humidity = aht20.getHumidity(); // Get the barometric pressure uint32_t pressure = bmp280.getPressure(); // Now display on the LCD // Your code must continue here! Teach-In challenge This month’s Teach-In challenge involves developing a device that monitors temperature, humidity and barometric pressure, and displays the current values on a 20 × 4 LCD display Fig.5.18. Using I2C to interconnect the sensors, 20 × 4 LCD display and ESP32. Gotcha! When performing calculations the order in which maths operators are applied is vitally important. It’s always worth checking carefully or splitting your calculations into smaller chunks spread over several lines of code. Practical Electronics | July | 2024 Fig.5.19. Modified AHT20/BMP280 module cable (a 4-pin header replaces one of the two connectors). 65 along the lines shown in Fig.5.17. We suggest that you use three I2C devices in the application: an AHT20 I2C temperature and humidity sensor, a BMP280 barometric pressure sensor, and a 20 × 4 I2C LCD display. Using I2C, it’s easy to interconnect the sensor modules, display and ESP32. In the layout shown in Fig.5.18 we’ve used a combined AHT20/BMP280 module. This module is available from various online suppliers and is often supplied with a 4-way cable. A simple way of attaching this to a breadboard is by removing one of the connectors and soldering a 4-pin male header mounted on a small piece of stripboard in its place (see Fig.5.19). The header can then simply be plugged into the breadboard in a suitable location (see Fig.5.20). Note that the colours used for the combined sensor module are not the same as those shown for the breadboard wiring in Fig.5.19. Additional wiring will be needed is you are using separate AHT20 and BMP280 sensors. In this challenge we’re going to leave you to develop the code, but we’ve provided you with some initial lines in Listing 5.6. The next task is completing the code in the main loop. This should send the temperature, humidity and pressure data to the LCD panel. If you Your best bet since Fig.5.20. Wiring diagram for this month’s Teach-In Challenge. Note that the combined sensor module cable is not shown in this diagram. get stuck, you can always download a solution from the PE website. Good luck! Next month In Part 6, we will be showing you how to connect your ESP32 to a Wi-Fi network. Coding Workshop will deal with strings and string manipulation and our Practical Project will feature a network-connected temperature and humidity monitor. Finally, as we will have reached the halfway point in our series, Checkpoint will provide you with a means of testing your ESP32 knowledge! MAPLIN Chock-a-Block with Stock Visit: www.cricklewoodelectronics.com Or phone our friendly knowledgeable staff on 020 8452 0161 Components • Audio • Video • Connectors • Cables Arduino • Test Equipment etc, etc JTAG Connector Plugs Directly into PCB!! No Header! No Brainer! Our patented range of Plug-of-Nails™ spring-pin cables plug directly into a tiny footprint of pads and locating holes in your PCB, eliminating the need for a mating header. Save Cost & Space on Every PCB!! Visit our Shop, Call or Buy online at: www.cricklewoodelectronics.com 020 8452 0161 66 Visit our shop at: 40-42 Cricklewood Broadway London NW2 3ET Solutions for: PIC . dsPIC . ARM . MSP430 . Atmel . Generic JTAG . Altera Xilinx . BDM . C2000 . SPY-BI-WIRE . SPI / IIC . Altium Mini-HDMI . & More www.PlugOfNails.com Tag-Connector footprints as small as 0.02 sq. inch (0.13 sq cm) Practical Electronics | July | 2024