ardfeat
Developing an IR remote and Software controller
May 4, 2016
idefeat
Programming the Arduino with Visual Studio
May 8, 2016
Show all

5 Useful Arduino Code Snippets

code

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++) {
    sampleData[i] = analogRead(analogPin);
    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

2 Comments

  1. Ty says:

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *