Silicon ChipPICn’Mix - January 2022 SILICON CHIP
  1. Outer Front Cover
  2. Contents
  3. Subscriptions: PE Subscription
  4. Subscriptions: PicoLog Cloud
  5. Back Issues: PICOLOG
  6. Publisher's Letter
  7. Feature: The Fox Report by Barry Fox
  8. Feature: Communing with nature by Mark Nelson
  9. Feature: Net Work by Alan Winstanley
  10. Project: Vintage Battery Radio Li-ion Power Supply by Ken Kranz and Nicholas Vinen
  11. Project: The MiniHEART by John Clark
  12. Project: Balanced Input and Attenuator for the USB by Phil Prosser
  13. Feature: Flowcode G raph ical Programming by Martin Whitlock
  14. Feature: Max’s Cool Beans by Max the Magnifi cent
  15. Feature: PICn’Mix by Mike Hibbett
  16. Feature: Circuit Surgery by Ian Bell
  17. Feature: AUDIO OUT by Jake Rothman
  18. Feature: Make it with Micromite by Phil Boyce
  19. PCB Order Form
  20. Advertising Index

This is only a preview of the January 2022 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)
PIC n’Mix Mike Hibbett’s column for PIC project enlightenment and related topics Part 9: PIC18F Development Board T his month, we will add an LCD panel to our Development Board. Not because it especially needs one – the IoT platform Internet dashboard we introduced is far more flexible and convenient – but to demonstrate the capability, and test out one of our board’s more complex peripheral interface, the SPI bus. Plus, of course, for some standalone applications a small, dedicated display is very useful. First, let’s add to the previous article by going into a little more detail about how to send data of your choice to the IoT dashboard, as shown in the main.c file from that article. The code itself is short, as shown in Listing 1, but there’s a lot of complexity buried within it. Let’s work through it. TCP The first two lines tell the ESP-01 module which website we are connecting to, and what protocol to use. Here, the connection will use the TCP protocol. This is a requirement for sending data to the Thingsboard website. Website The URL or website name we will connect to is: demo.thingsboard.io Port number The TCP Port number is 80. This number directs our data to a particular service on the website. Thingsboard implements their data input service on this port number, so that’s what we specify. PIC n’ Mix PIC18F Development Board The PCB for the PIC18F Development Board is available from the PE PCB Service – see the July 2021 section. www.electronpublishing.com/ product-category/pe-pcb-service/ 48 Now, we can send as much data as we wish. Each message to be sent consists of two steps: Telling the ESP-01 module how many bytes of data we are going to send in the message, then the message itself. Commands We use the AT+CIPSEND command to specify the number of bytes we will send; as shown in line 4, this will be 180 bytes. The bytes are sent using the POST command, as shown in line 9, where the command and our string of 180 bytes has been stored in the character array variable esp01_buff The message Now, the tricky part – and this did take a lot of trial and error to arrive at the correct message – exactly what do we need to send in that POST command? We use the sprintf function to create this string, because we need to insert into the string a different value for voltage each time it is used. It’s a long string, so let’s break it down into parts: POST /api/v1/ACCESS-TOKEN/ telemetry This is the address (like a sub-directory) on the website where the data will be sent. As this string contains our unique ACCESS-TOKEN, that directory is specific and private to us. (Note that it’s private because the ACCESS-TOKEN string is 16 characters long and randomly generated by Thingsboard, no one is going to guess it.) HTTP/1.1\r\nHost: demo. thingsboard.io\r\nAccept: application/json\r\nContentLength: 23\r\nContent-Type: application/json\r\n These characters define the type of message we are sending. Thingsboard expects you to be sending an HTTP POST message, but the ESP-01 module only supports raw TCP messages, which is a lower-level communication protocol. By sending these characters, we are effectively implementing the HTTP protocol ourselves. Thankfully, the message is a simple fixed-format string, so once you know what to send (and finding that out was a challenge!) it can be hard coded into your program, as shown above. Listing 1. Sending data over the ESP-01. uart2_putstr("AT+CIPSTART=\"TCP\",\"demo.thingsboard. io\",80\r\n"); parse_response(1000); uart2_putstr("AT+CIPSEND=180\r\n"); parse_response(500); sprintf(esp01_buff, "POST /api/v1/ACCESS-TOKEN/telemetry HTTP/1.1\r\nHost: demo.thingsboard.io\r\nAccept: application/json\r\nContent-Length: 23\r\nContent-Type: application/json\r\n\r\n{\"SolarVolts\": %1.3f}\r\n", solarPanel_volts); uart2_putstr(esp01_buff); parse_response(1000); All Listings are available for download from the January 2022 page of the PE website. Practical Electronics | January | 2022 Fig.1. 2×16-character LCD. There is one important part of that message that may change: the section Content-Length. Here, 23 is specifying how long the real payload of the HTTP message is. This information is required by the webserver so it can tell how many more data bytes will follow. And that brings us to the final part: \r\n{\"SolarVolts\": %1.3f} This is the actual message we are sending. Remember that this string is a format string for the sprintf C function, the \" characters will be replaced with a single " character, and the part %1.3f will be translated into a floating-point value, held in the variable SolarVolts, in the format 1.234, or five characters. So, finally, the message we are sending to the website is: {"SolarVolts": 1.234} This has a CRLF sequence at the beginning. Add these characters up, and you will see they come to 23 bytes. The entire string is 180 bytes long, which matches the value specified in the AT+CIPSEND command. Phew! That was a lot to take in, but the key point is that you can send a message with any variable name within the quoted string, and Thingsboard will create a new variable in the dashboard and save any data you send. Each time a message is received it is timestamped by Thingsboard before storing it in its database. So now, if you decide that you are going to send a new variable of a different length, note the full length of the string, as shown above, and adjust the value specified in Content-Length, and the length specified in the AT+CIPSEND command. As a final note, although we ran with the Thingsboard IoT platform, there are other free platforms available. We are currently evaluating www.kaaiot.com/free-trial after a recent demonstration by their development team. That service is Fig.2. 320×240 colour graphics display. provided for free if you have five or fewer devices, with historic data held for the previous three months. Adding a display It’s time to move on from Internet connectivity to the next peripheral interface on our Development Board – the display. While this interface on HDR16 is labelled ‘TOUCH LCD’, it’s not limited to a specific display technology, as we will see. The 12 GPIO pins allocated to this interface provide the flexibility to support a range of display technologies, albeit with some restrictions. As recently as 15 years ago the choice of display technology to attach to a microcontroller was very limited – typically, the 2×16-character LCD panel, with a backlight if you were lucky. In those days, we were happy with this status quo as the predominate technology since before this were seven-segment LEDs which were large, power hungry and extremely limited. Fast forward to today and, amusingly, the 2×16-character LCD is still popular and quite appropriate for many applications. However, there are several much more interesting options available, which provide full graphic capability and other interesting features. These can be summarised as follows. 2×16-character LCD These require a few GPIOs to control them and can operate at 3.3V or 5V, depending on the model purchased. They are very simple to use, with multiple software drivers available on the Internet. The example shown in Fig.1 has an LED backlight. Full-graphic displays These panels are available in a range of physical sizes but have the added benefit of an integrated controller with memory that simplifies the interface to a resource-constrained microcontroller. The example shown in Fig.2. has an integrated Fig.3. Tiny OLED screen. Practical Electronics | January | 2022 Fig.4. ePaper: a ‘modern-day Etch A Sketch!’ 49 makes them eminently suitable for small and novel projects. Despite its tiny size, the display in Fig.3. has a resolution of 128×64 pixels. ePaper One of the most unusual display innovations to have occurred in recent years is ePaper technology. These are mainly monochrome displays that retain their image even when power is removed. They have excellent contrast ratio and high resolution, making them easy to read. The example shown in Fig.4. has been designed to work with the Raspberry Pi, but we can use it too. The drawback with these displays is that changing the image shown, even just a few pixels, requires a refresh that can take up to a second. For projects where information changes infrequently, these can be ideal due to their extremely low power requirements. Fig.5. 2×16-character LCD pin mapping. resistive-touch sensitive layer, easily controlled by a microcontroller to enable rich interactive user interfaces. Resistive touch interfaces are not as nice as the capacitive touch sensors we are used to on mobile phones and tablets, but they are cheap and easy to interface to, and require just four G/O pins to control. OLED These are an interesting recent invention that provide high-resolution vibrant displays, in a thin physical format, with no need for an additional backlight. Due to their flexibility and low cost of manufacture they have become available in a wide range of sizes. Slightly more expensive than LCD panels, but their thin structure LVDS Commonly used in laptops and highend mobile phones, LVDS panels are so named due to the electrical interface used to communicate with them. (low-voltage differential signalling.) These panels can be large, high resolution and cheap, but unfortunately cannot be connected directly to a microcontroller. The communication speed is in the hundreds of MHz, and a huge RAM buffer is required to store the data to be displayed. Specialised processors such as the Raspberry Pi have a dedicated display driver peripheral and the ability to address a large RAM buffer, but not our humble PIC. Let’s take a few example displays and walk through the process of connecting them up and displaying data. We start with a classic. 2×16-character LCD We first create a project in MPLAB, just as we did in the previous article, remembering to select our processor, the PIC18F47K42. We name this project 2x16lcd The initial project setup does not create any actual source files like main.c, but that is OK as we will use the MCC tool to configure some options, and it will create the initial source files for us. Start by configuring within MCC the System Module peripheral, found in the ‘Project Resource’ window, to select our CPU clock source. Change ‘Oscillator Select’ from EXTOSC to HFINTOSC, ‘HF Internal Clock’ to 64_MHz, and ‘Clock Divider’ to 1. We will run the processor at its maximum speed of 64MHz. Now for the GPIO pins. Click on the Pin Module of the Project Resource window, then locate the ‘GPIO Output’ row in the ‘Pin Manager: Grid View’ at the bottom of the window. Within this row, click on the lock icons for Port C 3,4,5 and then Port D 4,5,6,7. Notice that as you click on each lock it turns green, and the pin name appears in a row at the top of the window. When done, change the ‘Package:’ field to ‘PDIP40’. Referring to Fig.5, there are three LCD control signals RS, R/W, ENABLE and then just four data pins required: D4, D5, D6 and D7 (the upper four pins of the data bus on the display must be used in 4-bit communication mode.) We will give meaningful names to our IO pins, renaming the ‘Custom Name’ column in the ‘Pin Module’ window for each pin to match its intended function. You can see this in Fig.6. Note that you must also unclick the analogue function associated with these pins. Fig.6. GPIO pin configuration in MCC. 50 Practical Electronics | January | 2022 H DR20 H DR16 G ND V + RC3 RC4 RC5 RD4 RD5 RD6 RD7 G ND V + H DR15 Fig.7. Hooking up the 2×16-character LCD to our board. You can now click the ‘Generate’ button in the ‘Project Resources’ window to create our source files. Now to create our LCD driver. To keep things tidy we will store each display’s driver code in separate files, so we start by creating files 2x16lcd.c and 2x16lcd.h and adding them to the project. In the ‘Project’ tab in the top left window, right-click over the ‘Source Files’ icon, select ‘New’ followed by ‘main.c...’ In the ‘File Name’ field enter ‘2x16lcd’ and click ‘Finish’. The file will open in the IDE; delete the three lines defining an empty main function. Now right-click over the ‘Header Files’ icon and select ‘New’ followed by ‘xc8_header.h...’ In the ‘File Name’ field enter ‘2x16lcd’ and click ‘Finish’. Again, the file will open in the IDE. This file template has lots of complex comments, just go ahead and delete all the contents. You can run a build at this point to confirm there are no errors, which if there are, will be minor typing mistakes on your part! So, we now have our files, but how will we write our actual driver code? Thankfully, this display has been popular for decades so there are dozens if not hundreds of well-written examples provided for free on the Internet. Surprisingly, Microchip have not provided an MCC function for driving LCDs. They do, however, have a legacy library which we can use as the basis for our own driver. The library can be downloaded from the Microchip website which you can find if you search for ‘PIC18F Legacy Peripheral Libraries v2.0’. Practical Electronics | January | 2022 There is no need to however, as Listing 2. Using the 2×16-character LCD driver. we will take the source code we need and add it to our own #include "mcc_generated_files/mcc.h" source code, which we provide #include "2x16lcd.h" for download from the January 2022 page of the magazine void main(void) website. You may find the full { Microchip download useful // Initialize the device however for other driver exSYSTEM_Initialize(); amples. While there are many sources available on the Inter// Enable the LCD net, we preferred to go with an Open2x16LCD(); original Microchip driver as we know the files are free for re-use // Turn blinking and cursor off with no licence restrictions. WriteCmdXLCD(BLINK_CURSOR_OFF); The downloaded library contains many libraries (all putrsXLCD("Practical"); worth looking at) but we focus WriteCmdXLCD(LINE_2_ADDRESS); on the XLCD library, which putrsXLCD("Electronics"); supports just the 2×16-character LCD, based on a 44780 __delay_ms(2000); LCD controller (this controller IC has been copied numerous WriteCmdXLCD(CLEAR_SCREEN_CMD); times by IC manufacturers and the chipset on your LCD may putrsXLCD("Postcard PIC"); not say the same part number, WriteCmdXLCD(LINE_2_ADDRESS); but they are all compatible.) putrsXLCD("Dev Board"); The library we are interested in is called ‘XLCD’. This conwhile (1) tains ten source files, which { sounds intimidating until // Add your application code you discover that each file } is a single function (a good } design principle, but a bit of over-kill for a simple display.) After a quick review of each file, the functions in our main.c file. The full we can see that several files related to main.c contents to drive the display can creating custom bitmaps and reading be seen in Listing 2. display memory can be ignored. All To wire up the LCD, follow the schematwe want to do is initialise the display, ic shown in Fig.7. Note that this display clear it, set a cursor position and write runs at 5V (you can find 3.3V versions, characters to the display. This requires but they are more expensive.) Because far less code (although it is nice to have of this, we must remove the SD Media the extended capabilities available.) We card interface and ESP-01 module as will copy all the functions we require these operate at 3.3V only. These LCDs into our driver file, 2x16lcd.c require a variable resistor to adjust the We start by copying across the display contrast, but we can make use of one alinitialisation code. This sets all the I/O ready fitted to the Development Board. pins to correct defaults and sends a short You can see an example setup and disconfiguration sequence to the display. play output in Fig.8. Our initial task is to re-assign I/O pin It’s worth noting that these 2×16-chardefines to match our selection, and also acter LCDs come in a variety of styles, implement some delay routines – the 3.3V operation, plus a choice of interface: LCD’s controller requires a short delay parallel, I2C and even UART. to execute each command. Most of our effort was associated with Full-colour graphic writing the delay functions, important Let’s move to the opposite end of the because the LCD’s internal controller spectrum and interface a popular fullruns relatively slowly and needs time to graphic display, the 1.8TFT SPI 128*160 complete commands sent to it. module. This is a small 1.8-inch diagonal With the delays implemented (thanks display that has a standard controller IC to messing around with an oscilloscope fitted, the ST7735. This IC has a 48KB and checking timings) we can just copy internal full-frame RAM buffer and proover the required functions to make the vides an SPI bus for control, so it can be ‘open’ function compile. With that workcoupled with a very constrained microing, the remaining functions can be copied controller. It’s manufactured by many over. Their prototypes are added to the vendors, so is unlikely to become un2x16lcd.h header file, so we can reference available at short notice. 51 board that also used a PIC18F processor. We can copy those files into our project and hopefully make just a few changes to reflect the different IO pins used. There are three source files: LCD-Graphic-Font.h LCD-Graphic-ST7735S.c LCD-Graphic-ST7735S.h Fig.8. The 2×16-character LCD in action. The interface to this display is very simple: 3.3V DC, an ‘SPI-like’ interface using just the clock signal and data input, and three control signals. You can see the display in Fig.9, and the wiring to our board in Fig.10. Because this display is based on TFT technology there is no need for a contrast adjustment resistor. The software interface to this display is very basic – you can set and clear individual pixels, and not much else. High-level functions, such as drawing lines, circles and even text must be built up from simple pixel functions. As you can guess, there is a complex software requirement coming! Let’s go ahead and create a project to drive the display. We start a completely new project, naming it graphicLCD. Once again, we start the MCC tool and set the processor clock to 64MHz, and the package type to PDIP40. We are going to need the SPI peripheral, so we click on the ‘+’ icon next to SPI1 in the ‘Device Resources’ list to add it to our device resources. In the ‘Pin Manager: Grid View’ tab, you can see three SPI function pins have been added to the list, and Port C pins 3 and 4 have been automatically added as SCK and SDI signals. We can move these to other pins if we want, but doing so requires messing with peripheral port select registers. That’s unnecessary anyway as these two pins come out to our LCD header (yes, we thought ahead when designing the Development Board’s pin allocations!) On the ‘SDO1’ row, click on the lock icon under Port C pin 5 to select that as the SPI bus output pin. We now want to add our three control signals, RA5, 6 and 7. In the ‘Pin Manager: Grid View’ tab on the ‘GPIO Output’ row, click on the icons for those three pins. Again, unclick the ‘Analog’ tick boxes for these three pins. We will leave the custom name associated with them unchanged. That’s all the configuration we need to do in MCC, so in the ‘Project Resources’ tab press the ‘Generate’ button to have MCC create our files. Graphics driver As mentioned, this display uses a common LCD controller IC called the ST7735S and driver software for this is freely available widely on the web – but finding the correct software can be a bit hit and miss. Thankfully, we developed a driver for this display back in 2014 when we launched the ‘LPLC’ Kickstarter, a To make use of these files the first step is to copy them into the project directory (in the same location as main.c). Next, we have to tell MPLAB to include these files within our project. Click on the ‘Projects’ tab in the top left window of MPLAB to show a summary list of the files. Next, right-click on the ‘Header Files’ section in the tree list, then ‘Add Existing Item...’ Click on the LCD-Graphic-Font.h file, then click the ‘Select’ button. Repeat for LCD-Graphic-ST7735S.h. Now rightclick on the ‘Source Files’ section, then ‘Add Existing Item...’ Click on the LCD-Graphic-Font.c file, then click the ‘Select’ button. As this is the first time we have integrated this LCD driver software into one of our Development Board projects, we will have to make a few changes to the source files. This consists of changing the I/O pins for the three control signals, and using the MCC-generated functions for writing to the SPI peripheral. And nothing else. In your own projects you may need to adjust the ‘Clock Divider’ fi eld of the SPI1 peripheral to get proper operation, since long wires connecting to the display will limit how fast the bus can run for reliable operation. On our setup we run the SPI bus at 6.4MHz with 20cm hookup wires connecting the display; you should be able to run this at 10MHz or more with very short wiring. We created a very simple program within our project’s main.c file to test some of the functions. You can see the results of the program shown in Listing 3 in the screen shot shown in Fig.11. H DR15 RC3 RC5 RA6 RA7 RA5 G ND V + H DR16 Fig.9. 1.8-inch graphics LCD. 52 Fig.10. Wiring schematic for the graphics display. Practical Electronics | January | 2022 Listing 3. Using the full graphic display. #include "mcc_generated_files/mcc.h" #include "LCD-Graphic-ST7735S.h" void main(void) { // Initialize the device SYSTEM_Initialize(); SPI1_Open(SPI1_DEFAULT); LCDST7735sInit(); LCD_Clear(BLACK); LCD_ShowString(50,50,"Hello World!"); LCD_DrawRectangle(20, 20, 40, 40); POINT_COLOR = RED; Draw_Circle(100,50,20); LCD_Fill(80, 80, 90, 90, GREEN); Fig.11. The 1.8-inch graphics LCD in action. If you like the format of this display, you can find similar display modules available across the Internet. At the time of writing, this version which should be compatible is available from eBay.co.uk as part number 174564132213. All these steps to incorporate source files and configure MPLAB have been completed in the source files available on the magazine website, so you do not need to run through the steps above. The source files for both of this month’s projects can be found on January 2022 page of the the magazine while (1) website in the zip file named { jan-2022-picnmix.zip // Add your application code We hope you have enjoyed } this introduction to the use } of the PIC18F Development Board, and have learned how to make use of MPLAB and the MCC tool to easily develop applications of your own. PIC n’ Mix files We look forward to developing new The programming files discussed projects from this platform in the future, in this article are available for and as always, if you have suggestions download from the PE website. for projects, please send them in! Teach-In 8 CD-ROM Exploring the Arduino This CD-ROM version of the exciting and popular Teach-In 8 series has been designed for electronics enthusiasts who want to get to grips with the inexpensive, immensely popular Arduino microcontroller, as well as coding enthusiasts who want to explore hardware and interfacing. Teach-In 8 provides a one-stop source of ideas and practical information. The Arduino offers a remarkably effective platform for developing a huge variety of projects; from operating a set of Christmas tree lights to remotely controlling a robotic vehicle wirelessly or via the Internet. Teach-In 8 is based around a series of practical projects with plenty of information for customisation. The projects can be combined together in many different ways in order to build more complex systems that can be used to solve a wide variety of home automation and environmental monitoring problems. The series includes topics such as RF technology, wireless networking and remote web access. PLUS: PICs and the PICkit 3 – A beginners guide The CD-ROM also includes a bonus – an extra 12-part series based around the popular PIC microcontroller, explaining how to build PIC-based systems. SOFTWARE EE FR -ROM CD ELECTRONICS TEACH-IN 8 £8.99 FREE CD-ROM SOFTWARE FOR THE TEACH-IN 8 SERIES FROM THE PUBLISHERS OF INTRODUCING THE ARDUINO • Hardware – learn about components and circuits • Programming – powerful integrated development system • Microcontrollers – understand control operations • Communications – connect to PCs and other Arduinos PLUS... PIC n’MIX PICs and the PICkit 3 - A beginners guide. The why and how to build PIC-based projects Teach In 8 Cover.indd 1 04/04/2017 12:24 PRICE £8.99 Includes P&P to UK if ordered direct from us The CD-ROM contains the software for both the Teach-In 8 and PICkit 3 series. ORDER YOUR COPY TODAY at: www.electronpublishing.com Practical Electronics | January | 2022 53