We will be writing functions for better Arduino code, with the help of a microcontroller (SAMD21) and a sensor. In today’s post there will be a prime in how functions work and how to use them. That includes passing parameters to them and also reading variables from them.
Here is the article’s video, where I go through everything that is going to be written below. You could totally skip either, but it is best for you to read and watch the full video.
Here is the full code for you to copy and use:
#define ledPin 10
int ledTimeExternal= 0;
int newLedTime= 0;
const int trigPin = D2;
const int echoPin = D3;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
int ultrassonicTime;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
int readAndPrintAnalog() {
static unsigned long analogTime = 0;
int analogValue = 0;
if (millis() - analogTime > 1000) {
analogTime = millis();
analogValue = analogRead(A0);
Serial.println(analogValue);
}
return analogValue;
}
void blinkLed(int ledTime) {
static unsigned long oldLedTime = 0;
if (millis() - oldLedTime > ledTime) {
oldLedTime = millis();
digitalWrite(ledPin, !digitalRead(ledPin));
}
}
int readUltrassonicSensor(){
static int returnDistanceTime= 0;
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
returnDistanceTime= map(distanceCm, 0, 300, 100, 1000);
return returnDistanceTime;
}
void loop() {
ultrassonicTime = readUltrassonicSensor(); // Innteger that comes from ultrassonic sensor
newLedTime = readAndPrintAnalog(); // Integer that comes from analog reading
// instead of ultrassonicTime, one could use newLedTime, which comes from the analog input A0
if (ultrassonicTime > 0) { // ignore 0s returned when not updating
ledTimeExternal = ultrassonicTime;
}
blinkLed(ledTimeExternal); // Function to blink an LED; it receives time from another function
}
Leave a Reply