Hi,
This is my first week learning Arduino and for the start, I bought UNO and Leonardo, I collected the below codes from everywhere, the codes below perfectly works with UNO(no serial1) but not with Leonardo, please have time to scan the code and comment, thank you in advance.
JoshSG
#define ENC_A 14
#define ENC_B 15
#define ENC_PORT PINC
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int switch0=0;
void setup() {
/* Setup encoder pins as inputs */
pinMode(ENC_A, INPUT);
digitalWrite(ENC_A, HIGH);
pinMode(ENC_B, INPUT);
digitalWrite(ENC_B, HIGH);
// initialize serial communication at 9600 bits per second:
Serial.begin(115200);
Serial.println("Start Serial0");
delay(1);
Serial1.begin(115200);
Serial.println("Start Serial1");
delay(1);
while (!Serial) { }
while (!Serial1) { }
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
static uint8_t counter = 0; //this variable will be changed by encoder input
int8_t tmpdata;
/**/
tmpdata = read_encoder();
if( tmpdata ) {
Serial.print("Counter value: ");
Serial.println(counter, DEC);
counter += tmpdata;
}
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
// print out the state of the button:
if (switch0 == 0){
Serial.print("ON ");
delay(1);
Serial.println(buttonState);
delay(1); // delay in between reads for stability
switch0=1;
}
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
if (switch0==1){
Serial.print("OFF ");
delay(1);
Serial.println(buttonState);
delay(1); // delay in between reads for stability
switch0=0;
}
}
}
/* returns change in encoder state (-1,0,1) */
int8_t read_encoder()
{
static int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
static uint8_t old_AB = 0;
/**/
old_AB <<= 2; //remember previous state
old_AB |= ( ENC_PORT & 0x03 ); //add current state
return ( enc_states[( old_AB & 0x0f )]);
}

