0

I am in my first arduino steps. I have a Mega2560R3 I wrote this code

const byte D0 = 22;
const byte D1 = 24;
const byte D2 = 26;
const byte D3 = 28;
const byte D4 = 30;
const byte D5 = 32;
const byte D6 = 34;
const byte D7 = 36;

void setup() {
  Serial.begin(115200);
  Serial.write("Started");
  pinMode(D0, INPUT);
  pinMode(D1, INPUT);
  pinMode(D2, INPUT);
  pinMode(D3, INPUT);
  pinMode(D4, INPUT);
  pinMode(D5, INPUT);
  pinMode(D6, INPUT);
  pinMode(D7, INPUT);
} 

void loop() {
  byte data;
  data = read_dataline();
  Serial.println(data);         
  delay(100);  
}


byte read_dataline() {
  byte val;
  noInterrupts();

  val |= (digitalRead(D0) == HIGH ? 0x1 : 0x0);
  val |= (digitalRead(D1) == HIGH ? 0x1 : 0x0) << 1;
  val |= (digitalRead(D2) == HIGH ? 0x1 : 0x0) << 2;
  val |= (digitalRead(D3) == HIGH ? 0x1 : 0x0) << 3;
  val |= (digitalRead(D4) == HIGH ? 0x1 : 0x0) << 4;
  val |= (digitalRead(D5) == HIGH ? 0x1 : 0x0) << 5;
  val |= (digitalRead(D6) == HIGH ? 0x1 : 0x0) << 6;
  val |= (digitalRead(D7) == HIGH ? 0x1 : 0x0) << 7;

  interrupts();
  return val & 0xFF;
}

To test it, I took a jumper cable and connected the 5V line with the appropriate pin. What I saw was the following:

  1. the number produced on the serial monitor is correct, but as soon as I unplug the jumper cable, the value lingers for a few iterations, instead of going immediately to zero.

  2. the value is very noisy and it can produce random values just by rubbing my finger over the board.

Why is that?

  • 4
    It's called a floating input and it's what you get when you don't have a pull-down or pull-up resistor. – Majenko Jan 16 '19 at 23:44
  • There is no need to turn off interrupts for a variable on the stack. Please add byte val = 0; The & 0xFF is not needed since it is a byte. When you use an open input and convert the value into a frequency, then you can make some kind of Theramin, the impedance of a floating input is extremely high. – Jot Jan 17 '19 at 8:02
  • it would be much simpler to set the inputs to INPUT_PULLUP and ground the pin for change of state – Juraj Jan 17 '19 at 8:39

Browse other questions tagged or ask your own question.