Example Code for Arduino Material Detection

This article offers a comprehensive guide to detecting materials using Arduino, featuring sample code, wiring diagrams, and step-by-step setup instructions for both IO and serial modes, including results for detecting soft and hard materials.

Hardware Preparation

Software Preparation

Arduino IDE Click to Download Arduino IDE from Arduino®

Other Preparation Work

supports IO mode and serial mode. The IO mode is used by default when the module is powered on.

IO mode Wiring Diagram

IO mode Wiring Diagram

UNO R3 PIN sensor PIN
UNO R3 Digital 8 sensor TX/IO
UNO R3 GND sensor GND
UNO R3 VCC sensor 3.3V

IO mode Sample Code

int ledPin = 13; // LED connected to digital pin 13
int inPin = 8;   // pushbutton connected to digital pin 8
int val = 0;     // variable to store the read value

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin 13 as output
  pinMode(inPin, INPUT);      // sets the digital pin 8 as input
  digitalWrite(ledPin, LOW);
}
void loop() {
  val = digitalRead(inPin);   // read the input pin
  if (val)
  {
    digitalWrite(ledPin, HIGH);
  }
  else
  {
    digitalWrite(ledPin, LOW);
  }
  delay(50);
}

Result

When the target material is a soft material, the TX pin outputs a low level of 0V, the LED is off;
When the target material is a hard material, the TX pin outputs a high level of 3.3V, the LED is on

Serial mode Wiring Diagram

Serial mode Wiring Diagram

UNO R3 PIN sensor PIN
UNO R3 Digital 9 sensor TX/IO
UNO R3 GND sensor GND
UNO R3 VCC sensor 3.3V
UNO R3 Digital 10 sensor RX

Serial mode Sample Code

#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10); // RX, TX

unsigned char Send_Date[6] = {0XAA,0XAA,0XFE,0X01,0X00,0X53};
unsigned char buffer_RTT[100] = {}; 
uint8_t checksum = 0;

void setup() {
  Serial.begin(9600);
  mySerial.begin(115200);
  mySerial.write(Send_Date,6);
}

void loop() {
 while (mySerial.available() > 0) 
 {
   if(mySerial.read() == 0XAA)
   {
     buffer_RTT[0]=0XAA;
     for(int i=1;i<8;i++)
     {
       buffer_RTT[i]=mySerial.read();
       }
       checksum =(buffer_RTT[0]+buffer_RTT[1]+buffer_RTT[2]+buffer_RTT[3]+buffer_RTT[4]+buffer_RTT[5]+buffer_RTT[6])&0X00FF;
      if(buffer_RTT[7]== checksum)
      {
        Serial.println(buffer_RTT[4]);				//read data bit status
      }
   }
 }
 delay(5);
}

Result

When hard material is detected, the serial port prints 0; when soft material is detected, the serial port prints 1.

Serial mode Result

Was this article helpful?

TOP