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.
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++) { sampleData[i] = analogRead(analogPin); val = val + sampleData[i]; delay(sampleInterval); } val = (val / samples); return map(val, 550, 1023, 100, 0); }
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 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; } } } }
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; }
Execute the following function to reset the Arduino.
void(* resetFunc) (void) = 0; //declare reset function @ address 0 resetFunc(); //Call to reset
2 Comments
We can improve these a bit.
For the changes between two values, it is enough to just return abs(lastVal – currVal) ….no if-statement needed.
Regarding the sorting, bubble sort is about the worse you can use. It’s running time is polynomial on the number of items! There are faster methods like insertionSort, but the I would actually recommend mergeSort which is the standard implementation.
For sorting, “gnome sort” (google it) seems pretty cool, and looks like it would be easy to implement.