Introduction: Distance Sensor With Arduino and Raspberry Pi
Have you ever thought of building your own project with a distance sensor? If yes then this project could be a foundation to the project you are building on. You will be able to calculate the distance through a distance sensor which will be displayed in the screen.
Step 1: Required Items
This are the required items that the project could be created using.
All you need is:
Distance sensor
Wires
Breadboard
Screen
Raspberry Pi
SD card of 8 gb minimum
Software:
Arduino IDE
Windows 10
Visual Studio Community 2015 update 3
Universal Windows Platform installed
Windows 10 IoT Core Dashboard
All you need is:
Distance sensor
Wires
Breadboard
Screen
Raspberry Pi
SD card of 8 gb minimum
Software:
Arduino IDE
Windows 10
Visual Studio Community 2015 update 3
Universal Windows Platform installed
Windows 10 IoT Core Dashboard
Step 2: How to Put It Together?
Step 1: Connect the raspberry pi to the screen through wires where we have to connect to a 5v pin, a signal wire and a ground from the raspberry pi to the LCD screen.
Step 2: Install the software into a SD card through the windows iot dashboard and slot in the SD card into the raspberry pi after completion.
Step 2: Power up the raspberry pi and make sure that the screen boots up, otherwise repeat step 1 and 2.
Step 3: Connect a ethernet cable from the raspberry pi to the router, then Connect a ethernet from your computer to your router.
Step 4: Make sure there is an active connection seen in the windows iot dashboard, otherwise check your connection cables.
NOTE: NEVER DO WIRING OR POWERING IT DOWN BEFORE SHUTDOWN.
Step 5: Connect the Distance sensor into the breadboard then use some male to male wires to connect the breadboard to the Arduino.
Step 6: Connect the Arduino to your computer and run the Arduino IDE.
Step 7: Install the library named "distance" in the Arduino, and run the sample code that is within the library and make sure there is active reading.
Step 8: Run the Visual studios in your computer and reference the Library to windows iot extension then create a new Universal application project, after that add the Package "Microsoft.Toolkit.Uwp.UI.Controls" to the project.
Step 9: Copy paste the codes in the attached zip file into both visual studios and Arduino.
Step 10: Set the connection to debug ARM, and click on remote machine and not on local machine to deploy application to the Pi.
Step 11: Click on the remote machine on the top and wailaaaaaaa! You have successfully deployed a Distance sensor project.
Step 2: Install the software into a SD card through the windows iot dashboard and slot in the SD card into the raspberry pi after completion.
Step 2: Power up the raspberry pi and make sure that the screen boots up, otherwise repeat step 1 and 2.
Step 3: Connect a ethernet cable from the raspberry pi to the router, then Connect a ethernet from your computer to your router.
Step 4: Make sure there is an active connection seen in the windows iot dashboard, otherwise check your connection cables.
NOTE: NEVER DO WIRING OR POWERING IT DOWN BEFORE SHUTDOWN.
Step 5: Connect the Distance sensor into the breadboard then use some male to male wires to connect the breadboard to the Arduino.
Step 6: Connect the Arduino to your computer and run the Arduino IDE.
Step 7: Install the library named "distance" in the Arduino, and run the sample code that is within the library and make sure there is active reading.
Step 8: Run the Visual studios in your computer and reference the Library to windows iot extension then create a new Universal application project, after that add the Package "Microsoft.Toolkit.Uwp.UI.Controls" to the project.
Step 9: Copy paste the codes in the attached zip file into both visual studios and Arduino.
Step 10: Set the connection to debug ARM, and click on remote machine and not on local machine to deploy application to the Pi.
Step 11: Click on the remote machine on the top and wailaaaaaaa! You have successfully deployed a Distance sensor project.
Step 3: What'a the Use of Such Projects?
Every building has its foundation, on my personal perception I would say that the distance sensor project is just a base which allows you to build more on top of it. There are various projects that you would be able to do with this Distance sensor:
Some projects that you might be able to work on...
• Security system
• Portable distance calculator than a tape
.
.
.
There are many projects that you could work on.
Some projects that you might be able to work on...
• Security system
• Portable distance calculator than a tape
.
.
.
There are many projects that you could work on.
Step 4: Necessary Codes.
I have attached code for NFC RFID too, remove the codes if you are not using that.
PASTE IN VISUAL STUDIOS
• .Xaml
x:Name="Page"
x:Class="Sharp.Home"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Sharp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
mc:Ignorable="d" Height="480" Width="800">
x:Name="RadialGauge"
Value="0"
Minimum="0"
Maximum="999"
StepSize="1"
IsInteractive="True"
TickSpacing="20"
ScaleWidth="26"
MinAngle="-150"
MaxAngle="158"
Unit="ADC"
TickBrush="Gainsboro"
ScaleTickBrush="{ThemeResource ApplicationPageBackgroundThemeBrush}"
UnitBrush="White"
ValueBrush="White"
NeedleWidth="1"
TickLength="15" Margin="218,92,305,77" />
x:Name="RadialGauge_Copy"
Value="0"
Minimum="7"
Maximum="60"
StepSize="1"
IsInteractive="True"
TickSpacing="20"
ScaleWidth="26"
MinAngle="-150"
MaxAngle="158"
Unit="CM"
TickBrush="Gainsboro"
ScaleTickBrush="{ThemeResource ApplicationPageBackgroundThemeBrush}"
UnitBrush="White"
ValueBrush="White"
NeedleWidth="1"
TickLength="15" Margin="490,92,15,77" />
•Xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Enumeration;
using Windows.Devices.I2c;
using System.Diagnostics;
using System.Threading;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Sharp
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
///
public sealed partial class Home : Page
{
private I2cDevice Device;
private Timer periodicTimer;
private int sampleFrequency = 500; // 1 second
private double storageadc = 0;
private double storagedist = 0;
private double checksum = 0;
public Home()
{
this.InitializeComponent();
SetupI2C();
}
private async void SetupI2C()
{
var settings = new I2cConnectionSettings(0x40); // Arduino address
settings.BusSpeed = I2cBusSpeed.StandardMode;
string aqs = I2cDevice.GetDeviceSelector("I2C1");
var dis = await DeviceInformation.FindAllAsync(aqs);
Device = await I2cDevice.FromIdAsync(dis[0].Id, settings);
// Start a timer
periodicTimer = new Timer(this.TimerGetAndDisplay
, null, 0, sampleFrequency);
}
private void TimerGetAndDisplay(object state)
{
if (checksum != 1)
{
byte[] RegAddrBuf = new byte[] { 0x40 }; // Arduino address
byte[] ReadBuf = new byte[6];
try
{
Device.Read(ReadBuf); // read the data
}
catch (Exception f)
{
Debug.WriteLine(f.Message);
}
// Decodes a sequence of bytes from the specified byte array into a string
// GetString: First parameter is the byte array
// Second parameter is the index of the first byte to decode
// Third parameter is the number of bytes to decode
char[] tArray = System.Text.Encoding.UTF8.GetString(ReadBuf, 0, 2).
ToCharArray();
char[] adcArray = System.Text.Encoding.UTF8.GetString(ReadBuf, 2, 3).
ToCharArray();
char[] nfcArray = System.Text.Encoding.UTF8.GetString(ReadBuf, 5, 1).
ToCharArray();
// Convert the character array into a string.
String c = new String(tArray);
String a = new String(adcArray);
string dist = c.Substring(0, 2);
string adc = a.Substring(0, 3);
Debug.WriteLine(dist);
Debug.WriteLine(adc);
if (checksum != 1)
{
var task1 = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{ RadialGauge.Value = Convert.ToInt32(adc); RadialGauge_Copy.Value = Convert.ToInt32(dist); });
}
}
}
}
}
• Arduino
#include
#include "SPI.h"
#include "MFRC522.h"
#define SS_PIN 10
#define RST_PIN 9
#define SP_PIN 8
#define SLAVE_ADDRESS 0x40
#define buzzer 6
MFRC522 rfid(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
char dist [5];
char adc [5];
char nfcCheck [1];
int x = 0;
int distance = 0;
int AVERAGING_LOOP_SIZE = 50;
int READ_PIN = 0; // Analogue pin
int RED_LED = 3; // wire other side to +5V and use min 220 Ohm resistor
int DISTANCE_BUFFER = 1; //cm
int MIN_DISTANCE = 7; // cm
int MAX_DISTANCE = 60; // cm
int IGNORE_BUFFER_THRESHHOLD = 35; // Readings
int thisDistance, lastDistance, ignoreBuffer, val;
String thisPrint, lastPrint;
int nfc = 0;
int nfcmethod(int newNfc);
int check = 0;
const int door = 8;
void setup() {
pinMode(READ_PIN, INPUT);
pinMode(RED_LED, OUTPUT);
pinMode(door, INPUT_PULLUP);
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
ignoreBuffer = 0;
SPI.begin();
rfid.PCD_Init();
}
void loop() {
val = 0;
x=analogRead(READ_PIN);
// Averaging Loop
for (int i = 0; i < AVERAGING_LOOP_SIZE ; i++) {
{
val = val + x;
}
}
val = val / AVERAGING_LOOP_SIZE;
thisDistance = (6762 / (val - 9)) - 4;
distance = thisDistance;
if ((thisDistance < MIN_DISTANCE) ||
(thisDistance > MAX_DISTANCE))
{
thisPrint = "No Object";
distance = 00;
digitalWrite(RED_LED, HIGH);
}
else if ((thisDistance < lastDistance + DISTANCE_BUFFER) ||
(thisDistance > lastDistance - DISTANCE_BUFFER))
{
ignoreBuffer ++;
if (ignoreBuffer > IGNORE_BUFFER_THRESHHOLD) {
thisPrint = "Object is now at: " + String(thisDistance) + "cm.";
lastDistance = thisDistance;
ignoreBuffer = 0;
if (thisDistance > 20)
{
digitalWrite(RED_LED, LOW);
delay(5000);
if(thisDistance > 20){
int check = nfcmethod(nfc);
for (int loop1 = 0; loop1 < 1000; loop1++)
{
check = nfcmethod(nfc);
if (check == 0)
{
tone (buzzer, 500);
check = nfcmethod(nfc);
if (check == 1)
{
noTone(buzzer);
break;
}
}
}
}
}
}
}
dtostrf(distance, 2, 0, dist);
dtostrf(x, 3, 0, adc);
Wire.onRequest(sendDataToPi);
if (thisPrint != lastPrint) {
Serial.println(thisPrint);
lastPrint = thisPrint;
Serial.print("Analog value: ");
Serial.println(x);
delay(500);
}
}
int nfcmethod(int newNfc) {
if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial())
return newNfc;
MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
Serial.println(F("Your tag is not of type MIFARE Classic."));
return newNfc;
}
String strID = "";
for (byte i = 0; i < 4; i++) {
strID +=
(rfid.uid.uidByte[i] < 0x10 ? "0" : "") +
String(rfid.uid.uidByte[i], HEX) +
(i!=3 ? ":" : "");
}
strID.toUpperCase();
Serial.print("Tap card key: ");
Serial.println(strID);
if (strID != "")
{
newNfc = 1;
}
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
return newNfc;
}
void sendDataToPi()
{
Wire.write(dist);
Wire.write(adc);
}
PASTE IN VISUAL STUDIOS
• .Xaml
x:Name="Page"
x:Class="Sharp.Home"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Sharp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
mc:Ignorable="d" Height="480" Width="800">
x:Name="RadialGauge"
Value="0"
Minimum="0"
Maximum="999"
StepSize="1"
IsInteractive="True"
TickSpacing="20"
ScaleWidth="26"
MinAngle="-150"
MaxAngle="158"
Unit="ADC"
TickBrush="Gainsboro"
ScaleTickBrush="{ThemeResource ApplicationPageBackgroundThemeBrush}"
UnitBrush="White"
ValueBrush="White"
NeedleWidth="1"
TickLength="15" Margin="218,92,305,77" />
x:Name="RadialGauge_Copy"
Value="0"
Minimum="7"
Maximum="60"
StepSize="1"
IsInteractive="True"
TickSpacing="20"
ScaleWidth="26"
MinAngle="-150"
MaxAngle="158"
Unit="CM"
TickBrush="Gainsboro"
ScaleTickBrush="{ThemeResource ApplicationPageBackgroundThemeBrush}"
UnitBrush="White"
ValueBrush="White"
NeedleWidth="1"
TickLength="15" Margin="490,92,15,77" />
•Xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Enumeration;
using Windows.Devices.I2c;
using System.Diagnostics;
using System.Threading;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Sharp
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
///
public sealed partial class Home : Page
{
private I2cDevice Device;
private Timer periodicTimer;
private int sampleFrequency = 500; // 1 second
private double storageadc = 0;
private double storagedist = 0;
private double checksum = 0;
public Home()
{
this.InitializeComponent();
SetupI2C();
}
private async void SetupI2C()
{
var settings = new I2cConnectionSettings(0x40); // Arduino address
settings.BusSpeed = I2cBusSpeed.StandardMode;
string aqs = I2cDevice.GetDeviceSelector("I2C1");
var dis = await DeviceInformation.FindAllAsync(aqs);
Device = await I2cDevice.FromIdAsync(dis[0].Id, settings);
// Start a timer
periodicTimer = new Timer(this.TimerGetAndDisplay
, null, 0, sampleFrequency);
}
private void TimerGetAndDisplay(object state)
{
if (checksum != 1)
{
byte[] RegAddrBuf = new byte[] { 0x40 }; // Arduino address
byte[] ReadBuf = new byte[6];
try
{
Device.Read(ReadBuf); // read the data
}
catch (Exception f)
{
Debug.WriteLine(f.Message);
}
// Decodes a sequence of bytes from the specified byte array into a string
// GetString: First parameter is the byte array
// Second parameter is the index of the first byte to decode
// Third parameter is the number of bytes to decode
char[] tArray = System.Text.Encoding.UTF8.GetString(ReadBuf, 0, 2).
ToCharArray();
char[] adcArray = System.Text.Encoding.UTF8.GetString(ReadBuf, 2, 3).
ToCharArray();
char[] nfcArray = System.Text.Encoding.UTF8.GetString(ReadBuf, 5, 1).
ToCharArray();
// Convert the character array into a string.
String c = new String(tArray);
String a = new String(adcArray);
string dist = c.Substring(0, 2);
string adc = a.Substring(0, 3);
Debug.WriteLine(dist);
Debug.WriteLine(adc);
if (checksum != 1)
{
var task1 = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{ RadialGauge.Value = Convert.ToInt32(adc); RadialGauge_Copy.Value = Convert.ToInt32(dist); });
}
}
}
}
}
• Arduino
#include
#include "SPI.h"
#include "MFRC522.h"
#define SS_PIN 10
#define RST_PIN 9
#define SP_PIN 8
#define SLAVE_ADDRESS 0x40
#define buzzer 6
MFRC522 rfid(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
char dist [5];
char adc [5];
char nfcCheck [1];
int x = 0;
int distance = 0;
int AVERAGING_LOOP_SIZE = 50;
int READ_PIN = 0; // Analogue pin
int RED_LED = 3; // wire other side to +5V and use min 220 Ohm resistor
int DISTANCE_BUFFER = 1; //cm
int MIN_DISTANCE = 7; // cm
int MAX_DISTANCE = 60; // cm
int IGNORE_BUFFER_THRESHHOLD = 35; // Readings
int thisDistance, lastDistance, ignoreBuffer, val;
String thisPrint, lastPrint;
int nfc = 0;
int nfcmethod(int newNfc);
int check = 0;
const int door = 8;
void setup() {
pinMode(READ_PIN, INPUT);
pinMode(RED_LED, OUTPUT);
pinMode(door, INPUT_PULLUP);
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
ignoreBuffer = 0;
SPI.begin();
rfid.PCD_Init();
}
void loop() {
val = 0;
x=analogRead(READ_PIN);
// Averaging Loop
for (int i = 0; i < AVERAGING_LOOP_SIZE ; i++) {
{
val = val + x;
}
}
val = val / AVERAGING_LOOP_SIZE;
thisDistance = (6762 / (val - 9)) - 4;
distance = thisDistance;
if ((thisDistance < MIN_DISTANCE) ||
(thisDistance > MAX_DISTANCE))
{
thisPrint = "No Object";
distance = 00;
digitalWrite(RED_LED, HIGH);
}
else if ((thisDistance < lastDistance + DISTANCE_BUFFER) ||
(thisDistance > lastDistance - DISTANCE_BUFFER))
{
ignoreBuffer ++;
if (ignoreBuffer > IGNORE_BUFFER_THRESHHOLD) {
thisPrint = "Object is now at: " + String(thisDistance) + "cm.";
lastDistance = thisDistance;
ignoreBuffer = 0;
if (thisDistance > 20)
{
digitalWrite(RED_LED, LOW);
delay(5000);
if(thisDistance > 20){
int check = nfcmethod(nfc);
for (int loop1 = 0; loop1 < 1000; loop1++)
{
check = nfcmethod(nfc);
if (check == 0)
{
tone (buzzer, 500);
check = nfcmethod(nfc);
if (check == 1)
{
noTone(buzzer);
break;
}
}
}
}
}
}
}
dtostrf(distance, 2, 0, dist);
dtostrf(x, 3, 0, adc);
Wire.onRequest(sendDataToPi);
if (thisPrint != lastPrint) {
Serial.println(thisPrint);
lastPrint = thisPrint;
Serial.print("Analog value: ");
Serial.println(x);
delay(500);
}
}
int nfcmethod(int newNfc) {
if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial())
return newNfc;
MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
Serial.println(F("Your tag is not of type MIFARE Classic."));
return newNfc;
}
String strID = "";
for (byte i = 0; i < 4; i++) {
strID +=
(rfid.uid.uidByte[i] < 0x10 ? "0" : "") +
String(rfid.uid.uidByte[i], HEX) +
(i!=3 ? ":" : "");
}
strID.toUpperCase();
Serial.print("Tap card key: ");
Serial.println(strID);
if (strID != "")
{
newNfc = 1;
}
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
return newNfc;
}
void sendDataToPi()
{
Wire.write(dist);
Wire.write(adc);
}