Skip to content

11. Input Devices

For this week we had to:

  • Group assignment

    • Probe an input device(s)’s analog and digital signals

    • Document your work on the group work page and reflect on your individual page what you learned

  • Individual assignment

    • Measure something: add a sensor to a microcontroller board that you have designed and read it.

Group assignment

Details of our group work can be found here.

As part of the group work, we examined analog and digital input sensors. To visually see the values produced by the sensors, we used an oscilloscope. And oscilloscope is an electrical device that makes it possible to see electrical vibrations with the eye. We also used a multimeter.

Variable resistors

For a clear understanding of what variable resistor is, we looked at an example that is present in the school laboratory:

school resistor

We examined this rheostat with a multimeter.

school resistor test

Its values are in the range from 12.6 Ohms to 400 Ohms.

We have several types of variable resistance sensors in our laboratory.

variable resistance sensors

We also considered LDR photoresistor

Photoresistor

The LDR or photoresistor is very similar in property to a rheostat, it is able to change its resistance. It only differs in that it changes the resistance value not mechanically, but inversely proportional to the intensity of the light falling on it. In order to use it we need a voltage divider circuit.

Digital Ultrasonic Distance Meter

Powering up the ultrasonic rangefinder is the initial step required to operate the device. However, unlike an analog infrared sensor, in order to read the signals generated by the range finder, you need to connect to the microcontroller and write a control code.

ultrasonic rangefinder

Individual assignment

Within this week, we need to connect the input sensors to us board and read the values.

Ultrasonic Sensor

Next, I would like to discuss the ultrasonic distance sensor HC-SR04.

Ultrasonic

The HC-SR04 ultrasonic sensor is a device that uses ultrasonic waves to measure the distance to an object. It consists of two main components: a transmitter and a receiver.

The working principle of the HC-SR04 sensor is based on sending an ultrasonic pulse and measuring the time it takes for the echo signal to return.

To use the HC-SR04 sensor, you need to connect it to a microcontroller, usually using digital pins. You will control the transmitter and read values from the receiver using the corresponding pins of your microcontroller.

After measuring the time delay, you can use a simple formula to calculate the distance:

distance = (time * speed of sound) / 2

It is important to note that for accurate measurements, various factors such as temperature and inaccuracies need to be taken into account. Additionally, obstacles that do not reflect sound waves can affect measurement accuracy.

The HC-SR04 sensor is widely used in various projects, such as distance measurement, robot control, obstacle avoidance systems, and other applications that require distance detection.

If we refer to the documentation, we can learn that the HC-SR04 operates within an operating voltage range of 3.3Vdc to 5Vdc, and it has an operating current of 15mA.

Ultrasonic-datasheet

My board meets these requirements, so let’s proceed with the programming.

Initially, I attempted to copy the code provided in the documentation, which was quite lengthy and couldn’t be uploaded to the board successfully. So, I decided to approach this issue differently.

I asked Chat GPT to provide me with the code for the HC-SR04 ultrasonic distance sensor, and it generated the following code:

#define PIN_TRIG 16
#define PIN_ECHO 15

long duration, cm;

void setup() {

   // Initialize communication on the serial port

   Serial.begin(9600);
   //Define inputs and outputs
   pinMode(PIN_TRIG, OUTPUT);
   pinMode(PIN_ECHO, INPUT);
}

void loop() {

   // First, we generate a short pulse with a duration of 2-5 microseconds.

   digitalWrite(PIN_TRIG, LOW);
   delayMicroseconds(5);
   digitalWrite(PIN_TRIG, HIGH);

   // With the signal high, wait about 10 microseconds. At this point, the sensor will send signals at a frequency of 40 kHz.
   delayMicroseconds(10);
   digitalWrite(PIN_TRIG, LOW);

   // The delay time of the acoustic signal on the echo sounder.
   duration = pulseIn(PIN_ECHO, HIGH);

   // Now it remains to convert time to distance
   cm = (duration / 2) / 29.1;

   Serial.print("Distance to object: ");
   Serial.print(cm);
   Serial.println("cm.");

   // Delay between measurements for the sketch to work correctly
   delay(250);
}

