Resource friendly structs and utility functions for Arduino
Author:  Alexander Brevig
Contact: alexanderbrevig@gmail.com

Resource Friendly Structs


Navigation


Download

There is no download available.

If you want to use this code in your project, just copypaste it.


Pin structs

Digital Pin

typedef struct {
  byte pin : 6;
  byte mode : 1;
  byte state : 1;
} DigitalPin;

void set(DigitalPin& pin,boolean mode=INPUT,boolean state=false)
{
 pin.mode = mode;
 pin.state = state;
 pinMode( pin.pin, pin.mode);
 digitalWrite( pin.pin, pin.state);
}

DigitalPin& read(DigitalPin& pin)
{
  pin.state = digitalRead( pin.pin );
  return pin;
}

boolean changed(DigitalPin& pin)
{
  return (pin.state != digitalRead( pin.pin ) ? true : false);
}

void write(DigitalPin& pin,boolean state)
{
  pin.state = state;
  digitalWrite( pin.pin, pin.state);
}

void toggle(DigitalPin& pin){
  write(pin,!pin.state); 
}
DigitalPin led = {13,OUTPUT,HIGH};
DigitalPin button = {13,OUTPUT,HIGH};
set(led);
set(button);

if (changed(button)){
  if (read(button).state == HIGH){
    write(led,HIGH);
  }else{
    write(led,LOW);
  }
}

Analog Pin

typedef struct {
  byte pin : 6;
  byte value : 10;
} AnalogPin;

void set(AnalogPin& pin,boolean mode)
{
  pinMode( pin.pin, mode);
  pin.value = analogRead(pin.pin);
}

AnalogPin& read(AnalogPin& pin)
{
  pin.value = analogRead(pin.pin);
  return pin;
}

void write(AnalogPin& pin)
{
  analogWrite(pin.pin,pin.value);
}

AnalogPin potentiometer = { 2 };
set(potentiometer,INPUT);
if (read(potentiometer).value >= 128){
  //potentiometer is above half way around
}


General useful structs

RGB leds

typedef struct {
  byte r;
  byte g;
  byte b;
} RGB;
RGB red = { 255 , 0 , 0 };

byte redComponent = red.r; //255
typedef struct {
  AnalogPin r;
  AnalogPin g;
  AnalogPin b;
} RGBPins;
void writeRGB(RGB& rgb)
{
  write(rgb.r);
  write(rgb.g);
  write(rgb.b);
}

// should this maybe start "AnalogPin red = {" ?
RGB red = { 
  {  9 , 255 },
  { 10 , 0 },
  { 11 , 0 }
};

writeRGB(red); //your rgb led connected to 9 10 11 should light up in a red color.

Eight Bit field

typedef struct {
  byte b1 : 1;
  byte b2 : 1;
  byte b3 : 1;
  byte b4 : 1;
  byte b5 : 1;
  byte b6 : 1;
  byte b7 : 1;
  byte b8 : 1;
} EightBitfield;

EightBitfield states = { 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 };


Links


Information about this page

Part of AlphaBeta Utilities.
Last Modified: March 02, 2014, at 04:29 PM
By: DavidCary

Share