Generally, you can be convicted of a DUI/DWI for taking prescription medication or a drug that's legal in your state. It just depends on whether you've taken enough of the drug or medication to be "under the influence" or "intoxicated" as defined by state law.
The DUI laws of most states make it illegal to drive while under the influence of (intoxicated by) any substance or with a certain amount of alcohol in your system (a "per se" DUI). Some states also have per se DUI laws that make it illegal to operate a vehicle with a certain concentration of drugs in your blood.
In other words, you can get a DUI based on the actual effects of the substances you ingested or the measured amount of certain substances in your system.
Impairment DUI laws focus on the effects that the ingested substance had on the driver—not necessarily what the substance was or how much of it was in the driver's system. So, cases involving prescription drugs like painkillers and benzos are typically charged under impairment DUI laws.
To prove an impairment DUI at trial, the prosecution needs to show the driver was "under the influence" or "intoxicated" as defined by state law. States differ on the level of impairment that prosecutors must prove. Some states, for example, require proof that the driver was "substantially affected," while in other states, evidence of "any effect" is enough.
Per se drug DUI laws typically apply only to common illegal drugs like cocaine, methamphetamines, and marijuana. So prescription drug use generally won't lead to per se charges.
A driver who's arrested for a DUI based on prescription drug use may have a limited defense. A handful of states will let drivers off the hook if they can show they were impaired as the result of taking a prescription medication as prescribed by a licensed physician.
However, this defense doesn't come into play very often. Generally, a driver would have to show that they took a prescription medication as prescribed and there was no warning on the label about driving while taking the medication.
Quite a few states now have at least some legal marijuana use—either recreational or for medical purposes. But just like with prescription medications, legal marijuana use can result in a DUI conviction based on impairment.
Some states also have per se marijuana laws that prohibit motorists from driving while having a certain blood concentration of THC, the psychoactive ingredient in marijuana.
If you've been arrested for a DUI related to lawful drug use or medication that a doctor prescribed to you, get in contact with a knowledgeable DUI lawyer in your area. An experienced DUI attorney should be able to tell you how state law applies in your situation and whether you have any viable defenses.