Difference between revisions of "Arduino - čítanie z Ultrazvukového senzora pomocou prerušení"
(Created page with "Tento program číta z ultrazvukového senzora pomocou prerušení: <syntaxhighlight lang="C" line=line> #define TRIG 7 #define ECHO 8 void setup() { init_ultrasonic();...") |
m |
||
Line 1: | Line 1: | ||
Tento program číta z ultrazvukového senzora pomocou prerušení: | Tento program číta z ultrazvukového senzora pomocou prerušení: | ||
− | <syntaxhighlight lang="C" line=line> | + | <syntaxhighlight lang="C" line='line'> |
#define TRIG 7 | #define TRIG 7 | ||
#define ECHO 8 | #define ECHO 8 | ||
Line 66: | Line 66: | ||
delay(100); | delay(100); | ||
} | } | ||
− | </ | + | </syntaxhighlight> |
Latest revision as of 06:06, 3 August 2018
Tento program číta z ultrazvukového senzora pomocou prerušení:
1 #define TRIG 7
2 #define ECHO 8
3
4 void setup() {
5 init_ultrasonic();
6 Serial.begin(9600);
7 }
8
9 static volatile uint32_t pulse_start;
10 static volatile int16_t distance;
11 static volatile uint8_t new_distance;
12
13 void init_ultrasonic()
14 {
15 pinMode(ECHO, INPUT);
16 pinMode(TRIG, OUTPUT);
17
18 PCMSK0 |= 1; //PCINT0;
19 PCIFR &= ~1; //PCIF0;
20 PCICR |= 1; // PCIE0;
21 }
22
23 ISR(PCINT0_vect)
24 {
25 if (PINB & 1) pulse_start = micros();
26 else
27 {
28 distance = (int16_t)((micros() - pulse_start) / 58);
29 new_distance = 1;
30 }
31 }
32
33 void start_distance_measurement()
34 {
35 distance = -1;
36 new_distance = 0;
37 digitalWrite(TRIG, HIGH);
38 delayMicroseconds(10);
39 digitalWrite(TRIG, LOW);
40 }
41
42 void wait_for_distance_measurement_to_complete()
43 {
44 uint8_t counter = 0;
45 while ((counter < 20) && !new_distance)
46 {
47 delay(1);
48 counter++;
49 }
50 }
51
52 uint16_t measure_distance()
53 {
54 start_distance_measurement();
55 wait_for_distance_measurement_to_complete();
56 return distance;
57 }
58
59 void loop() {
60 uint16_t d = measure_distance();
61 Serial.print("Distance: ");
62 Serial.println(d);
63 delay(100);
64 }