Go Down

Topic: Code works on Uno but not on Leonardo (Read 68 times) previous topic - next topic



Please excuse my ignorance in this area. I using the code below on a Uno and it works as it should, but then I try the same code with a Leonardo without no success. (reading the value from my receiver as they change when I move the transmitter sticks and print the values).
I am aware of the difference in serial and serial1 and I tried both, again without success.

The hardware is a Spektrum AR 610 receiver and a UnoR3 and a brand new Leonardo.
I have 5V and Ground to my receiver from the board and then I have 4 channels from the receiver connected to A0-A3 (I know I should not use A4+A5)
The reason for using the Leonardo is that I will need more than 6 Analog inputs.

The code is from this website and again it works fine with the Uno.

#include <EnableInterrupt.h>

#define SERIAL_PORT_SPEED 57600
#define RC_NUM_CHANNELS  4

#define RC_CH1  0
#define RC_CH2  1
#define RC_CH3  2
#define RC_CH4  3

#define RC_CH1_INPUT  A0
#define RC_CH2_INPUT  A1
#define RC_CH3_INPUT  A2
#define RC_CH4_INPUT  A3

uint16_t rc_values[RC_NUM_CHANNELS];
uint32_t rc_start[RC_NUM_CHANNELS];
volatile uint16_t rc_shared[RC_NUM_CHANNELS];

void rc_read_values() {
  memcpy(rc_values, (const void *)rc_shared, sizeof(rc_shared));

void calc_input(uint8_t channel, uint8_t input_pin) {
  if (digitalRead(input_pin) == HIGH) {
    rc_start[channel] = micros();
  } else {
    uint16_t rc_compare = (uint16_t)(micros() - rc_start[channel]);
    rc_shared[channel] = rc_compare;

void calc_ch1() { calc_input(RC_CH1, RC_CH1_INPUT); }
void calc_ch2() { calc_input(RC_CH2, RC_CH2_INPUT); }
void calc_ch3() { calc_input(RC_CH3, RC_CH3_INPUT); }
void calc_ch4() { calc_input(RC_CH4, RC_CH4_INPUT); }

void setup() {

  pinMode(RC_CH1_INPUT, INPUT);
  pinMode(RC_CH2_INPUT, INPUT);
  pinMode(RC_CH3_INPUT, INPUT);
  pinMode(RC_CH4_INPUT, INPUT);

  enableInterrupt(RC_CH1_INPUT, calc_ch1, CHANGE);
  enableInterrupt(RC_CH2_INPUT, calc_ch2, CHANGE);
  enableInterrupt(RC_CH3_INPUT, calc_ch3, CHANGE);
  enableInterrupt(RC_CH4_INPUT, calc_ch4, CHANGE);

void loop() {

  Serial.print("CH1:"); Serial.print(rc_values[RC_CH1]); Serial.print("\t");
  Serial.print("CH2:"); Serial.print(rc_values[RC_CH2]); Serial.print("\t");
  Serial.print("CH3:"); Serial.print(rc_values[RC_CH3]); Serial.print("\t");
  Serial.print("CH4:"); Serial.println(rc_values[RC_CH4]);



Leonardo programs need the line
Code: [Select]
while (!Serial) {}
so it waits until the serial port is created before trying Serial.begin()


Two or three hours spent thinking and reading documentation solves most programming problems.

Go Up