Code for tm1637 and ultrasonic sensor not working

In this code there d1 and d2 are the two terminals of a switch, but when the switch is pressed there is no effect. Please help



#include <NewPing.h>

#define TRIGGER_PIN  12  
#define ECHO_PIN     11  
#define MAX_DISTANCE 400 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); 

////////////////////////////
#include <Arduino.h>
#include <TM1637Display.h>

// Module connection pins (Digital Pins)
#define CLK 2
#define DIO 3
// The amount of time (in milliseconds) between tests
#define TEST_DELAY  500
TM1637Display display(CLK, DIO);
/////////////////////////
int d1 = 6;
int d2 = 7;
int distance;

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  pinMode (d1, OUTPUT);
  pinMode (d2, INPUT);
   distance = 0;
    uint8_t data[] = { 0x0, 0x0, 0x0, 0x0 };
  display.setSegments(data);
    display.setBrightness(0x0f);
  

}
  int Valued2; 
    

 
void loop() {

  Valued2=0;
  digitalWrite(d1 , HIGH);
  delay(50);
  Valued2 = digitalRead(d2);  
  delay(50);
   Serial.print("D2 Valude");
  Serial.println(Valued2);
  delay(100);
 
  if (Valued2 == HIGH)    
  {  
    distance = sonar.ping_cm();
  
  }  

 //else   
  {  


  Serial.println("cm");
  display.showNumberDec(distance, false, 3, 1);
  delay(100);
}
}

You could add some prints to tell you what values you are getting.

You've got some crazy scope going on there...and a crazy use of an "else". Think about it.

Depending on how things are wired, pinMode (d2, INPUT); change to pinMode (d2, INPUT_PULLUP);


FYI

Recommend wiring switch similar to S3 below:
Always show us a good schematic of your proposed circuit.
Show us a good image of your ‘actual’ wiring.
Give links to components.

Why do you initialize it, and then almost immediately overwrite it?

Why commented out? You said nothing.

I solved the problem. I added a 200ohm pull down resistor to the switch and changed the program and it worked. Thanks for the help

1 Like

Hey, that's great! One thing, 200 ohms is way too low for a typical pull up. Should be more like 1k - 10k.

Probably, the INPUT_PULLUP method mentioned in the exhaustive reply #3, would also work, and would eliminate the need for any resistor.

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