typestar

Structs in Arduino

One struct rides a whole reading through the sketch.

// A struct rides one reading through the sketch in one piece.
struct Reading {
  unsigned long at;
  int soil;
  float volts;
};
Reading sample() {
  Reading r;
  r.at = millis();
  r.soil = analogRead(A0);
  r.volts = r.soil * (5.0 / 1023.0);
  return r;
}
void setup() { Serial.begin(9600); }

void loop() {
  Reading r = sample();
  Serial.print(r.at); Serial.print(' '); Serial.println(r.volts);
  delay(500);
}

How it works

  1. struct Reading bundles timestamp, counts, and volts.
  2. sample() fills one and returns it by value.
  3. Fields read with dots: r.at, r.volts.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
394
Tokens
116
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 107 seconds.

Type this snippet

Step 2 of 3 in Data, step 20 of 27 in Language basics.

← Previous Next →

Structs in other languages