Yes, the code worked and the Serial Monitor displayed the values of the distance to the object. The only thing I didn’t like about this code is that the sensor can give incorrect values. This mainly happens if the distance to the object is too large or small, or if the object does not reflect the sound wave well.

Serial monitor bad values

In order to avoid issuing incorrect values, I decided to prescribe the condition that if the distance exceeds 400 cm, then Distance was measured incorrectly should be displayed on the serial monitor, otherwise the distance value.

if (cm > 400) {
    Serial.println("Distance was measured incorrectly");
  } else {
    Serial.print("Distance to object: ");
    Serial.print(cm);
    Serial.println("cm.");
  }

And I will change the time so that the calculations are performed every 2 seconds:

delay(2000);

And so, the final code will be the following:

#define PIN_TRIG 16
#define PIN_ECHO 15

long duration, cm;

void setup() {

   // Initialize communication on the serial port

   Serial.begin(9600);
   //Define inputs and outputs
   pinMode(PIN_TRIG, OUTPUT);
   pinMode(PIN_ECHO, INPUT);
}

void loop() {

   // First, we generate a short pulse with a duration of 2-5 microseconds.

   digitalWrite(PIN_TRIG, LOW);
   delayMicroseconds(5);
   digitalWrite(PIN_TRIG, HIGH);

   // With the signal high, wait about 10 microseconds. At this point, the sensor will send signals at a frequency of 40 kHz.
   delayMicroseconds(10);
   digitalWrite(PIN_TRIG, LOW);

   // The delay time of the acoustic signal on the echo sounder.
   duration = pulseIn(PIN_ECHO, HIGH);

   // Now it remains to convert time to distance
   cm = (duration / 2) / 29.1;

  if (cm > 400) {
    Serial.println("Distance was measured incorrectly");
  } else {
    Serial.print("Distance to object: ");
    Serial.print(cm);
    Serial.println("cm.");
  }

   // Delay between measurements for the sketch to work correctly
   delay(2000);
}
And if you now look at the Serial Monitor, then in case of an incorrect calculation of the value, the following message is displayed: Distance was measured incorrectly.

Serial monitor bad values

Infrared rangefinder

I decided to connect a rangefinder Sharp 2Y0A21 to my board.

Sharp 2Y0A21 is an infrared distance sensor. It emits infrared light that bounces off an object and then measures the delay time of the reflected signal. Based on this delay time, the sensor calculates the distance to the object.

Sharp 2Y0A21

It is important to note that the Sharp 2Y0A21 rangefinder is designed to measure distances in the range of approximately 10 cm to 80 cm. It can be used for obstacle detection, distance control and other similar tasks.

I gave power to the sensor from my board and connected the signal output of the sensor to PIN 2:

Sharp first contact

Found on the Internet ready-made code and decided to upload it on my board.

const int IRpin = A0;          // analog pin for connecting the Vo sensor output
int value1;                    // to store an analog value

void setup() {
  Serial.begin(9600);            // Starting the serial port
  }

void loop() {
  Serial.println(irRead(), DEC);
 // we get a smoothed value and translate into voltage
 float volts = analogRead(IRpin)*0.0048828125;
 // and in distance in cm
 float distance=32*pow(volts,-1.10);
 Serial.print(distance);      // send value to port
 delay(200);                    
}

// Averaging multiple values for smoothing
int irRead() {
  int averaging = 0;             //  variable for summarizing data

  // Getting 5 values
  for (int i=0; i<5; i++) {
    value1 = analogRead(IRpin);
    averaging = averaging + value1;
    delay(55);      // Wait 55 ms before each read
  }
  value1 = averaging / 5;      // average values
  return(value1);              
} 

Ultimately, the code did not load onto the board and an error was thrown. At first I thought that the problem was with the board and some contacts were not correct, but to my delight our colleague Maxime Richard suggested that the problem due to the fact that this code is not loaded for the reason that there is not enough space on the microcontroller to add this code.

