 Developing an IR remote and Software controller
May 4, 2016 Programming the Arduino with Visual Studio
May 8, 2016 Below you will find useful Arduino code snippets from our library of code, these have been used in our projects previously. From resetting the Arduino to debugging the amount of RAM available left on the device.

Smoothing values by sampling data

This is useful for smoothing out values from analog sensors, such as LDRs

int sampleData(int analogPin, int samples = 8, int sampleInterval = 50) {
int sampleData[samples];
int val = 0;
for (int i = 0; i<samples; i++) {
val = val + sampleData[i];
delay(sampleInterval);
}
val = (val / samples);
return map(val, 550, 1023, 100, 0);
}

Calculating the change between two values (including negative numbers)

This is extremely useful when comparing temperature changes.

int getValueChange(int currVal, int lastVal) {
if (currVal > lastVal) {
return (currVal - lastVal);
} else {
int dec = -(lastVal - currVal);
return dec;
}
}

Sorting an array of integers

Sorting an array of values using a bubble sort algorithm.

void sort(int a[], int size) {
for(int i=0; i<(size-1); i++) {
for(int o=0; o<(size-(i+1)); o++) {
if(a[o] > a[o+1]) {
int t = a[o];
a[o] = a[o+1];
a[o+1] = t;
}
}
}
}

Get the available memory usage

Mainly used for debugging, this will return the amount of used RAM on the Arduino.

int getMemory() {
int size = 1024; // Use 2048 with ATmega328
byte *buf;

while ((buf = (byte *) malloc(--size)) == NULL);

free(buf);
return size;
}

Reset the Arduino with a function

Execute the following function to reset the Arduino.

void(* resetFunc) (void) = 0; //declare reset function @ address 0

resetFunc(); //Call to reset

1. Ty says:
• Robert says: