I think the best answer to this post is pretty much what madires and Rerouter suggested: read the datasheet, learn about the arduino's internal peripherals and make it work!
Or, you can still use the code proposed by Mechatrommer... The only caveat with this code snippet is the MCU will be 100% busy doing just that, leaving no MCU time at all for anything else.
Hence you are obviously using arduino, I suggest you to take a look at the NewTone library, it was designed to generate specific tones to drive piezzoelectric buzzers, but all it does in fact is makes use of timers to generate PWM signals. It is far from being perfect, but at least you can learn how to implement a timer, timer overflow ISR, etc. That way, the MCU has plenty of time to execute other useful code!
It might sound strange, but I think it's better to understand the internals first then really know how to code
Indeed, you will often discover a lot of internal things that can do what you want 10x easier and with 10x less of code than doing it all by yourself. Enjoy!