So, first post. I'm not sure if something like this is posted around here somewhere so here goes.
I'm trying to take an analog input from a pot (0-255) and send that to an 8-bit R/2R ladder connected to the digital pins. I know the easiest way to get the 0-255 value is to use:
map(potin, 0, 1023, 0, 255)
My question is, is there an easier way to do the binary output on the digital pins than using a switch/case with 256 cases?
The simplest way would be to put all the eight lines of the ladder on a single I/O port (like port C). You would then be able to output the value with a simple assignment...
PORTC = MyAnalogValue;
There's a description here that will hopefully get you started...
No, you're making it too complicated! What Coding Badly was coding properly was much simpler:
val = map(potin, 0, 1023, 0, 255);
PORTC = val;
The end. That's it! Assuming, of course, all your pins are on PORTC and you've configured all pins to be outputs.
The bigger question is: why? It sounds like you're trying to "reflect" an analog voltage set by a potentiometer to go somewhere else. Why not just use an op-amp in a noninverting buffer configuration? One little chip...
Ah, that makes a lot more sense. Thank you RuggedCircuits. As to why: It's going to be a part of something bigger. My own take on an Arduino synthesizer. I'll be sure to post results as I go along. Just waiting for my Arduino to arrive in the mail to implement things.
Is there a port that you could actually do this with on a Duemilanove? PORTD looks like the only one where you might be able to use all 8 pins, but 0 and 1 are the serial Tx/Rx pins, so you might have to connect/disconnect them every time you uploaded a new sketch.
//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;
////Pin connected to your analog pot
int potPin = 5;
void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
pinMode(potPin, INPUT);
}
void loop() {
potin = analogRead(potPin);
val = map(potin, 0, 1023, 0, 255);
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, MSBFIRST, val);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 1);
delay(1000);
}
If you don't want to use a continuous port and you don't have a shift register chip "handy" you could just define a eight digital pins (I'm using 2 through 9, but you could use others) and use the following code: