Skip to content
On this page

Input device

For input device week, I use the broad produced in Electronic Design and Electronic Production Week to test the input devices used in my dog feed machine. The input devices tested in this week include an Ultrasonic sensor, a HC-SR501 Motion sensor and a Keypad.

SEEED studio XIAO extension broad design

The detail design of the XIAO extension broad is shown as pictures below.

The soldered extension broad is shown below.

Circuit design

The circuit applied at this stage is shown as figure below.

Code

The code used is provided as below.

#define TrigPin A0    
// __|^|_____________
// 10us or more HITH SIGNAL will drive it work for one time
#define EchoPin A1    
// ______|^^^^^^^^|__ 
// PULSE WIDTH stand for distance(the time of ultrasound transmit, both go and back)
// pulse width WILL NOT long than 38ms, it means timeout
// Distance = Speed x Time
// Speed of sound ~= 340m/s = 0.340mm/us

int count = 0;
int val;
// define led according to pin diagram
int led1 = D10;
int led2 = D9;
int led3 = D8;
int pripin = D6;
int motion;
long duration;
// PULSE WIDTH

void setup() {
    // set Serial communication
    Serial.begin(115200);
    // set pin mode
    pinMode(pripin, INPUT);
    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(TrigPin, OUTPUT);
    pinMode(EchoPin, INPUT);
    // init pin
    digitalWrite(TrigPin, LOW);
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, HIGH);
    delay(1000);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    delay(1000);

}

void loop() {
    Serial.println(count++);
    Serial.println(getDistance());
    motion = digitalRead(pripin);
    val=getDistance();
    if (motion == HIGH){
      digitalWrite(led3, HIGH);   // turn the LED3 on 
      Serial.println("Motion detected");; 
      } else { 
      digitalWrite(led3, LOW);    // turn the LED3 off   
      Serial.println("No motion");    // turn the LED3 off   
    }       
    if (val<100){
     digitalWrite(led1, HIGH);   // turn the LED1 on 
     digitalWrite(led2, LOW);   // turn the LED2 off 
     } else {
     digitalWrite(led2, HIGH);    // turn the LED2 on
     digitalWrite(led1, LOW);    // turn the LED1 off   
    }          // wait for a second
    
    Serial.println("");
    Serial.println("");
    delay(100);
}

long getDistance() {
    // trig
    digitalWrite(TrigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(TrigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(TrigPin, LOW);
    // echo
    duration = pulseIn(EchoPin, HIGH);     // unit: us
    return duration * 0.34029 / 2;         // unit: mm
}

Result

The final result is shown as pictures below. The red light turns on when there is no obstacles.

If there is a obstacles,the green light will be turn on.

If there is motion around the HC-SR501 sensor then the blue light will turns on.