Audio Circuit: Single Frequency Output Selection

Audio Circuit Driven by Op Amp, GY-9833 frequency synthesizer, and Arduino

Above is the circuit I mentioned earlier had been intending to design with a small 3W speaker driven by an LM386 op amp driven by an AD9833 frequency synthesizer chip, driven by SPI (sourced in the schematic from an Arduino Uno).

I thought designing and testing this simple circuit would only take an hour or two. But I got hung up for a lot of hours because, in the breadboard, I was getting weird spurious signals in the output when I had the the circuit set to certain volume levels, and I couldn’t figure out what the problem was. In the end, the problem was fixed by putting a large capacitor across +5V and AGND. After that, this output sounded pure and pleasant, testing with 1000Hz, 1500Hz, and 2000Hz signals. I do not know if it is really necessary to use a capacitor quite that big, but I didn’t feel like doing additional testing.

I had thoughts to turn the circuit into a PCB, though it would be through-hole (easier to assemble) and not a miniature surface-mount design like would be seen in a commercial application. This would be around 6cm x 5cm, with the speaker plugging in on the right pins and the Arduino plugging in on the left header. The GY-9833 module would slide onto the center pins and could be soldered on to them.

I can provide design files later after I finish laying out the traces. I can also post some FlashForth code later.

LM386 Audio Amplifier

Learning how to use the LM386 Audio Amplifier IC — a “minimum parts” circuit.

I was pondering how I was going to amplify the signal coming out of my AD9833 signal generator module, to drive my MakerHawk 3 watt, 8 ohm speaker. Then I found an LM386 IC in my box of assorted op-amps. I found this amplifier to be easy to use, especial with the example “minimum parts” circuit in the data sheet:

Minimum parts circuit from LM386 data sheet. Pins 1, 7, and 8 can be left open if you are okay with the default gain setting of 20.
The LM386 pinout

In the picture at the top of this post, you can see the AD9833 module, but I’m actually trying out the amplifier chip by driving it with a desktop signal generator, which is connected to the leads on the left. With the signal generator set to as little as 100mV p-p, I had no trouble hearing the sound on the speaker with 1khz, 1.5 khz, and 2 khz tones. The sound was quiet and distorted at 500 Hz and lower, but that would be expected of such a small speaker.

The Uno in the picture is not providing the LM386 input signal in this test, but is simply providing the 5V supply voltage.

Some caveats; the LM386 requires at least 4V supply voltage, which is a problem for folks who want to use their microcontrollers with a lower 3.3 V supply only. Also, I think the AD9833 generated a 700 mV p-p signal when I tried it last week, which I believe fits just inside the LM386’s range of minimum -4V and maximum +4V input signal — probably you will want a voltage divider or volume control to attenuate the signal some.

AD9833 Signal Driven by Flash Forth

400 Hz signal from an AD9833 module, initialized by 328P MC running FlashForth

Having figured out how to configure the parameters of the SPI bus, and transmit bytes, I wanted then drive my AD9833 module, which is a frequency generator.

Arduino Uno running FlashForth connected to a GY-9833 module, which is a dev module for the AD9833 signal generator chip

I determined from the datasheet that I would need the SCLK signal to be high on idle, and to sample on the leading edge. Also, fsync needs to go low before the data is transmitted.

Timing Diagrams for AD9833 chip

Here are the FSYNC, SCK, and data signals on a scope:

FSYNC signal is yellow, SCK signal is green, and data signal is purple

I actually had to study these signals for a few minutes because at first the initialization code was not working. I released that there was a bug in my code such that the fsync signal was inverted. That was easy to fix.

The above data translates to this example initialization data from the programmer’s guide:

Zooming in, you can see the first byte, 0x21:

First byte’s worth of signals

With sampling on leading edge of SCK (green signal) we have 00100001, i.e., 0x21.

Here is the code so far:

\ ad9833.fs

\ Copyright 2021 Christopher Howard

\ Licensed under the Apache License, Version 2.0 (the "License");
\ you may not use this file except in compliance with the License.
\ You may obtain a copy of the License at

\     http://www.apache.org/licenses/LICENSE-2.0

