Behaviours evolve by iterations of natural selection, but we have few insights into the molecular and neural mechanisms involved. Here we show that some Caenorhabditis elegans wild strains switch between two foraging behaviours in response to subtle changes in ambient oxygen. This finely tuned switch is conferred by a naturally variable hexacoordinated globin, GLB-5. GLB-5 acts with the atypical soluble guanylate cyclases, which are a different type of oxygen binding protein, to tune the dynamic range of oxygen-sensing neurons close to atmospheric (21%) concentrations. Calcium imaging indicates that one group of these neurons is activated when oxygen rises towards 21%, and is inhibited as oxygen drops below 21%. The soluble guanylate cyclase GCY-35 is required for high oxygen to activate the neurons; GLB-5 provides inhibitory input when oxygen decreases below 21%. Together, these oxygen binding proteins tune neuronal and behavioural responses to a narrow oxygen concentration range close to atmospheric levels. The effect of the glb-5 gene on oxygen sensing and foraging is modified by the naturally variable neuropeptide receptor npr-1 (refs 4, 5), providing insights into how polygenic variation reshapes neural circuit function.