Using Distance sensor and shock sensor in 1 arduino board

Hello, I am trying to put 2 functions in a single board. This is a simple version of it. The distance sensor seems to work well but the shock sensor is not sending the 'Hello'. But if without the distance sensor codes, the shock sensor works. Is it possible to let both of them work? If yes, i need help on how to write the proper codes :sob: :sob:

#include <SharpIR.h>

#define ir A6
#define model 20150
SharpIR SharpIR(ir, model);
#define sensor 10
int sensor_state = 0;
 

void setup() {
  pinMode (sensor, INPUT);
  Serial.begin (9600);
}

void loop() { 
  shock();
  distancesensor();
}


void shock()
{
  sensor_state = digitalRead (sensor);
  if (sensor_state == 1){
    Serial.println ("Hello");
  }
}

void distancesensor()
{
  int dis=SharpIR.distance();  // this returns the distance to the object you're measuring
    Serial.println(dis);
    delay(2000);
  }  

The delay function stops execution of the code. Your code spends nearly all of the time doing nothing. The shock sensor is only read once every 2 seconds or so. So you are lucky if you happen to pick up a shock.

Try this:

#include <SharpIR.h>

#define ir A6
#define model 20150
SharpIR SharpIR(ir, model);
#define sensor 10
int sensor_state = 0;


void setup()
{
   pinMode (sensor, INPUT);
   Serial.begin (9600);
}

void loop()
{
   shock();
   distancesensor();
}

void shock()
{
   sensor_state = digitalRead (sensor);
   if (sensor_state == 1)
   {
      Serial.println ("Hello");
   }
}

// call this function every time through loop, but 
// get a new range only every 2 seconds
void distancesensor()  
{
   static unsigned long timer = 0; // see BWOD example
   unsigned long interval = 2000;
   if (millis() - timer >= interval)
   {
      timer = millis();
      int dis = SharpIR.distance(); // this returns the distance to the object you're measuring
      Serial.println(dis);      
   }
}

This is untested. It uses the blink without delay method for non-blocking coding so that the shock sensor can be read much more often.

Non-blocking timing tutorials:
Blink without delay().
Blink without delay detailed explanation
Beginner's guide to millis().
Several things at a time.

Could it be anything to do with the two seconds it spends twiddling thumbs?

The code u gave works. THX! I will look into the tutorials u've listed. Thank you very much. :smiley:

Glad that I could help.

Learning to do non-blocking coding is one of most important concepts to coding embedded processors.

If your question has been answered to your satisfaction, please mark the thread as solved so that other members that wish to help will not waste their time opening the thread only to find that you no longer require assistance.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.