Hi folks,
Pardon my newbie questions.
My project is a Volume control which takes the input value from a rotary encoder position (via interrupts),
displaying the actual value on a Serial 7 Segment Display.
It's connected via it's RX pin to the Leonardo board.
This part works flawlessly so far.
In addition, I need to control an R-2R ladder, so I need 8 outputs to display the binary value of encoder Pos.
I tried several codes, but none worked, including the use of Port B
through
DDRB = 0xFF;
PORTB = encoderPos;
no luck. When I add this, the whole project stops working.
Any suggestion?
The code below is the working one, but missing the 8-bit parallel output to control the R-2R ladder:
/*--------------------------
* R-2R Volume Control
* Rev. 1.0.2
* Date: 31/03/2017
*/
#include <SoftwareSerial.h>
//connect RX from Display to Digital Pin 1 (TXD)
SoftwareSerial Serial7Segment(0, 1); //RX pin, TX pin
enum PinAssignments {
encoderPinA = 3, //interrupt 0
encoderPinB = 2, //interrupt 1
clearButton = 4
};
volatile byte encoderPos = 0;
byte lastReportedPos = 1;
boolean A_set = false;
boolean B_set = false;
void setup() {
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
pinMode(clearButton, INPUT);
digitalWrite(clearButton, HIGH);
// encoder pin on interrupt 0 (pin 3)
attachInterrupt(0, doEncoderA, CHANGE);
// encoder pin on interrupt 1 (pin 2)
attachInterrupt(1, doEncoderB, CHANGE);
Serial.begin(9600);
Serial7Segment.begin(9600); //Talk to the Serial7Segment at 9600 bps
Serial7Segment.write('v'); //Reset the display - this forces the cursor to return to the beginning of the display
}
void loop() {
if (lastReportedPos != encoderPos) {
Serial.print("Index:");
Serial.print(encoderPos, DEC);
Serial.println();
lastReportedPos = encoderPos;
char tempString[10]; //Used for sprintf
sprintf(tempString, "%4d", encoderPos); //Convert deciSecond into a string that is right adjusted
Serial7Segment.print(tempString); //Send serial string out the soft serial port to the S7S
delay(10);
}
if (digitalRead(clearButton) == LOW) {
encoderPos = 0;
}
}
// Interrupt on A changing state
void doEncoderA(){
// Test transition
A_set = digitalRead(encoderPinA) == HIGH;
// and adjust counter + if A leads B
encoderPos += (A_set != B_set) ? +1 : -1;
}
// Interrupt on B changing state
void doEncoderB(){
// Test transition
B_set = digitalRead(encoderPinB) == HIGH;
// and adjust counter + if B follows A
encoderPos += (A_set == B_set) ? +1 : -1;
}