Not enough space

After many attempts and fails I decided to write the code from scratch using analog read example of arduino. The example code reads the analog value from analog pin (in our case pin 2) and outputs to the serial monitor. I wanted to have an action based on a threshold so I connected a piezo buzzer to digital pin 3 and modified the code to generate a simple pulse train when the analog value is greater than 800.

Sharp and pezo

Piezo buzzer is a device that converts an electrical signal into sound vibrations. It is used to generate sound signals in various electronic devices and warning systems.

Here’s the code and the result.

int sensorValue = 0;

void setup() {
  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);
  Serial.begin(9600);
}
void loop() {
  // read the analog in value:
  sensorValue = analogRead(2);

  if(sensorValue > 800){  
  digitalWrite(3, HIGH);
  delayMicroseconds(125);
  digitalWrite(3, LOW);
  delayMicroseconds(125);
  }
  // print the results to the Serial Monitor:
  Serial.print("sensor = ");
  Serial.print(sensorValue);
}

Hall sensor

During this week I also tested SMD hall sensor A1324LLHLT-T since I’m going to use it in my final project to detect the moment when the watch handle passes the 12:00 on the watch dial. I designed a board in Kicad to be able to connect it to my board.

schematic

I also added a decoupling capacitor that was indicated in the datasheet (page10) under Typical Application Circuit diagram.

application circuit

The hall sensor has sot23 package that is a common type of 3 legged components like voltage regulators, transistors etc…

footprint

I then milled the board, soldered the components in place here’s the result

pcb-sensor

Then I connected tho my setup just by replacing IR sensor with my new hall sensor.

connected

Since it’s an analog device it will work similar to IR distance sensor and there’s no need to build a voltage divider circuit around it. I simply replaced IR sensor with my new setup of hall sensor. The code is the same as in IR sensor’s case. Here is the the video:

Microcontroller lock

During the uploading and testing process, I encountered a situation where I accidentally unplugged the board from the USB port before the code could finish uploading. This resulted in my board becoming unrecognized by the computer.

I tried restarting the Arduino IDE, restarting the computer, and changing the port, but none of these steps resolved the issue. The computer still couldn’t recognize my board. I then used a multimeter to check the contacts, and all the connections were fine.

I even attempted to reload the bootloader, and the upload was successful, but the board remained unrecognized by the computer.

Then I shared the incident with Babken Chugaszyan and asked him for help. Babken initially tried to find a solution to the problem within the Fab community, but when he couldn’t find one, he started searching for a solution on the internet. Unfortunately, he couldn’t find a solution there either.

Then we decided to check what commands are available in the EDGB software for microcontroller programming. You can find the commands here.

Not enough space

The most harmless at first glance seemed to be the following command:

-u, --unlock     unlock the chip (forces chip erase in most cases)

so the final command that unlocks and erases the chip is the following:

./edbg.exe -b -t samd11 -pv -u

Then we proceeded to install the bootloader again, so it is possible that the entire program was removed by the command * –unlock*

./edbg.exe -b -t samd11 -pv -f sam_ba_SAMD11D14AS.bin

After performing these operations, my board became recognizable by computers.

I am not aware of the details regarding the automatic microcontroller lockout, but it is an issue that can arise and can be resolved.

Conclusion

I’ve come to the conclusion that coding should be task-based, and an example of this would be using an infrared rangefinder in my project. My task was to make the piezo buzzer emit a sound if the object was approaching closer than a given distance. However, the microcontroller on my board did not have enough memory to load the code associated with the infrared rangefinder, as complex calculations were required to convert the analog signal value to centimeters. Since my task did not require an accurate determination of the distance from the infrared sensor, I focused on one fixed value when programming.

Also, I liked the use of the Hall sensor. To use it, I needed to develop a board for its installation.

Files

KiCad project files for Hall sensor board

SVG files for carving and cutting the Hall sensor board

INO - ultrasonic sensor

INO - analog alarm


Last update: June 22, 2023