"Hardly" vs. "barely"
Solution 1:
They are not always interchangeable.
I would say that someone who scored 60 on a test for which 60 was the lowest possible passing grade barely passed the test, but not hardly passed the test.
I would say of someone I thought unsuitable to be, for example, a high school teacher, that "He's hardly the type of person who should be a high school teacher", but not "He's barely the type of person who...".
That's American English. I don't know about other varieties.
Solution 2:
Each has meanings that are different from those of the other, but I assume you are referring to cases in which the two seem interchangeable. The relevant definitions in the Oxford English Dictionary suggest that they are:
Barely. Only just; hence, not quite, hardly, scarcely, with difficulty.
Hardly. Barely, only just; almost not; not quite; scarcely.
Because of their other meanings, a corpus search is not entirely reliable. However, the Corpus of Contemporary American English shows the two words as being almost equally as frequent as each other, whereas the British National Corpus shows a strong preference for hardly. A more detailed search might establish whether one is used in a different kind of context from the other, as can sometimes be the case with such pairs.