Silicon ChipMax’s Cool Beans - June 2020 SILICON CHIP
  1. Outer Front Cover
  2. Contents
  3. Subscriptions: PE Subscription
  4. Subscriptions: PicoLog Cloud
  5. Publisher's Letter: Publisher's Statement
  6. Publisher's Letter
  7. Feature: Techno Talk by Mark Nelson
  8. Feature: Net Work by Alan Winstanley
  9. Back Issues: Net Work by Alan Winstanley
  10. Project: AM/FM/CW Scanning HF/VHF RF Signal Generator by Andrew Woodfield
  11. Project: A low-cost 3.5-inch touchscreen for the Arduino or Micromite by Tim Blythman
  12. Project: Ultra-low-distortion Preamplifier with Tone Controls Part 3 by John Clarke
  13. Feature: Circuit Surgery by Ian Bell
  14. Feature: Practically Speaking by Mike Hibbett
  15. Feature: Make it with Micromite by Phil Boyce
  16. Feature: AUDIO OUT by Jake Rothman
  17. Feature: Max’s Cool Beans by Max the Magnificent
  18. PCB Order Form
  19. Advertising Index

This is only a preview of the June 2020 issue of Practical Electronics.

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

Articles in this series:
  • Techno Talk (June 2020)
  • Techno Talk (June 2020)
  • Techno Talk (July 2020)
  • Techno Talk (July 2020)
  • Techno Talk (August 2020)
  • Techno Talk (August 2020)
  • Techno Talk (September 2020)
  • Techno Talk (September 2020)
  • Techno Talk (October 2020)
  • Techno Talk (October 2020)
  • (November 2020)
  • (November 2020)
  • Techno Talk (December 2020)
  • Techno Talk (December 2020)
  • Techno Talk (January 2021)
  • Techno Talk (January 2021)
  • Techno Talk (February 2021)
  • Techno Talk (February 2021)
  • Techno Talk (March 2021)
  • Techno Talk (March 2021)
  • Techno Talk (April 2021)
  • Techno Talk (April 2021)
  • Techno Talk (May 2021)
  • Techno Talk (May 2021)
  • Techno Talk (June 2021)
  • Techno Talk (June 2021)
  • Techno Talk (July 2021)
  • Techno Talk (July 2021)
  • Techno Talk (August 2021)
  • Techno Talk (August 2021)
  • Techno Talk (September 2021)
  • Techno Talk (September 2021)
  • Techno Talk (October 2021)
  • Techno Talk (October 2021)
  • Techno Talk (November 2021)
  • Techno Talk (November 2021)
  • Techno Talk (December 2021)
  • Techno Talk (December 2021)
  • Communing with nature (January 2022)
  • Communing with nature (January 2022)
  • Should we be worried? (February 2022)
  • Should we be worried? (February 2022)
  • How resilient is your lifeline? (March 2022)
  • How resilient is your lifeline? (March 2022)
  • Go eco, get ethical! (April 2022)
  • Go eco, get ethical! (April 2022)
  • From nano to bio (May 2022)
  • From nano to bio (May 2022)
  • Positivity follows the gloom (June 2022)
  • Positivity follows the gloom (June 2022)
  • Mixed menu (July 2022)
  • Mixed menu (July 2022)
  • Time for a total rethink? (August 2022)
  • Time for a total rethink? (August 2022)
  • What’s in a name? (September 2022)
  • What’s in a name? (September 2022)
  • Forget leaves on the line! (October 2022)
  • Forget leaves on the line! (October 2022)
  • Giant Boost for Batteries (December 2022)
  • Giant Boost for Batteries (December 2022)
  • Raudive Voices Revisited (January 2023)
  • Raudive Voices Revisited (January 2023)
  • A thousand words (February 2023)
  • A thousand words (February 2023)
  • It’s handover time (March 2023)
  • It’s handover time (March 2023)
  • AI, Robots, Horticulture and Agriculture (April 2023)
  • AI, Robots, Horticulture and Agriculture (April 2023)
  • Prophecy can be perplexing (May 2023)
  • Prophecy can be perplexing (May 2023)
  • Technology comes in different shapes and sizes (June 2023)
  • Technology comes in different shapes and sizes (June 2023)
  • AI and robots – what could possibly go wrong? (July 2023)
  • AI and robots – what could possibly go wrong? (July 2023)
  • How long until we’re all out of work? (August 2023)
  • How long until we’re all out of work? (August 2023)
  • We both have truths, are mine the same as yours? (September 2023)
  • We both have truths, are mine the same as yours? (September 2023)
  • Holy Spheres, Batman! (October 2023)
  • Holy Spheres, Batman! (October 2023)
  • Where’s my pneumatic car? (November 2023)
  • Where’s my pneumatic car? (November 2023)
  • Good grief! (December 2023)
  • Good grief! (December 2023)
  • Cheeky chiplets (January 2024)
  • Cheeky chiplets (January 2024)
  • Cheeky chiplets (February 2024)
  • Cheeky chiplets (February 2024)
  • The Wibbly-Wobbly World of Quantum (March 2024)
  • The Wibbly-Wobbly World of Quantum (March 2024)
  • Techno Talk - Wait! What? Really? (April 2024)
  • Techno Talk - Wait! What? Really? (April 2024)
  • Techno Talk - One step closer to a dystopian abyss? (May 2024)
  • Techno Talk - One step closer to a dystopian abyss? (May 2024)
  • Techno Talk - Program that! (June 2024)
  • Techno Talk - Program that! (June 2024)
  • Techno Talk (July 2024)
  • Techno Talk (July 2024)
  • Techno Talk - That makes so much sense! (August 2024)
  • Techno Talk - That makes so much sense! (August 2024)
  • Techno Talk - I don’t want to be a Norbert... (September 2024)
  • Techno Talk - I don’t want to be a Norbert... (September 2024)
  • Techno Talk - Sticking the landing (October 2024)
  • Techno Talk - Sticking the landing (October 2024)
  • Techno Talk (November 2024)
  • Techno Talk (November 2024)
  • Techno Talk (December 2024)
  • Techno Talk (December 2024)
  • Techno Talk (January 2025)
  • Techno Talk (January 2025)
  • Techno Talk (February 2025)
  • Techno Talk (February 2025)
  • Techno Talk (March 2025)
  • Techno Talk (March 2025)
  • Techno Talk (April 2025)
  • Techno Talk (April 2025)
  • Techno Talk (May 2025)
  • Techno Talk (May 2025)
  • Techno Talk (June 2025)
  • Techno Talk (June 2025)
  • Techno Talk (July 2025)
  • Techno Talk (July 2025)
