Knowing when to use an accidental is a difficult question to answer, and the best I can say is Whenever you like. Whatever your musical ear tells you is acceptable for the purpose is what is allowed.
Let's assume that you want the music to sound interesting without being dissonant. in that case there are a few uses that I can think of off the top of my head*(bear in mind these are guidelines)*
As a grace note before your main note/chord
Certain notes of the diatonic scale are more like colourings than main notes. For example in a minor scale the 6th can either be a minor 6th(natural minor scale/Aolean) or a major 6th(as in the dorian mode) and both have their place.
As a passing tone between 2 chords
if you treat chords as their individual notes you'll notice certain relationships between the notes. Let's take a simple I - V
CMaj - CEG
GMaj - GBD
The distance between C in CMaj and D in GMaj is one tone, or 2 semitones, so it's completely faesable to use the note in the middle as a passing tone.
instead of CMaj-GMaj try Cmaj C# GMaj
As part of a deliberate Dissonance
you can substitute certain chords in a scale with other chords involving non diatonic notes. The example I'm thinking of is using a diminished chord instead of a straight dominant chord on the 5th, If you want to explore substitutions further might I suggest Ted Greene's Chord Chemistry
As part of a key change
Let's say you want to move from C major to G major, as you may know C major uses no sharps/flats and G major uses one sharp (F#). Usually at some point before the actual new key you need to introduce that F# so that the shift doesn't sound forced or out of place
As part of a non-diatonic scale
eg chromatic scale, Whole tone, dininished scale, Hybrid Scales, Neapolitan scale, the original modes
To avoid dissonance on voice leading
The wording of this one might be off, but when you're sticking to one key with no accidentals you can still have dissonant intervals happening, in C if you have chords a 5th apart you get 6 perfect intervals - CG DA EB FC GD AE and then you have BF which is a diminished 5th. if it so happens that your chord contains B and F you will have a dissonance which can be removed if you sharpen or flatten either of the 2 notes. If you decide to Flatten B or Sharpen F, you have yourself an accidental(or if you want to be techie then it's a transient modulation of a 4th or 5th)
In a harmonic minor scale, the 7th degree is sharpened(so that it has a leading note)
In a melodic minor scale, the 6th and 7th degrees are sharpened
The blues scale uses a diminished 5th
A heavy answer to a heavy question