I am currently trying to create a simple Theremin, using two ultrasonic sensors and a piezo buzzer. I know how to control the frequency of the notes using tone(), and I can separately control the volume of the buzzer via analogWrite().
However, is there a method to combine the two, outputting a desired frequency at the desired volume? Thanks in advance for your help.
The regular Arduino doesn't have a true analog output so the only way to adjust the volume is to control the duty cycle.
Or you can "fake it" with something like TMRpcm, which is high-frequency PWM (also modulating the PWM with the lower-frequency audio signal).
I've never used TMRpcm but it was designed to play WAV files so it would have to be "tweaked".
The tone() function always has a 50% duty cycle which is maximum loudness so you'd have to write your own code/function.
Also, changing the duty cycle changes the harmonic content (more high-frequency content with narrower pulse). The fundamental frequency doesn't change (if you hold the same frequency) and the musical note doesn't change but you might perceive a higher pitch as the higher harmonics dominate (you might hear a musical note one octave, or more, higher).