I'm writing a free online book, "Clojure for the Brave and True" (http://www.braveclojure.com/), that has been picked up by No Starch. A couple of the chapters, "Start Using Emacs" and "Functional Programming" have done pretty well here on HN. I've made about $1k on leanpub so far for the unfinished book (ebook buyers will get the full No Starch ebook when it's ready).
The main thing that has worked for me has been to constantly get feedback from readers. Every time I release a chapter I tweet it, send it to my mailing list, and post it on reddit and G+. The comments have been overwhelmingly supportive. If it weren't for that kind of enthusiastic feedback, I'm pretty certain I would have given up.
Other people might have other ways to stay motivated, but this make the project much more "real" for me. I feel proud to provide my readers with quality content, and that they would choose to spend their time reading my work. It also helps to get those leanpub emails saying that someone has paid for the PDF - it's very encouraging when people pay for a free resource. To sum up this point - try thinking about what kind of process will make the risk worth it for you.
The second thing that's worked for me has been to write in a way that I, personally, find entertaining. When I sit down to write, I crank up the Lady Gaga and let out my inner idiot. It's way more fun that way, and people seem to like the result.
I hope this helps!