Silicon ChipATtiny816 Breakout and Development Board with Capacitive Touch - July 2021 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: Techno Talk by Mark Nelson
  9. Feature: Net Work by Alan Winstanley
  10. Project: ATtiny816 Breakout and Development Board with Capacitive Touch by Tim Blythman
  11. Project: Infrared Remote Control Assistant by John Clarke
  12. Project: Touchscreen Wide-range RCL Box by Tim Blythman
  13. Feature: Practically Speaking
  14. Feature: PIC n’Mix by Mike Hibbett
  15. Feature: AUDIO OUT by Jake Rothman
  16. Feature: Make it with Micromite by Phil Boyce
  17. Back Issues: Circuit Surgery by Jake Rothman
  18. Feature: Circuit Surgery by Ian Bell
  19. Feature: Max’s Cool Beans by Max the Magnificent
  20. Feature: Max’s Cool Beans cunning coding tips and tricks
  21. PCB Order Form
  22. Advertising Index

This is only a preview of the July 2021 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)
ATtiny816 by Tim Blythman Breakout and Development Board with Capacitive Touch After Microchip purchased their arch-rivals Atmel, good things started to happen. Now they are producing microcontrollers with some of the best features that we’ve come to expect from both companies. One such chip is the ATtiny816, and we’re going to describe its features and show you how to use them. W e’re fans of both the PIC and AVR families of microcontrollers for different reasons. So it’s exciting to see the two worlds come together now that the companies have merged. The new products are starting to combine the best features of the two families and the ATtiny816 is the one that we’ve chosen to use first. See the table below for a summary. One of the (few) drawbacks of this chip is that, like so many ICs these days, it’s only available in surface-mounting packages. But the 20-pin SOIC chip is not difficult to solder; however, you need some sort of ‘break-out’ board to experiment with it. Breakout board So we designed one! This board not only serves this purpose, but also contains some extra components to let you take advantage of its inbuilt capacitive touch sensing. Basically, you get four pushbuttons and/or a slider control essentially for free – there are no components to install. The PCB itself provides these controls! We’ve also made provision on the board for five LEDs, because they’re useful for debugging and indication purposes and they also look nice. Plus we’ve provided a space to mount a CP2102-based USB/serial adaptor and a USB socket to get power to the chip. PICkit 4 programming One of the thing that stops many people who are already into PICs from using AVRs is the need for a separate programmer. But now that Microchip and Atmel are one, they are starting to release AVR parts which can be programmed with the PICkit 4, and this is one of them. So if you already have the latest PICkit, you won’t need any extra development tools. You can also use the same MPLAB X software that’s used to develop code for PICs, too, as long as you have the latest version. As well as showing you how to build and hook up the development board, this article will provide in-depth information on how to program it, including some sample software that will give you a good starting point. The ATtiny816 When we first looked at the new ATtiny1607 chip’s specifications they seemed great, but unfortunately it is only available in a 24-pin VQFN package, which would be too challenging 16 for many readers.That’s just the way things are going these days. But we decided to see if they had released any other, similar chips in larger packages. After extensive searching, we discovered that the ATtiny816 has many of the same new features and is available in a 20-pin SOIC package. If you compare it to the ubiquitous ATmega328P used in the Arduino Uno, the ATtiny816 is really not that ‘tiny’. It is at the lower end of the product range in terms of RAM and Flash space but overall, its hardware features are a big step up from the ATmega328. The biggest change is the programming interface. The ATtiny816 is now programmed using the single-wire UPDI protocol, rather than the familiar four-wire SPI-compatible ICSP interface used on earlier ATmega and ATtiny chips. This is an evolution of the debugWire debugging interface. You can see a sample UPDI waveform in Scope.1. It uses a half-duplex asynchronous serial protocol. Since this programming signal is fed to the device’s reset pin, that maximises the number of available I/O pins for general purpose use. Despite using a single pin, this programming scheme is fast compared to the old ICSP system. Admittedly, the ATtiny816 only has 8kB of Flash, but the delay between pressing the ‘Program’ button and seeing the results is just a few seconds. We’ll now run through some of the outstanding features of this chip, especially those that jumped out as being bigger than we expected for such a ‘tiny’ chip! For more detailed information, refer to the device’s data sheet at: http://ww1. microchip.com/downloads/en/DeviceDoc/40001913A.pdf ATtiny816 features Number of pins .................20 SRAM ............................512 bytes Flash memory ..................8kB EEPROM .........................128 bytes Maximum clock freqrency.....20MHz ADC channels ...................12 x 10-bit Event System channels ........6 General Purpose I/O pins .....18 (17 with UPDI enabled) Timers............................4 Communications ...............USART, SPI, TWI DAC ...............................1 x 8-bit Practical Electronics | July | 2021 Do refer to the panel ‘PIC vs AVR’ at this stage, to get an idea of why we’re excited about the meeting of the two worlds. Analogue inputs The 20-pin ATtiny816 has two power pins and seventeen I/O pins (eighteen if the programming function is disabled), of which 12 can be used as inputs for the 10-bit analogue-todigital converter (ADC) module. That’s twice as many possible ADC channels as the ATmega328 on an Arduino Uno board! The ADC can also be used to sample the output of an internal temperature sensor and the DAC module output. The chip also features a true (non-PWM) 8-bit DAC. It only has a single channel and can only use pin 4 (PA6) for its output, but it can be updated at 350kHz. It can be referenced to one of five internal reference voltages, but not, unfortunately, from the 5V rail. The highest reference voltage available is 4.34V. It also has an analogue comparator which can have its inputs connected to various I/O pins or the internal DAC’s output. Event System and Configurable Custom Logic The Event System and Configurable Custom Logic (CCL) are designed to reduce the software and hardware overhead of designs using the ATtiny816. The Event System runs independently of the core once set up, and is capable of triggering events when conditions are met, similarly to how interrupts are triggered. For example, a timer overflow can trigger the ADC module to start a conversion without a software interrupt handler being needed, removing the interrupt overhead and latency. Another possible use is to provide gated timing, using an internal timer to count how long a condition (eg, an analogue comparator comparison) exists. CCL can be used to implement functions that would otherwise require external logic gates. CCL involves two programmable look-up tables, each of which takes three inputs from either external pins or internal peripherals. A truth table determines what the output value should be based on the input states, allowing the implementation of basic or relatively complex logic. A simple use case would be to mix the output from two timers to create a pulse-modulated tone. There is an Application Note describing the CCL and Event System that you can download at: http://ww1.microchip.com/downloads/ en/AppNotes/DS00002451B.pdf Communications The ATtiny816 features a USART module, SPI module and TWI module. TWI stands for ‘two-wire interface’, and is a term often used to describe a bus compatible with I 2 C and SMBus. As well as a standard serial mode, the USART module also supports SPI master mode and RS-485 mode, and the SPI module supports master and slave modes. All three of the above modules have alternative pin mappings selectable in software, which allows the three modules to operate concurrently without interfering with each other. Here’s the ATtiny816 Breakout Board connected to a PICkit 4 programmer. The UPDI protocol only uses three pins, but we’ve included a header for all eight pins to ensure that it is connected correctly. Practical Electronics | July | 2021 Scope.1: the UPDI one-wire programming signal used for this new generation of AVR chips. It appears to support reasonably fast re-programming of the chip. These new chips no longer support the old SPI-based in-circuit programming system used in older AVRs (eg, the ATmega328P used in the Arduino Uno). That frees up more pins for general purpose use. Timers The chip has three independent timer/counter modules as well as a 16-bit real-time clock (RTC) module. The RTC is suited for timekeeping tasks such as providing an application clock or generating periodic interrupts, and can be clocked from an internal low-power oscillator or an external watch crystal (for improved accuracy). This frees up the other timer/counters for duties such as input capture, waveform generation, PWM and motor control. The 12-bit Timer/Counter Type D (TCD) is specifically designed for motor control; it’s able to provide programmable dead time and respond to events from the Event System. That would be useful to react to faults (either from a digital input or the analogue comparator), shutting down the motor control output under fault conditions without the delay of an interrupt service routine. 16-bit Timer/Counter A is suited for waveform generation and has three output compare channels. It can be split into two 8-bit timer/counters, each with three output compare channels, giving the possibility of up to six waveforms being generated simultaneously. Timer/Counter B is also a 16-bit unit, and is more suited for input capture type operations such as frequency and pulse-width measurement. Its input is fed from the Event System, allowing both internal and external events to be measured. Both Timer/ Counter A and B have selectable alternative output pins. Other features An internal voltage reference provides 0.55V, 1.1V, 1.5V, 2.5V and 4.34V references for use by the ADC, DAC and analogue comparator. These are independent of the actual supply voltage. The 4.34V reference would only be usable with a 4.5-5.5V supply. The ADC can also use VDD as its reference. A CRC Flash memory scan can be set to run and detect any errors which may occur over time in the Flash memory. A non-maskable interrupt is generated if a CRC error is detected. 17 USB POWER CON3 1 ICSP CON1 +5V 1–VDD 2–PA4/T1 4 CP2102 CON4 2 3–PA5/T2 +5V 1 4–PA6/LED1 GND 5 6–PB5 CP2102 CON5 +5V GND 2 URX 3 6 7–PB4 7 8–PB3/RXD 8 9–PB2/TXD UTX 4 3 5 6 1 2 5–PA7/T3 UTX 4 9 10 5 10–PB1/T4 Vcc SCK/CLKI/AIN3 /PA3 PA5/AIN5 MISO /AIN2/PA2 PA6/AIN6 MOSI/AIN1/PA1 PA7/AIN7 RESET/UPDI/PA0 PB5 /AIN8 IC1 ATtiny 816 PA4 TOUCH 2 PA5 PC3 PC2 PB4 /AIN9 PB3/RXD/TOSC1 PC1 PB2/TXD/TOSC2 PC0 PB1/AIN10/SDA AIN11/SCL/PB 0 19 PA7 TOUCH 4 3 UPDI 4 5 18–PA2 6 18 7 17–PA1 8 17 16–UPDI 16 15–PC3/LED5 15 MISO +5V 1 14 14–PC2/LED4 13 13–PC1/LED3 2 SCK 3 4 MOSI RST 5 12 6 AVRISP CON2 GND 12–PC0/LED2 11 11–PB0 GND 20 TOUCH 3 2 GND 19–PA3 PA4/AIN4 6 TOUCH 1 +5V 1 4 URX 3 1 +5V 20–GND PB1 1k 1k 1k 1k 1k A A A A A  K LED 1  K LED 2  K LED 3  LED 4  LED 5 K K LED1 – LED5: ANY COLOUR AS REQUIRED LEDS < SLIDER > SC AT TINYBreakout ATtiny816 Board for PICkit 4 816 BREAKOUT BOARD FOR PICKIT 4 20 1 9 K A Fig.1: each pin of the chip is connected to a 3-pin header to make off-board connections easy. A programming header (CON1) is provided, along with a USB power input (CON3) and headers for a USB/serial adaptor (CON4/ CON5). Five LEDs are also included for debugging and feedback, plus the four capacitive buttons and slider. Peripheral Touch Controller Details on this module in the data sheet are fairly scant. The data sheet states that ‘the user must use the Atmel Start QTouch Configurator to configure and link the QTouch Library firmware with the application software.’ According to comments in online forums, the QTouch Library firmware can use up to 7kB of the ATtiny816’s 8kB of Flash, and this is backed up by the fact that, according to the datasheet, the PTC is only available on the 8kB ATtiny816 and not the 4kB ATtiny416. That seems excessive, and we didn’t like the idea of using the library code without fully understanding it. So, instead, we’ve written our own code to provide a basic touch interface using a similar technique. (See the Sidebar for more information about how the ‘Shared Capacitance Touch Sensing’ works, and how we implemented it). We can’t claim that our software has the sensitivity or features of the QTouch Library firmware. For example, the QTouch Library can calibrate itself, and even detect when the touch sensors may be affected by moisture. Our system can’t do that. But it seems to work well despite this, and uses a much smaller proportion of the Flash memory. Microchip has made an excellent guide to the design of capacitive touch PCB buttons, wheels and sliders. We found 18 some great ideas for what sort of touch sensors can be created from nothing more than PCB traces. It’s available at: http:// ww1.microchip.com/downloads/en/appnotes/doc10752.pdf The development board The above is by no means a complete list of all of the features of the ATtiny816; just the ones that we thought were most notable. So that you can try out some of these features and incorporate one of these chips in a ‘breadboard’ type set-up, we have designed a development/break-out board which allows you to program an ATtiny816 with a PICkit 4 and connect it up to external circuitry. The circuit diagram for this board is shown in Fig.1. Each of the 20 pins on the chip (IC1) is broken out to three separate header pins, to make connections to external circuitry easier. There are five onboard LEDs, LED1-5, in case you need them. These light up when the following outputs go high: PA6 (pin 4), PC0 (pin 12), PC1 (pin 13), PC2 (pin 14) and PC3 (pin 15) respectively. Programming header CON1 has eight pins, to suit the PICkit 4 (the PICkit 3 only had six, and generally didn’t use the sixth). Theoretically, you only need the 5V, GND and Practical Electronics | July | 2021 UPDI connections to program the chip but the other pins are wired up for completeness. USB connector CON3 is purely to provide a source of 5V power to run the board (and IC1) – note that the PICkit 4 is not (currently) capable of supplying power to the board while programming a chip in UPDI mode. CON4 and CON5 make it easy to add a USB serial interface, which could be useful for debugging. These connectors are wired up to IC1’s default UART pins. If a CP2102 module is fitted, 5V power can come from this instead of CON3. As described earlier, the PCB incorporates four touch pads and a slider at the bottom. The pads and slider are both connected to the same I/O pins to simplify the code. The pins used to sense the four buttons are PA4 (pin 2), PA5 (pin 3), PA7 (pin 5) and PB1 (pin 10) respectively. An alternative use One thing to note is the presence of CON2, which is the old-style six-pin programming header. This is not provided for programming IC1, as this chip does not support such a programming scheme. Rather, it is included so that you can potentially use this board as a way to program older AVR chips using a PICkit 4. If you need to be able to do that, you can use this PCB and simply fit CON1 and CON2 – nothing else. You can then plug the PICkit 4 into CON1 and connect CON2 to your target device (eg, using a 6-wire IDC ribbon cable). It then simply acts as an adaptor between the two connector pinouts. Construction The PCB overlay for the development/breakout board is shown in Fig.2. Use this as a guide during construction. We recommend that you fit the ATtiny816 (IC1) first. Start by applying some solder flux to its pads, then locate the IC with its pin 1 dot towards the top left, as per Fig.2. Tack solder one corner pin in place and check that all the other pins line up with their pads. If not, carefully adjust the IC by re-heating the solder joint and gently nudging it until it is located correctly. Then, tack the pin in the opposite corner and carefully solder each pin. Inspect the IC using a magnifier and remove any solder bridges using a dab of extra flux paste and some solder wick. Next, we suggest that you fit USB power socket CON3. Again, start by applying some flux to the pads, including the five small pins and the four large mounting pads. Drop the part in place and move it around until the plastic locating pins drop into the holes on the PCB. Then check that the Parts list – ATtiny816 development board 1 double-sided PCB coded 24110181, 99mm x 77m available from the PE PCB Service 1 CP2102 USB/Serial adaptor module 1 8-pin right-angle pin header (CON1) 1 2x3-pin header (CON2, optional) 1 mini type-B SMD USB socket (CON3) 1 6-pin header (CON4) OR 1 6-way female pin socket (CON5) 20 3-way pin headers (may be snapped from two 40-pin headers) 4 2-pin headers (optional; for external touchpads) Semiconductors 1 ATtiny816 8-bit microcontroller, wide SOIC-20 (IC1) 5 3mm LEDs, various colours (LED1-LED5) Resistors (all 1/4W or 1/2W 1% or 5%) 5 1kΩ five small signal pins line up correctly with the pads and tack one of the large mounting pins in place. Re-check the signal pin alignment, then solder the other three large mounting pins, followed by the five small signal pins, which are partially hidden under the socket body. We have put slightly enlarged pads on the PCB to simplify soldering them. You should just need to touch the iron (with a bit of solder on the tip) to each pad and it will flow onto the pins. Only the two outside pads at the back of the USB socket are needed, as this socket is only used for power. The other pins may be soldered for completeness, but you must ensure they are not bridged to any pins, as they may stop the upstream USB socket from working correctly. If you have managed to bridge the pads, then use flux paste and solder wick to remove the bridges. Fit the resistors next, then the LEDs. Ensure that the cathode flat of each LED goes to the right (adjacent to the ‘K’ mark), and that the longer anode leg is to the left. Solder right-angle programming header CON1 in place next. You should only fit one of CON4 or CON5. Fit a vertical male header for CON4 if you want to mount a CP2102 module on the board permanently. Fit a vertical female header for PIC vs AVR We should explain the pros and cons of AVR vs PICs, as the ATtiny816 combines many of the advantages of both architectures. The main advantage that AVRs always had over 8-bit PICs was the use of a high-speed, high-efficiency RISC CPU core. It can process one instruction per clock and most AVRs can run with a clock up to 20MHz. So you could easily execute 20,000,000 instructions per second with a typical AVR chip. On the other hand, most 8-bit PICs execute one instruction for every four clock cycles. So even though some of them can run with a clock speed up to 48MHz, that equates to the execution of just 12,000,000 instructions per second – barely half that of the AVRs. Also, the AVR instruction set lends itself much better to compilergenerated code, so you generally get excellent results using the free avr-gcc ‘C’ compiler, whereas PIC compilers used to cost money (they still do if you want all their features) and usually are far less efficient, generating larger and slower code by comparison. On the other hand, many PICs contain internal PLLs which allow them to run at maximum speed without an external crystal or Practical Electronics | July | 2021 resonator. By comparison, AVRs are generally more limited. They mostly lack PLLs, but they usually do have one or more internal resonators. However, these may not allow them to operate at full speed. For that, you generally do need extra external components. Another advantage of PICs over AVRs is that they are programmed in one pass, with a single HEX file, whereas AVRs have a separate set of EEPROM ‘fuses’ which need to be programmed to access all the device’s features. Not only is this a separate step, but getting it wrong can effectively ‘brick’ the chip. And even if you get it right, you may have difficulty reprogramming the chip afterwards, as the programming interface was traditionally clocked based on the crystal and oscillator settings. So there is a bit of a ‘chicken-and-egg’ type problem programming many AVRs. Finally, PICs were usually cheaper than similarly-specced AVRs, and often came with a much more full set of internal hardware peripherals. But that’s all changing now that Microchip is starting to add their generous hardware to AVR cores. 19 R1 R2 R3 R4 R5 1k 1k GND 19-PA3 3-PA5 18-PA2 IC1 ATtiny816 4-PA6 5-PA7 6-PB5 7-PB4 CON1 ICSP 1k VDD 2-PA4 1 DAC 1k 1k USB POWER 17-PA1 16-UPDI 15-PC3 LED5 14-PC2 LED4 RX 8-PB3 13-PC1 LED3 TX 9-PB2 12-PC0 LED2 10-PB1 11-PB0 PA4 1 PA5 2 3V3 DTR RX TX GND 5V K PA7 3 24110181 K AVR ISP K SILICON18101142 CHIP CON5 CP2102 CON2 K CON4 CP2102 K 3V3 DTR RX TX GND 5V LED1 LED2 LED3 LED4 LED5 CON3 PB1 4 < SLIDER > 24110181 ATtiny816 Breakout for PICKIT4 Fig.2: use this overlay diagram and photo as a guide during construction. You can choose to leave off parts that you don’t need. The most interesting feature of this board is the network of tracks at the bottom which provide the same function as four pushbuttons and a slider but with no actual parts needing to be soldered to the board. CON4 or a right-angle female header for CON5 if you want to be able to plug a CP2102 module into the board. As noted above, you will probably not fit CON2 to the board. You would only do so if you are building it as a simple programming adaptor. In that case, CON1 and CON2 would normally be the only parts installed (possibly also CON3, if you want to be able to power the target from USB 5V). The 20 3-way male headers are the last essential components to fit. There is one for each pin on IC1. We find it easiest to solder one pin of each group before the rest; this allows the header to be adjusted if it is not quite vertical, before soldering the remaining pins. You may also choose to leave the header pads vacant if you don’t wish to do any prototyping, or you wish to solder components directly to the pads. The headers marked PA4, PA5, PA7 and PB1 allow you to connect to external touch-pads. These are not necessary if you will be using the onboard touchpads. We recommend not fitting them until after you have experimented with the PCB touch pads – extra connections will affect the pads’ capacitance and touch sensitivity. Installing the software You will need to install Microchip MPLAB X and the XC8 compiler on your system to compile the software and upload it to the chip. These are both free downloads from Microchip. But note that to get the full optimisations from XC8, you may need to pay for a license (not needed for this project. The MPLAB X IDE (integrated development environment) is cross-platform software that is available for Windows, macOS and Linux, so download the version appropriate for your system from: www.microchip.com/mplab/mplab-x-ide It allows you to edit and compile code, and upload the compiled code (HEX file) to the target chip – in this case, the ATtiny816. The XC8 compiler converts the C code into a HEX file (and optionally also an assembly language file). This is integrated with MPLAB X, but you download and install it separately. When you install the MPLAB X IDE, it will also install drivers for the PICkit 4, if you don’t have them already. 20 Ensure the PICkit 4 is plugged into your computer so that MPLAB X can identify it. By the way, this software can also be used to program PICs and some other Atmel chips. To use the AVR/PICkit 4 combination, you need to have MPLAB X version 5.05 or newer and XC8 version 2.00 or newer. Compilers, including XC8, can be downloaded from: www.microchip.com/mplab/compilers You will also need to download the sample software for this project, available from the July 2021 page of the PE website. Extract the zip package to a convenient location. Compiling the demo code Once both packages are installed, launch the IDE, then use the File>Open Project menu option to locate and load the sample software that you extracted earlier. Next, right-click on the project name which appears in the left-hand pane, and select Properties. Ensure Conf:[default] is selected, and check that your PICkit 4 is showing and selected under Hardware Tool, and that XC8 (v2.00) is selected under Compiler Toolchain. If all this is correct, click OK, and connect the ATtiny816 PCB to the PICkit 4 via the 8-way header, ensuring the arrows marking pin 1 line up. You will also need to ensure that the PCB is powered, either from a CP2102 module or via the Mini-B USB socket. Now click the button labelled ‘Make and Program Device’. This looks like an IC with a green arrow pointing down. The software should compile and then upload the program to the board. We have also provided a HEX file in the download package, which can be flashed directly to the ATtiny816 using the IPE (integrated programming environment) which is installed alongside the IDE, in case you are not interested in the code itself and don’t want to compile it. The demo code The sample software we have written demonstrates some of the exciting capabilities of the ATtiny816 chip. It includes Practical Electronics | July | 2021 Shared Capacitance Touch Sensing Touch sensing technology allows simple and intuitive interfaces to be developed. While the touchscreens on our mobile phones are not quite the same thing as what we are demonstrating here, they use a similar phenomenon. The human body has a measurable capacitance, and we can change the intrinsic capacitance of a circuit by coming in contact with it. It may not even be a direct electrical contact; this effect works even when capacitively coupled across an insulating medium. Hence the two advantages of the touch sensor: there does not need to be direct contact between the circuit and user; and the actual sensor is nothing more than a means of coupling to the user, in effect, an antenna. In practice, the sensor is usually a PCB trace, perhaps matched by a second trace to shape and isolate the touch zone. This means the touch sensor has negligible extra manufacturing cost if the design already includes a PCB. We implemented two different touch sensing algorithms in our demo code. The first was inspired by some Arduino code dating from over ten years ago, which will work with any digital I/O pin. It measures the time constant of an RC network consisting of a pin’s internal pull-up resistance and the connected capacitance, including a finger if it is near the pad. While simple to implement, it isn’t very sensitive, with variations between the touch and no-touch state only differing by a count of one or two units. We haven’t used the code at all in our demonstration, but have left it in the touch.c file supplied, for interest’s sake. The second method, which the QTouch Library firmware also uses, is called ‘shared capacitance sensing’. It allows the value of an unknown capacitor to be determined using a known capacitance. Imagine a capacitor C1, with a known capacitance. We fully discharge this capacitor by shorting both ends to ground. Next, we take an unknown capacitor Cx and charge it up to a known voltage VS by connecting one end to ground and the other to a supply of VS. Now, we disconnect the capacitors from their respective supplies and connect them in parallel. This shares the charge between them, hence the name of the method. Once the voltages have settled, we separate the capacitors and measure the voltage across either of them (which will be the same), and call this VF. Starting with the capacitor charge formula Q=CV, and knowing that: Q1 = 0 (b ecause V1=0) and Qx = Cx.Vs thus: Qtotal = Cx.Vs We can solve this to give: Cx/ C1 = VF/ (VS- VF) From this, we can see that the larger CX is, the larger VF (our measured voltage) will be. In practice, for touch sensing, the exact value of CX does not need to be known. We just need to be able to detect a measurable change in its value. In our ATtiny816, C1 is the ADC module sampling capacitor, which has a value of around 10pF. CX is the capacitance of the item in contact with the sensor. Typical values for the human body are around 100pF, so we functions to drive I/O pins, use the onboard DAC and ADC, the UART serial port, some basic real-time clock functions and capacitive touch sensing. The code to do this is contained within the ‘main’ function of the main.c file, along with separate ‘library’ files which perform specific functions. We were inspired by the Arduino language to create some similar intuitively named functions for these purposes. By default, the code continually monitors the touch pads on the PCB. If the pads are touched, then an LED lights up – LED2 lights for pad 1, LED3 for pad 2 and so on. The slider (which uses the same I/O pins as the pads) position is also read, and the position is displayed using can see that this is at a reasonable level for detecting with our method, keeping in mind that the touch circuitry will add extra capacitance to this amount. To discharge C1, we instruct the ADC to take a sample from its internal ground reference. To charge up CX, we set the analogue input pin to have its internal pull-up current source switched on (this is actually left on in between samples, so that the circuit is always ready). This brings Cx up to Vs. C1 will be disconnected from ground after its ADC sample is complete, and we disconnect CX from its supply by disabling the internal pull-up current. The capacitors are automatically connected together by taking an ADC sample of the pin, and the ADC reading becomes the voltage reading (VF), which we could put into the above formula if we wanted to work out the value of the connected capacitance. In practice, we take repeated ADC readings, and when we see a rise above a certain threshold, we report that a touch has occurred. Our prototype circuit gives readings of around 680 ADC counts while idle, rising to 900 when a touch occurs. These are equivalent to capacitances of around 20pF rising to around 100pF during a touch event. The slider uses a similar method, but combines the readings from several adjacent pins. In essence, the closer your finger is to one of the junctions in the slider, the more capacitance is detected at that point. By performing a linear interpolation between the pin positions in proportion to their measured capacitance, we can calculate the approximate touch location. LED1. It lights at a low intensity with a finger touching the left-hand end and with high intensity at the right-hand end. The granularity that can be achieved can be demonstrated by gradually moving a finger along the slider. This code also demonstrates the use of IC1’s internal DAC, which is used to fade LED1 in line with the touched position on the slider; it is not pulse-width modulated. Note that LEDs2-5 will also light up when the slider is used (and If you want to experiment with programming other AVR ICs (such as the ATmega328 on an Arduino board), you can also use our PCB as an ICSP breakout for the PICkit 4. It appears configuration fuse programming is not supported yet. (We tried!) Practical Electronics | July | 2021 21 The challenges of working with a new micro With any new microcontroller, especially one that’s using a new compiler and programmer combination, you’re likely to run into a few minor roadblocks. Here’s what we found when we first started programming the ATtiny816 using MPLAB X. For a start, the XC8 compiler has traditionally been for PICs only, but they have now added AVR capability (both Microchip’s XC8 and Atmel’s avr-gcc are based on the GNU gcc compiler). As a result of this history, the XC8 User Guide is PIC-oriented, and some of the documentation within does not apply to Atmel parts. For example, the syntax it gives for interrupt service routines (ISRs) is PIC-specific. The manual does not explain how to set up an ISR on an AVR part. Since we are using interrupts to handle the UART’s serial receive event, we had to resolve this. The code we were copying directly from the XC8 User Guide was being rejected by the compiler. Eventually, we found some code from an Atmel Studio project (the software which was used to program AVRs before Microchip’s takeover). This compiled successfully. It has this format: ISR(USART0_RXC_vect){} We ran into similar problems trying to program the AVR’s configuration fuses (see the PIC vs AVR panel for an explanation of fuses). The tool for generating the micro’s configuration bits creates code in the same style as for a PIC microcontroller, but again, it does not compile. Like with the ISR, we found some Atmel Studio code that worked instead. It looks like this: FUSES = { .APPEND = 0, .BODCFG = ACTIVE_DIS_gc | LVL_BODLEVEL0_gc | SAMPFREQ_1KHz_gc | SLEEP_DIS_gc,.BOOTEND = 0, .OSCCFG = FREQSEL_20MHZ_gc, .SYSCFG0 = CRCSRC_NOCRC_gc | RSTPINCFG_UPDI_gc, .SYSCFG1 = SUT_64MS_gc, .WDTCFG = PERIOD_OFF_gc | WINDOW_OFF_gc}; In any case, we have commented out this section in our code, so that the programmer will not touch the fuse settings on the chip. The chip’s default fuse values are suitable for our project, so leaving them as-is is a lower risk strategy. We also struggled to find the device I/O header file, which tells the compiler where all the various special registers are located in RAM and provides various handy macros for controlling I/O pins and so on. Eventually, we found it on our system in this folder: C:\ProgramFiles(x86)\Microchip\xc8\v2.00\dfp\include\ avr\iotn816.h We aren’t sure what ‘dfp’ stands for. We also found, while experimenting with the compiler optimisation settings, that the code did not compile at all on optimisation level zero (no optimisation), but did so at level one. The error message said that the vector table had been truncated, which suggests that the compiled code may not fit in the available Flash space, but it only uses 29% of Flash space with optimisation enabled, so that seems like a huge difference. With all the above in mind, we eventually got the code to compile and work. The MPLAB X support for AVRs is still at a beta stage, so we expect many of these problems will disappear over the next few months as support matures. LED1 will change brightness when the pads are touched), since they are sharing the I/O pins on the microcontroller. Serial debugging data If you have a CP2102 USB-Serial module connected to CON4, you can also see the raw analogue touch values that 22 Fig.3: example output of the ADC sample values corresponding to the sensed relative capacitance for each of the four pushbuttons and the slider. You can see that the four first values are fairly steady over time, while the last value is zero. If you bring your finger near or touch a button, one of the values will increase, indicating the added capacitance from your finger. are being sampled. Open a serial terminal program (eg, the Arduino Serial Monitor, PuTTY or TeraTerm) at 9600 baud, select the appropriate COM port and you will see the data being sent to the terminal. If you have one of the more recent versions of the Arduino IDE (we are using version 1.8.5), you can also use its Serial Plotter function to show the values as a graph. This can be found under the Tools menu. The first four numbers printed on each line are the raw ADC readings from each touchpad on a scale from 0 to 1023 (see Fig.3). You can use this information, along with the formulas from the sidebar about Shared Capacitance Touch Sensing, to estimate the actual capacitance connected to the pin before, during and after a touch has occurred. The final number is the calculated slider value, which is zero if no touch has occurred and in the range 20 to 80 if a touch is occurring. The values are arbitrary but demonstrate the resolution of the slider pad. If you find that touches are not being consistently and accurately detected, then the threshold and baseline levels in the program may need to be adjusted. A touch is detected when the raw ADC value rises above the baseline plus threshold value, so this should be set about halfway between the touched and untouched ADC values. Conclusion We found the ATtiny816 to be a capable device, and it was easy to work with once we had figured out the quirks of the compiler. But we were a bit disappointed that we could not think of good ways to demonstrate the other features of the microcontroller, such as the CCL or Event System. The 20MHz internal oscillator mode is rated to work down to around 4.5V supply voltage, but we did some tests with a 3.3V supply and found most things seemed to work adequately. But the performance does degrade slightly. For example, the ADC results appeared to drift more than with a 5V supply. Another ATtiny series chip (ATtiny85), has even had a USB stack ported to it, so if the same can be done for the ATtiny816, then we can expect some interesting projects to appear. The small amount of RAM and Flash memory appears to be limiting, but we expect this microcontroller will make a great peripheral IC to another micro, and we look forward to using it for other projects. Reproduced by arrangement with SILICON CHIP magazine 2021. www.siliconchip.com.au Practical Electronics | July | 2021