Guest User

Untitled

a guest
Jun 24th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. #include "pitches.h"
  2. //Pins
  3. int redLEDPin = 10;
  4. int grnLEDPin = 9;
  5. int speakerPin = 3;
  6. int analogInPin = A0; //analog input pin that the potentiometer is attached to
  7. int sonarPin = A1;
  8. //----
  9. //sensor values
  10. int targetDistance = 0; //potentiometer
  11. int sensorValue = 0; //sonar
  12. int outputValueRed = 0; //Red LED
  13. int outputValueGrn = 0; //Green LED
  14. int distance = 0;
  15.  
  16. boolean play = false; //to play or not to play the melody
  17.  
  18. void setup(){
  19. analogReference(DEFAULT);
  20. // initialize serial communications at 9600 bps:
  21. Serial.begin(9600);
  22. //playMelody();
  23. }
  24.  
  25. void loop(){
  26. delay(50);
  27. play = false;
  28. // read the analog in value:
  29. //The three is to make the potentiometer less erratic
  30. targetDistance = analogRead(analogInPin) / 3;
  31.  
  32. //conversion to inch based on experiment and docs
  33. sensorValue = analogRead(sonarPin)*6/11;
  34.  
  35. //Serial.print("ActualDistance: ");
  36. //Serial.println(sensorValue);
  37. //Serial.print("SpecifiedDistance: ");
  38. //Serial.println(targetDistance);
  39.  
  40. if(abs(targetDistance - sensorValue) <= 5){
  41. outputValueGrn = 0;
  42. outputValueRed = 0;
  43. distance = 0;
  44. play = true;
  45.  
  46. }else if(targetDistance - sensorValue < -5){//If too far
  47. //Serial.println("Too Far");
  48. outputValueGrn = 0;
  49. distance = sensorValue - targetDistance;
  50. //Serial.print("Difference: ");
  51. //Serial.println(distance);
  52. if(distance <=40){
  53. outputValueRed = map(distance, 5, 40, 0, 200);
  54. }else{
  55. outputValueRed = 255;
  56. }
  57. }else{ //if too close
  58. //Serial.println("Too Close");
  59. outputValueRed = 0;
  60. distance = targetDistance - sensorValue;
  61. //Serial.print("Difference: ");
  62. //Serial.println(distance);
  63. if(distance <=40){
  64. outputValueGrn = map(distance, 5, 40, 0, 200);
  65. }else{
  66. outputValueGrn = 255;
  67. }
  68. }
  69. //outputValue = map(0, 0, 1023, 0, 255);
  70. analogWrite(redLEDPin, outputValueRed);
  71. analogWrite(grnLEDPin, outputValueGrn);
  72. //Serial.println("");
  73. //Serial.print("red: ");
  74. Serial.println(outputValueRed);
  75. //Serial.print("grn: ");
  76. Serial.println(outputValueGrn);
  77. if(play){
  78. playTone();
  79. }
  80. Serial.println("");
  81. }
  82.  
  83. //the method to play the tone
  84. void playTone(){
  85. tone(speakerPin, NOTE_C4 ,1000/4);
  86. delay(1000/4*1.30);
  87. noTone(speakerPin);
  88.  
  89. }
Add Comment
Please, Sign In to add comment