\ Unless required by applicable law or agreed to in writing, software
\ distributed under the License is distributed on an "AS IS" BASIS,
\ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\ See the License for the specific language governing permissions and
\ limitations under the License.

ad9833
marker ad9833

: init-spi ( -- )
    \ set data direction bits
    DD_OUT DD_MOSI lshift
    DD_OUT DD_SCK  lshift or
    DD_OUT DD_SS   lshift or DDR_SPI mset
    \ Setup control register
    1           SPR0 lshift
    0           SPR1 lshift or \ fck/16
    CPHA_SMPLED CPHA lshift or
    CPOL_HIDLE  CPOL lshift or
    MSTR_MSTR   MSTR lshift or 
    DORD_MSB    DORD lshift or
    SPE_ENAB    SPE  lshift or
    SPIE_DISAB  SPIE lshift or SPCR c!
;

: init-fsync [ DD_OUT #4 lshift ] literal DDRD mset ;

: fsync-low [ 1 #4 lshift ] literal PORTD mclr ;

: fsync-high [ 1 #4 lshift ] literal PORTD mset ;

: demo-400hz
    init-spi
    init-fsync
    fsync-low
    $21 tx-spi $00 tx-spi
    $50 tx-spi $c7 tx-spi 
    $40 tx-spi $00 tx-spi 
    $c0 tx-spi $00 tx-spi 
    $20 tx-spi $00 tx-spi
    fsync-high
;

\ Only for viewing the SPI signals
: test-demo begin demo-400hz 1 ms again ;

First you have to load this ad9833 code:

\ ff-328p.fs

\ Copyright 2021 Christopher Howard

\ Licensed under the Apache License, Version 2.0 (the "License");
\ you may not use this file except in compliance with the License.
\ You may obtain a copy of the License at

\     http://www.apache.org/licenses/LICENSE-2.0

\ Unless required by applicable law or agreed to in writing, software
\ distributed under the License is distributed on an "AS IS" BASIS,
\ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\ See the License for the specific language governing permissions and
\ limitations under the License.

ff-328p
marker ff-328p

\ General I/O port addresses

$25 constant PORTB
$28 constant PORTC
$2b constant PORTD

\ Data Direction Registers

$24 constant DDRB
  1 constant DD_OUT
  0 constant DD_IN
$2a constant DDRD

\ DDR for SPI comms

$24 constant DDR_SPI
$2 constant DD_SS
$3 constant DD_MOSI
$5 constant DD_SCK

\ SPI control register

$4c constant SPCR
$0 constant SPR0 \ SPI Clock Rate Selector bits
$1 constant SPR1 \ (see table 18-5 in 328P datasheet)
$2 constant CPHA \ Clock Phase bit
  1 constant CPHA_SMPTRL \ sample on trailing edge of SCK
  0 constant CPHA_SMPLED \ sample on leading edge of SCK
$3 constant CPOL \ Clock Polarity bit
  1 constant CPOL_HIDLE \ SCK high when idle
  0 constant CPOL_LIDLE \ SCK low when idle
$4 constant MSTR \ Master/Slave Select bit
  1 constant MSTR_MSTR \ master mode
  0 constant MSTR_SLAVE \ slave mode
$5 constant DORD \ Data Order bit
  1 constant DORD_LSB \ LSB transmitter first
  0 constant DORD_MSB \ MSB transmitted first
$6 constant SPE \ SPI Enable bit
  1 constant SPE_ENAB \ SPI enabled
  0 constant SPE_DISAB \ SPI disabled
$7 constant SPIE \ SPI Interrupt Enable bit
  1 constant SPIE_ENAB \ SPI Interrupt Enabled
  0 constant SPIE_DISAB \ SPI Interrupt Disabled

\ SPI status register

$4d constant SPSR 
$0 constant SPI2X \ Double SPI Speed Bit
$6 constant WCOL \ Write COLlision Flag
$7 constant SPIF \ SPI Interrupt Flag

\ SPI Data Register (i/o port)

$4e constant SPDR

: tx-spi ( c -- )
    SPDR c! begin SPSR c@ 1 SPIF lshift and until
;

FlashForth SPI (328P)

example 0: byte 0xDE sent using SPI (green) and SCK driver signal (yellow). Common SPI configuration.

I wrote some some FlashForth code to be able to initialize the SPI system on the 328P, and transmit bytes – a more thorough version of what I had done earlier with Arduino-FVM. It basically amounted to a list of SPI-related register and bit constants.

\ ff-328p.fs

\ Copyright 2020 Christopher Howard

\ Licensed under the Apache License, Version 2.0 (the "License");
\ you may not use this file except in compliance with the License.
\ You may obtain a copy of the License at

\     http://www.apache.org/licenses/LICENSE-2.0

\ Unless required by applicable law or agreed to in writing, software
\ distributed under the License is distributed on an "AS IS" BASIS,
\ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\ See the License for the specific language governing permissions and
\ limitations under the License.

ff-328p
marker ff-328p

\ General I/O port addresses

$25 constant PORTB
$28 constant PORTC
$2b constant PORTD

\ Data Direction Registers

$24 constant DDRB
  1 constant DD_OUT
  0 constant DD_IN

\ DDR for SPI comms

$24 constant DDR_SPI
$2 constant DD_SS
$3 constant DD_MOSI
$5 constant DD_SCK

\ SPI control register

$4c constant SPCR
$0 constant SPR0 \ SPI Clock Rate Selector bits
$1 constant SPR1 \ (see table 18-5 in 328P datasheet)
$2 constant CPHA \ Clock Phase bit
  1 constant CPHA_SMPTRL \ sample on trailing edge of SCK
  0 constant CPHA_SMPLED \ sample on leading edge of SCK
$3 constant CPOL \ Clock Polarity bit
  1 constant CPOL_HIDLE \ SCK high when idle
  0 constant CPOL_LIDLE \ SCK low when idle
$4 constant MSTR \ Master/Slave Select bit
  1 constant MSTR_MSTR \ master mode
  0 constant MSTR_SLAVE \ slave mode
$5 constant DORD \ Data Order bit
  1 constant DORD_LSB \ LSB transmitter first
  0 constant DORD_MSB \ MSB transmitted first
$6 constant SPE \ SPI Enable bit
  1 constant SPE_ENAB \ SPI enabled
  0 constant SPE_DISAB \ SPI disabled
$7 constant SPIE \ SPI Interrupt Enable bit
  1 constant SPIE_ENAB \ SPI Interrupt Enabled
  0 constant SPIE_DISAB \ SPI Interrupt Disabled

\ SPI status register

$4d constant SPSR 
$0 constant SPI2X \ Double SPI Speed Bit
$6 constant WCOL \ Write COLlision Flag
$7 constant SPIF \ SPI Interrupt Flag

\ SPI Data Register (i/o port)

$4e constant SPDR

: tx-spi ( c -- )
    SPDR c! begin SPSR c@ 1 SPIF lshift and until
;

Here are some examples:

\ a common configuration
: init-spi-ex0 ( -- )
    \ set data direction bits
    DD_OUT DD_MOSI lshift
    DD_OUT DD_SCK  lshift or
    DD_OUT DD_SS   lshift or DDR_SPI c!
    \ Setup control register
    1           SPR0 lshift
    0           SPR1 lshift or \ fck/16
    CPHA_SMPLED CPHA lshift or
    CPOL_LIDLE  CPOL lshift or
    MSTR_MSTR   MSTR lshift or 
    DORD_MSB    DORD lshift or
    SPE_ENAB    SPE  lshift or
    SPIE_DISAB  SPIE lshift or SPCR c!
;

\ send byte repeatedly with 1 ms delay in between
: rpt-spi-char ( c -- )
    begin dup tx-spi 1 ms again ;

init-spi-ex0  ok<#,ram> 
$de rpt-spi-char
example 0: a common configuration

Here we are transmitting with a 1Mhz clock (fck/16). We have the SCK set to idle on low voltage, with the sample on the lead edge. This means when you see the yellow signal jump up, look down at the green line to see the bit – high for 1 and low for 0. Here we have 11011110, i.e., value 0xDE in Most Significant bit (MSB) order, as expected.

In this slight variation, we sample on the trailing edge of the SCK signal instead:

\ with clock phase sampled on trailing
: init-spi-ex1 ( -- )
    \ set data direction bits
    DD_OUT DD_MOSI lshift
    DD_OUT DD_SCK  lshift or
    DD_OUT DD_SS   lshift or DDR_SPI c!
    \ Setup control register
    1          SPR0 lshift
    0          SPR1 lshift or \ fck/16
    CPHA_SMPTRL CPHA lshift or
    CPOL_LIDLE CPOL lshift or
    MSTR_MSTR  MSTR lshift or 
    DORD_MSB   DORD lshift or
    SPE_ENAB   SPE  lshift or
    SPIE_DISAB SPIE lshift or SPCR c!
;
example 1: sample on trailing edge of SCK

So to determine the bit value, you must look at the value below where the yellow SCK signal falls down to low.

Another variation is to go back to sampling on the leading edge, but have SCK idle on high, so again we must look for the SCK signal to fall down to low.

\ clock polarity high on idle
: init-spi-ex2 ( -- )
    \ set data direction bits
    DD_OUT DD_MOSI lshift
    DD_OUT DD_SCK  lshift or
    DD_OUT DD_SS   lshift or DDR_SPI c!
    \ Setup control register
    1           SPR0 lshift
    0           SPR1 lshift or \ fck/16
    CPHA_SMPLED CPHA lshift or
    CPOL_HIDLE  CPOL lshift or
    MSTR_MSTR   MSTR lshift or 
    DORD_MSB    DORD lshift or
    SPE_ENAB    SPE  lshift or
    SPIE_DISAB  SPIE lshift or SPCR c!
;
example 2: SCK idle on high

In another variation, we can go back to the common configuration, with SCK idle on low, and looking for the leading edge (rise in SCK signal), but instead transmit the bits in Least Significant Bit (LSB) order:

\ LSB data order
: init-spi-ex3 ( -- )
    \ set data direction bits
    DD_OUT DD_MOSI lshift
    DD_OUT DD_SCK  lshift or
    DD_OUT DD_SS   lshift or DDR_SPI c!
    \ Setup control register
    1           SPR0 lshift
    0           SPR1 lshift or \ fck/16
    CPHA_SMPLED CPHA lshift or
    CPOL_LIDLE  CPOL lshift or
    MSTR_MSTR   MSTR lshift or 
    DORD_LSB    DORD lshift or
    SPE_ENAB    SPE  lshift or
    SPIE_DISAB  SPIE lshift or SPCR c!
;
example 3: transmit bits in LSB order

Now you see the bits are 01111011, which reverses to 11011110, i.e., 0xDE.

Our final demonstration variation is the common configuration but at a much slower speed, fck/128, or 125,000 bits/sec in our case.

\ much slower speed
: init-spi-ex4 ( -- )
    \ set data direction bits
    DD_OUT DD_MOSI lshift
    DD_OUT DD_SCK  lshift or
    DD_OUT DD_SS   lshift or DDR_SPI c!
    \ Setup control register
    1           SPR0 lshift
    1           SPR1 lshift or \ fck/128
    CPHA_SMPLED CPHA lshift or
    CPOL_LIDLE  CPOL lshift or
    MSTR_MSTR   MSTR lshift or 
    DORD_MSB    DORD lshift or
    SPE_ENAB    SPE  lshift or
    SPIE_DISAB  SPIE lshift or SPCR c!
;
example 4: slower speed

You see the waveform is the same except one SCK cycle is taking a full 8 microseconds.

First Foray into FlashForth for AVR

Arduino-FVM was a nice, easy introduction to Forth on AVR/Arduino, and has a few advantages as a Forth implementation. But I was interested in something more developed and full-featured. So today I got FlashForth installed on a 328P MC, running on an Arduino Uno.

Installing FlashForth on AVR requires setting fuse bits as well as burning a new flash image, so I had to wire up my Nano ArduinoISP programmer again. Pulling this off required mixing details from the ArduinoISP tutorial, my previous post on ArduinoISP, and instructions from the FlashForth Web site, none of which were quite sufficient information taken individually.

I used the precompiled 328P hex flash image that is included in the FlashForth git repo. I intend at some point to compile the source, but I needed to get over the initial hurdle of seeing if I could get FlashForth to run on an MC at all, and if I liked it. This was the avrdude call which worked for me:

christopher@theoden ~/Repos/flashforth/avr/hex$ avrdude -p m328p -c stk500v1 -P /dev/ttyUSB0 -b 19200 -e -u -U flash:w:328-16MHz-38400.hex:i -U efuse:w:0xff:m -U hfuse:w:0xda:m -U lfuse:w:0xff:m

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: erasing chip
avrdude: reading input file "328-16MHz-38400.hex"
avrdude: writing flash (32524 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 32524 bytes of flash written
avrdude: verifying flash memory against 328-16MHz-38400.hex:
avrdude: load data flash data from input file 328-16MHz-38400.hex:
avrdude: input file 328-16MHz-38400.hex contains 32524 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 32524 bytes of flash verified
avrdude: reading input file "0xff"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xff:
avrdude: load data efuse data from input file 0xff:
avrdude: input file 0xff contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xda"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xda:
avrdude: load data hfuse data from input file 0xda:
avrdude: input file 0xda contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xff"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xff:
avrdude: load data lfuse data from input file 0xff:
avrdude: input file 0xff contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

Here is the logon using picocom:

christopher@theoden ~/Repos/flashforth/avr/hex$ picocom -b 38400 -c /dev/ttyACM0picocom v3.1

port is        : /dev/ttyACM0
flowcontrol    : none
baudrate is    : 38400
parity is      : none
databits are   : 8
stopbits are   : 1
escape is      : C-a
local echo is  : yes
noinit is      : no
noreset is     : no
hangup is      : no
nolock is      : no
send_cmd is    : sz -vv
receive_cmd is : rz -vv -E
imap is        : 
omap is        : 
emap is        : crcrlf,delbs,
logfile is     : none
initstring     : none
exit_after is  : not set
exit is        : no

Type [C-a] [C-h] to see available commands
Terminal ready
E FlashForth 5 ATmega328 18.11.2020

Here are the words defined by default:

words 
p2+ pc@ @p hi d. ud. d> d< d= d0< d0= dinvert d2* d2/ d- d+ dabs ?dnegate dnegate s>d rdrop endit next for in, inline repeat while again until begin then else if zfl pfl xa> >xa x>r dump .s words >pr .id ms ticks r0 s0 latest state bl 2- ['] -@ ; :noname : ] [ does> postpone create cr [char] ihere ( char ' lit abort" ?abort ?abort? abort prompt quit true false .st inlined immediate shb interpret 'source >in tiu tib ti# number? >number ud/mod ud* sign? digit? find immed? (f) c>n n>c @+ c@+ place cmove word parse \ /string source user base pad hp task ulink rsave bin hex decimal . u.r u. sign #> #s # digit <# hold up min max ?negate tuck nip / u*/mod u/ * u/mod um/mod um* 'key? 'key 'emit p++ p+ pc! p! p@ r>p !p>r !p u> u< > < = 0< 0= <> within +! 2/ 2* >body 2+ 1- 1+ negate invert xor or and - m+ + abs dup r@ r> >r rot over swap drop allot ." ," s" (s" type accept 1 umax umin spaces space 2swap 2dup 2drop 2! 2@ cf, chars char+ cells cell+ aligned align cell c, , here dp ram eeprom flash >< rp@ sp@ 2constant constant 2variable variable @ex execute key? key emit Fcy mtst scan skip n= rshift lshift mclr mset ic, i, operator iflush cwd wd- wd+ pause turnkey to is defer value fl+ fl- c! c@ @ a> ! >a literal int! ;i di ei ver warm empty rx0? rx0 tx0 load- load+ busy idle exit 
marker  ok<#,ram>

I only had a few minutes to experiment with it, but here are a several things of interest:

  • One great thing about FlashForth is that all the three memory types – RAM, flash, and EEPROM, are mapped to a contiguous address space, and accessible with @ and ! memory words. So, you don’t have to do anything special to write to flash or EEPROM.
  • By default, all words you add to the dictionary are compiled to flash memory and therefore survive a chip reset. This is very convenient.
  • You are not actually allowed to redefine words (at least, in the usual way of defining words), but you are expected instead to use the marker Forth word to construct forgettable sections of words. Also the empty word will remove all words but the core FlashForth words.