超音波センサー(HC-SR04) 割り込み コード, Ultrasonic sensor(HC-SR04) intterupt Source code

int Trig[5] = {100, 28, 36, 44, 52};
int Echo[5] = {100, 21, 20, 19, 18};

unsigned long Distance[5] = {0};
unsigned long Duration[5] = {0};

volatile unsigned long LastPulseTime1;
volatile unsigned long LastPulseTime2;
volatile unsigned long LastPulseTime3;
volatile unsigned long LastPulseTime4;

int iTemperature = 20;
int UltraVelocity = 330 + (0.6 * iTemperature);
int K = UltraVelocity * 0.0005;

void setup() {

Serial.begin(9600); // Starts the serial communication

for (int i = 1; i <= 4; i ++)
{
pinMode(Trig[i],OUTPUT);
}

for (int i = 1; i <= 4; i ++)
{
pinMode(Echo[i],INPUT);
}

attachInterrupt(2, EchoPin1_ISR, CHANGE);
attachInterrupt(3, EchoPin2_ISR, CHANGE);
attachInterrupt(4, EchoPin3_ISR, CHANGE);
attachInterrupt(5, EchoPin4_ISR, CHANGE);
}

void loop() {

for ( int i = 1; i <= 4; i ++)
{
  delay(20);
  digitalWrite(Trig[i], HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig[i], LOW);

}

int sensorValue0 = analogRead(A0);
int sensorValue1 = analogRead(A1);
int sensorValue2 = analogRead(A2);

for (int i = 1; i <= 4; i ++)
{
  Distance[i] = Duration[i] * 330 * 0.0005;
  Serial.print(Distance[i]);
  Serial.print(“. “);
}

  Serial.print(sensorValue0);
  Serial.print(“. “);
  Serial.print(sensorValue1);
  Serial.print(“. “);
  Serial.print(sensorValue2);
  Serial.println(” “);
}

void EchoPin1_ISR() {
    static unsigned long startTimeA;

    if (digitalRead(21))
        startTimeA = micros();
    else
        Duration[1] = micros() – startTimeA;
}

void EchoPin2_ISR() {
    static unsigned long startTimeB;

    if (digitalRead(20))
        startTimeB = micros();
    else
        Duration[2] = micros() – startTimeB;
}

void EchoPin3_ISR() {
    static unsigned long startTimeC;

    if (digitalRead(19))
        startTimeC = micros();
    else
        Duration[3] = micros() – startTimeC;
}

void EchoPin4_ISR() {
    static unsigned long startTimeD;

    if (digitalRead(18))
        startTimeD = micros();
    else
        Duration[4] = micros() – startTimeD;
}

Published by

TEO

-Language KOR, JPN, ENG . -Major Mechanics, C++ . -Camera A6000, SM-950N

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s