I'm trying to use a rotary switch to turn on 7 individual leds based on connecting 7 different resistance values. This is the switch. https://www.mouser.com/datasheet/2/626/Grayhill_07272021_7db2d6_2bce8318cc2c400da5c3930fd-2509274.pdf
The individual tabs of the switch will have a different resistor with all 7 leads connected to A0.
I'm unsure were the center terminal o]f the switch will be connected to - I tried 5v and GND - in both cases got garbage on serial monitor.
The attached sketch is only trying to turn on the onboard led just for testing.
Is this doable and if so what am I doing wrong
Thanks
const int POT_PIN = A0;
int swcnt = 0;
#define led 13
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
// Read potentiometer value
int val = analogRead(POT_PIN);
Serial.print (val);
Serial.println (" ");
delay(200);
if (val = 10) {
swcnt = 0;
}
if (val = 47) {
swcnt = 1;
}
if (val = 100) {
swcnt = 2;
}
if (val = 180) {
swcnt = 3;
}
if (val = 220) {
swcnt = 4;
}
if (val = 470) {
swcnt = 5;
if (val = 510) {
swcnt = 6;
}
}
if (swcnt = 0) {
digitalWrite (led, HIGH);
}
}
For starters you have to look for a range of values. You're rarely going to get any exact value from an analog input. Plus, there is usually some noise/instability and there is always the possibility of being on the hairy-edge between two digital values, even if everything is "perfect".
If you have a known and unknown resistance in a voltage divider, you can calculate the unknown resistance.
It's a bit tricky and will require some algebra to derive a C+ expression. I don't have it off the top of my head, but the voltage is non-linear with resistance change because it's a ratio.
Be careful with low resistance. For example, with 5V applied 10 Ohms total, that's half an Amp (Ohm's Law) and the voltage might drop if the power supply can't supply it, or you could burn-up a small resistor.
What kind of "garbage"? Do you have a multimeter to measure the voltage and does the reading correspond to the voltage?
Certainly you probably want == (test for equality) not = (assignment) here. Your first post was full pf the same type expression.
Which is not an error, but unusual. Go to the IDE and turn up all warnings and verbosity, this kind of mistake not an error will be brought to,your attention so you can decide if it is what you really meant or not.
Then be aware that the analog pin will see the full voltage between positions - however a 300k resistor is stout protection so its probably not an issue - in future consider using the multi-way switch on the top resistor in the divider, not the bottom one...
I know that it is not the question of the post, but have you considered a rotary encoder instead?
You could just count the clicks to the right or to left by software to control the leds. You would need just 2 arduino pins and you would get rid of the resistors complexity.