Max’s Cool Beans By Max the Magnificent Home working and flashing LEDs motorised stands that can raise it so I can work standing up (I fully intend to make use of this feature… one day soon). Stay secure and be alert Fig 1. Welcome to the pleasure dome (my office). Note all the plastic boxes crammed with cables and components under the desk. I don’t know about you, but I’m in a bit of a tizz-woz at the moment. As you may know, although I was born and bred in Sheffield, Yorkshire, England, I currently hang my hat in Huntsville, Alabama, US (I moved here for the nightlife – that’s a little Alabama joke right there). Almost a real job We subscribe to BritBox, so each weekend we get to binge-watch a week’s episodes of Good Morning Britain (GMB). The UK was put under lock-down a couple of weeks ago at the time of this writing. We aren’t under lock-down here in Alabama, although many other states are and there are rumours we might be joining them soon, but we have been advised to work from home if at all possible. Thus, I’m penning these words with numbness in my nether regions caused by sitting on a hard wooden chair at my kitchen table (the things I do for you!). Actually, I started working from home at Maxfield Mansions a couple of weeks ago. Theoretically, as a freelance technology consultant and writer, I could work from home all the time. In practice, I rent an office in a building downtown. My office is lined with bookshelves bursting at the seams with technical 58 books, science fiction books, and graphic novels – pretty much everything my wife (Gina the Gorgeous) deems to be incompatible with the ambience of our study at home. The office also forms a repository for my large hobby projects, which typically feature a lot of strange sounds and flashing LEDs, and which are also – inexplicably – denied pride of place in our family room. Quite apart from anything else, getting up at 6:30am each morning, arriving at the office some time before 8:00am, and working away till 5:00, 6:00, or 7:00pm, depending on the work I have in, almost makes it seem like I have a real job. I miss my office Working at home isn’t dreadful. I have my laptop plugged into a beautiful curved 34-inch monitor that I paid an arm-anda-leg for about four years ago, and that you can now purchase for peanuts at local electronics stores, but such is the way of the world. However, it has to be said that I really miss the setup I have in my office, with my tower computer driving three 28inch monitors that form a single desktop (Fig.1). The reason the monitor in the middle is a little higher than its companions is that it sits on one of those There’s an old joke that goes, ‘Be alert (the world needs more lerts).’ I didn’t say it was a good joke. I read with interest Alan Winstanley’s recent Net Work column (PE April 2020), in which he discussed various aspects of Internet security, including ‘The curse of cookies,’ ‘The rise of the Cookieless Monsters,’ and ‘How browsers leave fingerprints.’ In my case, I have what I consider to be a reasonably typical setup. As noted earlier, this includes a tower computer in my office and a laptop computer at home. Both are PCs running Windows 10 protected by Windows Defender augmented by Norton Antivirus. I use Outlook for my email (the app, not the browser interface), and both of my systems are synchronised via Google’s G Suite, which means that any email activity (sending, receiving, deleting, moving) on one machine is immediately reflected on the other if it is currently active. Alternatively, everything is automatically synchronised when either of the systems is powered up and Outlook is launched on that system. Similarly, all of my data files are stored in a DropBox folder, so changes made to any file (including a ‘Save’ while in the process of editing a file) on one of my systems are immediately propagated up into the DropBox cloud. If my other system is active, those changes are also promulgated from the DropBox cloud to the DropBox folder on that system. Fig 2. My Traveler identified 302 worrisome Wi-Fi networks on the 30minute drive from my home to my office. Practical Electronics | June | 2020 Fig 3. Goodly Juju and yours truly standing outside my office (I’m the one in the Hawaiian shirt). Alternatively, everything is automatically synchronised when the other system is powered up. One thing I worry about is ransomware. The idea here is that you inadvertently get some malware on your system that encrypts all your files, at which point you are held to ransom to get them back. The problem from my point of view is that any such encryption activities would be seen by DropBox as changes to my files, which would therefore be copied up into the DropBox cloud. I personally think there should be worldwide laws and rigorous enforcement for this sort of thing. When caught, the perpetrators should be hung up by their short-and-curlies and spend the rest of their lives in jail (and I say this with love). Until this happy day is upon us, once a week I disconnect whichever computer I’m working on from the Internet, perform a full virus scan, plug in an external drive, back-up the contents of my DropBox folder, to the external drive, unplug (‘air gap’) the external drive, and reconnect my computer to the Internet. Of course, there’s always a chance I’ve inadvertently backed-up a sneaky virus, but you can only do what you can do (also, DropBox has a ‘Rewind’ feature that would let me regress my account by up to 30 days). Wobbly Wi-Fi Do you use a virtual private network (VPN)? If not, why not? The problem is that when you try to do anything via the Internet, your internet service provider (ISP) can see – and potentially log – everywhere you go and everything you do. Also, if you are using an unsecured connection, nefarious players have a much easier task of monitoring your activities and gaining access to your personal information, like the names of your cats and the numbers on your credit cards. The idea behind a VPN – like NordVPN, PureVPN, or Norton Secure VPN – is that you have a client app on your home computer. When you run this app, it establishes a secure, encrypted connection between your machine and the VPN’s host servers. Now, any information that passes between your machine and your VPN’s servers looks like gibberish to any observers, including your ISP, so you are 100% secure, or are you? Practical Electronics | June | 2020 Well, if your computer is connected to the Internet via a wired (Ethernet) connection, then a VPN does indeed make you reasonably secure. The problem arises if you are using Wi-Fi in a café, hotel, airport... even in your home. The thing is that the lower layers (2 and 3) of the Open Systems Interconnection (OSI) model aren’t covered by your VPN when you are using Wi-Fi. In turn, this means that you are susceptible to rogue access points, evil twin access points, connection hijacks, man-in-the-middle attacks, and so forth. As one security expert told me, ‘This is like having a house with a state-of-the-art alarm system, but then leaving your basement door wide open.’ Happily, the guys and gals at WifiWall (https://bit.ly/2UXP6NV) have developed a technology they call WiFiWall Dome. Companies can employ a WifiWall Dome to monitor and secure all Wi-Fi activity on their premises. In the case of ‘road warriors’ who have to leave the protection of the dome, these brave lads and lasses can be provided with WifiWall Traveler units, which we can visualise as mini-domes, or bubbles. Sad to relate, WifiWall Travelers aren’t currently available for individuals, but only as part of a corporate WifiWall Dome offering. On the bright side, I happen to be in possession of my own Traveler. How? It’s obvious – I’m special (my mother always used to tell me I was ‘special,’ and I foolishly thought she intended it as a complement). It’s a scary world out there. A couple of weeks ago, prior to becoming housebound, I powered-up my Traveler, dropped it in my pocket, and headed to my office. The Traveler constantly scans any Wi-Fi networks in its vicinity. By the time I reached my office, it had identified 302 networks as being unsecured or ‘suspicious’ in one way or another (Fig.2). Of course, simply being told that there is a problem doesn’t do you much good. Thus, I’ve informed the Traveler of the MAC addresses of my tower, my laptop, my iPhone, and my iPad. The Traveler ‘sniffs’ every Wi-Fi packet that passes by, paying particular attention to any packets with my name on them (ie, any of my MAC addresses). If the Traveler sees anything untoward, it will send a command to the relevant device, instructing it to immediately disconnect from the Wi-Fi, thereby protecting my device and my precious data. But wait, there’s more, because I was chatting to the folks at WifiWall just the other day. They tell me that since so many companies have employees that are currently having to work from home, they are working furiously (‘nights as the days,’ as the old Hebrew saying goes) on a new ‘WifiWall Dome for Home’ product that will allow organisations to distribute out-of-thebox Wi-Fi security solutions to each of their employees, where these solutions will include mini-WifiWall Domes and Travelers. Simon says Before we proceed further, I would like to give a shout-out to PE reader Simon Moore, who hails from Birmingham, England (there is also a city called Birmingham and a town called Sheffield in Alabama), and who will be ‘chuffed’ to see his name in print. It was reading the first column in my Flashing LED miniseries (PE March 2020) that prompted Simon to purchase an Arduino Uno and a bunch of LEDs and start experimenting. Furthermore, it also prompted him to root through his old issues of the magazine to track down earlier columns on my BADASS Display (https://bit.ly/pe-jun20-bad). In fact, I just posted a column discussing Simon’s recent success in using an MSGEQ7 audio spectrum analyser chip in conjunction with his Arduino Uno to flash his LEDs in response to sound (https://bit.ly/2R9HdUu). Arduino for Abecedarians Speaking of the Arduino, over the past 10 years, I’ve used this little rascal as a basis for teaching electronics to a number of 59 boasts three 32-bit cores, each running at 200MHz. Furthermore, unlike the Arduino Mega, each of these cores has its own floating-point unit (FPU), which means using floating-point variables doesn’t slow things down significantly. And things just keep on getting better and better, because (a) you can program the ShieldBuddy using your regular Arduino integrated development environment (IDE), and (b) a NeoPixel library is available for the ShieldBuddy. My cup runneth over. Diggers from Down Under Fig.4. The ShieldBuddy has enough processing power to make your eyes water. people, ranging from 14 to 70+ years in age. I’m currently teaching a friend called Juju (Fig.3), although I started to call him Goodly (as in ‘Good Juju,’ meaning ‘Good Luck’), and the name seems to have stuck. Why yes, Goodly does seem to be holding a copy of my book, Bebop to the Boolean Boogie (https://amzn.to/2wOVQ8R), I wonder where that came from. Actually, Goodly is one of the few people I know who has read this book from cover-tocover and come back asking for more. Goodly and his two friends own a T-shirt printing company. They are all artists and photographers and suchlike, but they know absolutely nothing about electronics and microcontrollers. This is unfortunate because they are desperately keen to introduce flashing LED effects to their T-shirt offerings. On the other hand, they know me, and if there’s one thing I do know, it’s how to flash an LED. Based on working with Goodly, I decided to start a series of articles on my Cool Beans Blog under the umbrella name of Arduino for Abecedarians. I posted the first one a couple of days ago, starting with the fundamental concepts of voltage, current, and resistance (https:// bit.ly/343kKxy). In fact, the two images in that column showing a trio of Cool Beans proudly sporting their V, I, and R T-shirts which were created by Goodly’s colleague and my chum, Ronnie. Flashing LEDs and drooling engineers – Part 4 As you may recall from Part 1 of this miniseries, one of my hobby projects is my Inamorata Prognostication Engine (see this Instagram photo by <at>PracticalElectronics: https://bit.ly/2UUV2Y0). NeoPixels are a special form of tricolour LED that we will be looking at in my next column. The reason I mention this here is that, in addition to two knife switches, eight toggle switches, ten pushbutton switches, five motorised potentiometers, 60 six analogue meters, and a variety of sensors (temperature, barometric pressure, humidity, proximity), this little scamp has 83 NeoPixels in the upper cabinet and 116 NeoPixels in the lower cabinet. Eeek! I almost forgot (looking at the picture reminded me), there are another 155 NeoPixels powering the five monster vacuum tubes sitting on top of the engine. For my first-pass tests, I’ve been powering the various subsystems (furnace, front panels, vacuum tubes) using a motley collection of Arduino Uno and Mega boards, but I’ve known the time is fast approaching when I’m going to need a more powerful processing solution. Well, that solution just arrived in the form of a ShieldBuddy (https://bit. ly/2xLZaBq), which was created by the boffins at Hitex (hitex.com). The first thing you notice about the ShieldBuddy is that it has the same footprint as an Arduino Mega (Fig.4). OK, it’s time for you to sit up and pay attention because this bit is important. A standard Arduino Mega is based on a Microchip ATmega 8-bit processor running at 16MHz with 256KB of Flash memory and 8KB of RAM. By comparison, the ShieldBuddy is based on the Infineon Aurix TC275 processor. These bodacious beauties are normally only to be found in state-of-the-art embedded systems; they rarely make it out into the daylight of the hobbyist/maker world. The TC275’s 32-bit processor core runs at 200MHz and has 4MB of Flash memory and 500KB of RAM. Pause for a moment to compare these numbers with those of the Arduino Mega. To put this another way, the Arduino Mega’s core manages only around sixteen 8-bit instructions per microsecond (µs). By comparison, the TC275’s core has a 5ns cycle time, which means it can typically execute around 150 to 200 32-bit instructions/ µs (1µs = 1000ns). Oh wait! Did I say ‘core’ (singular)? Silly me. I meant to say that the TC275 A few weeks ago, I received an email from PE reader, David R. Humrich, who hails from Perth, Australia. Like Simon, who we introduced earlier, David told me that he’d just finished reading Part 1 of this miniseries, and that this had prompted him, in his own vernacular, to ‘get off my bum and into the vast pile of Arduino stuff I’ve collected over the years.’ A few days later, David emailed again to ask if I was familiar with the Duinotech 8x5 RGB LED Shield for Arduino (https://bit.ly/2Jz5mQ0). I wasn’t, but I have played with a somewhat similar 8x8 NeoPixel-based shield before, and I told David that an interesting little program with which he might want to experiment would be a ‘worm’ crawling around the display. The idea here is that you have one pixel for the worm’s ‘head’ and a couple more pixels for its ‘body.’ You light the head and the body with different colours, and you set the worm to randomly meander its way around the display. In addition to being visually appealing, this is a great little task that can facilitate learning a lot of C programming tricks. I sent David a link to a video of just such a program running on my 8x8 display (https://bit. ly/2R5TfOn). Let’s take the red pill Do you remember the first Matrix movie where Neo has to choose between taking the blue pill or the red pill (https://bit. ly/39AW2Wo)? As Morpheus says: ‘You take the blue pill – the story ends, you wake up in your bed and believe whatever you want to believe. You take the red pill – you stay in Wonderland, and I show you how deep the rabbit hole goes.’ Well, I’m afraid I opted for the red pill, because my dialogue with David has prompted me to plunge headfirst into my own rabbit hole to build a magnificent matrix based on ping pong balls illuminated by NeoPixels – something like the ‘Video Wall’ you can see on YouTube (https://bit.ly/3aG1itl). My first pass is going to be a small 12 × 12 = 144 ping-pong prototype. At some stage in the future, I intend to construct Practical Electronics | June | 2020 T op v iew 3 4 1 1 S ide v iew 2 3 4 1 2 3 = R ed anode = C om m on c athode = G reen anode = B lue anode 2 4 Your best bet since MAPLIN Chock-a-Block with Stock Fig.5. A regular tricolour LED. Visit: www.cricklewoodelectronics.com Or phone our friendly knowledgeable staff on 020 8452 0161 Components • Audio • Video • Connectors • Cables Arduino • Test Equipment etc, etc U p/ Off/ I nac tiv e C enter ( from U p) D own/ On/ A c tiv e C enter ( from D own) U p/ Off/ I nac tiv e Fig.6. Using a tricolour LED with an SPCO switch and with two colours for the centre position. a much bigger version. I just took delivery of five meters of 30-pixels-per-meter NeoPixel strip from Adafruit (https://bit. ly/3dOa5v4). I also received 288 ping-pong balls (I always believe in having spares) from Amazon, where they cost only $11 for a pack of 144 in the US. These aren’t game-quality balls, but they are more than good enough for what I’m going to do with them. I will, of course, be reporting further in future columns. Over the rainbow Did you ever see the video of Israel ‘IZ’ Kamakawiwoʻole singing Somewhere Over the Rainbow while playing the ukulele (https://bit.ly/34cx0f5)? In fact, it was seeing this video that prompted me to build my own ukulele, but that’s a story for another day. First, I haven’t forgotten that we looked at bicolour LEDs in my previous column (PE May 2020) and that I still owe you a sketch (the file is CB-Jun20-01.txt – now available for download from the June 2020 page of the PE website) and a video (https://bit.ly/2XiVli0) relating to the 2-terminal device. Well, the next step up the ladder is to use a tricolour component, which contains red, green, and blue LEDs (Fig.5). I’m using Chanzon 5mm RGB LEDs, which you can purchase in 100-piece packs from Amazon UK for only £5.18 (https:// amzn.to/2x1mc7l). According to the datasheet, the red diode has a forward voltage drop of 2.0 to 2.2V (we’ll assume 2.0V), while the green and blue diodes both have forward-voltage drops of 3.0 to 3.2V (we’ll assume 3.0V). Furthermore, the datasheet says that all three diodes have maximum forward current values of 20mA. From previous columns, we know that this means we’ll need to use a 150Ω current-limiting resistor in series with the red diode, and 100Ω resistors for the green and blue diodes. If we just turn our three diodes on and off, we can achieve 23 = 8 different colours: red, green, blue, yellow (red + green), cyan (green + blue), magenta (red + blue), white (red + green + blue), and black (all off). Alternatively, if we use 8-bit pulse-width modulation (PWM) to control the brightness of each diode (PE March 2020), this means each diode can have 256 different levels. Thus, mixing all three diodes allows us to achieve 256 × 256 × 256 = 16,777,216 different colours. For the purposes of this column, assuming the use of a single-pole, centrePractical Electronics | June | 2020 Visit our Shop, Call or Buy online at: www.cricklewoodelectronics.com 020 8452 0161 Visit our shop at: 40-42 Cricklewood Broadway London NW2 3ET off (SPCO) switch (PE May 2020), we will use our tricolour LED to generate only four colours: red, green, yellow, and orange. We’ll use red to indicate when the switch is Off/Inactive, green to indicate when the switch is On/Active, and either orange or yellow when the switch is in its center position to provide an indication as to its previous state (Fig.6). You can download a sketch (file CB-Jun20-01.txt – available on the June 2020 page of the PE website) and watch a video (https://bit.ly/3b6hDYx) to see all of this in action. Next time Standard tricolour LEDs can be a lot of fun, but they also have several disadvantages, not least that they each require three output pins from our microcontroller to drive them. By comparison, the NeoPixels we will be looking at in my next column each have only four pins: 0V, 5V, Data-In, and Data-Out. Each NeoPixel contains a little controller along with three 8-bit PWMs (one each for its red, green, and blue LEDs). As we will see, we can daisy-chain these little beauties together, allowing us to control hundreds of pixels with a single pin from our microcontroller. As always, I welcome your comments, questions, and suggestions. Until next time, be safe, wash your hands, drink cold lemonade (responsibly, and assuming you are of drinking age), eat hot bacon (or cheese) sandwiches, and wear Hawaiian shirts (Hey – it works for me). Cool bean Max Maxfield (Hawaiian shirt, on the right) is emperor of all he surveys at CliveMaxfield.com – the go-to site for the latest and greatest in technological geekdom. Comments or questions? Email Max at: max<at>CliveMaxfield.com 61 Max’s Cool Beans cunning coding tips and tricks I n my previous column (PE May 2020), I promised that this month we would consider how the << and >> operators perform their magic. Sad to relate, we are going to have to kick this one down the road because reader David R Humrich, who hails from Perth in Australia, emailed me with a rather interesting question relating to the use of curly brackets { }. Before we look at David’s question, let’s first remind ourselves that { } can be used to create what is called a ‘compound statement.’ This is the mechanism used by the C programming language to group multiple statements into what can be thought of as a single statement. Consider, for example, what happens when we define a function called MyFunction (): void MyFunction () { // Pretend this comment is a statement // Pretend this comment is a statement // Pretend this comment is a statement } When we call this function from somewhere else in the program, the computer ‘sees’ all of the statements in the function as forming a single logical entity. The same thing happens if we use { } along with a control statement like an if (). First, let’s assume that if the condition is true, we only wish to perform a single action, in which case we could write this as follows: if (done == true) fred = fred + 1; statement in the middle of a function – by ‘standalone,’ we mean that it’s not associated with a control statement like if () or for (). In fact, this is perfectly legal. If you wish, you can simply use { } to gather a group of statements together to make it clear to yourself and anyone else that you consider these statements to be related. These are often referred to as a ‘block,’ and using this technique may be referred to as ‘block programming.’ You can also have nested { { } } to whatever level you desire. But the really interesting thing is that, in addition to statements, your blocks can also contain variable declarations. Why is this interesting? I’m glad you asked. In my previous column, we talked about global and local variables. We noted that global variables are declared outside of any function and can be seen and modified by any function. By comparison, local variables are declared inside a function and can be seen and modified only by the function in which they are declared. We also talked about the ‘scope’ of a variable, which refers to the extent to which that variable can be seen. For example, if we declare a variable as part of a for () loop, the scope of the variable is limited to that loop (PE, May 2020). Well, if a variable is declared inside a block, its scope is that block; that is, it cannot be ‘seen’ outside of the block, even by other parts of the function in which the block resides. Consider the following ‘nonsense program’ example: int John = 6; void MyFunction () { int jane = 9; Now, C doesn’t care how many whitespace characters we use, so: { if (done == true) fred = fred + 1; // First block int bert = jane + John // More stuff } We are, of course, assuming that the variables done and fred have been declared elsewhere in the program. Now, suppose that we want to perform several actions if our condition is true. One way to do this would be as follows: { // Second block int jack = jane – John; // More stuff } if (done == true) fred = fred + 1; if (done == true) jane = jane – 1; if (done == true) bert = fred + jane; In addition to looking silly, this is inefficient because we are performing the same test three times. This example calls out to us to use a compound statement as follows: if (done == true) // Equal to above { fred = fred + 1; jane = jane - 1; bert = fred + jane; } In this case, a compound statement is both more efficient and it makes it clearer what we are trying to achieve. Back to David Returning to David’s question. He asked what would happen if one were to use { } and hence create a standalone compound 62 } Remember that I use initial uppercase and lowercase letters for my global and local variables, respectively (PE April 2020). So, John is a global variable whose scope is every function in the program, while jane is a local variable whose scope is limited to MyFunction (). By comparison, the scope of bert is limited to the first block, while the scope of jack is limited to the second block; neither can be seen outside their respective blocks. Dividing a large program into a number of smaller, well-defined functions makes it easier to test each function in isolation and reuse functions in different programs. Similarly, one advantage of using a block-based technique to limit the scope of variables is that it makes it easier to reuse those blocks in other functions and other programs. Next Time I’m not going to say what we’ll be looking at next time because things change quickly around here (I’ve learned my lesson). We’ll all just have to wait and see. Until then, have a good one! Practical Electronics | June | 2020