1

Тема: Функция micros()

Добрый день! Недавно стал обладателем Freeduino nano v5. Написал код, в котором при замыкании контакта D2 на землю возвращает число микросекунд.

int in_1 = 2;
unsigned long time;

void setup()
{
  pinMode(in_1, INPUT);
  Serial.begin(115200);
  digitalWrite(2, HIGH);
}

void loop()
{
  time = micros();
  if(digitalRead(in_1) == LOW)
  {
    Serial.println(time);
  }
}

При просмотре через монитор порта, у меня отображает следующее...

17029060
17030380
17031692
17033012
17034332
17035644
17036960
17038276
17039596
17040908

т.е. период между числами варьируется между 1312 и 1320 микросекунд. А возможно ли сделать период в 500 микросекунд?

Re: Функция micros()

Я так понимаю все это время большей частью тратится внутри Serial.println.
Смотря какая задача, может можно в какой-то массив сначала сохранять данные, а уже потом
их посылать.
Либо пробовать посылать самостоятельно - на низком уровне, исключив некоторый имеющийся
во всех "оберточных" функциях overhead.

3

Re: Функция micros()

в общем, по пути сохранения в буфер я и пошел:

#define mTimeBufferSize 64 // MUST only be 2^x value, such as 2, 4, 8, 16, 32, 64, 128

volatile unsigned long mTimesBuffer[mTimeBufferSize]; // Buffer to store values before they are sent over serial
volatile unsigned long mTimesBufferStorePtr=0; // Pointer into the buffer showing where we are currently storing values to.  Note this pointer does not loop over, it counts up continually
volatile unsigned long mTimesBufferSendPtr=0; // Pointer into the buffer showing where we are currently sending values over serial from.  Note this pointer does not loop over, it counts up continually

unsigned long lastSent = 0; // Used to hold the previous micros() value sent to the PC so the difference from current micros can be calculated

void setup()
{
  Serial.begin(115200); // Enable serial port communication at 115200 baud
  pinMode(2, INPUT); // Set digital pin 2 to an input pin
  digitalWrite(2, HIGH);
  attachInterrupt(0, onChangeX, FALLING); // Setup interrupt 0 (which is on digital pin 2), triggered on a rising edge input, calling the onChangeX function
}


void loop()
{
  if(mTimesBufferSendPtr < mTimesBufferStorePtr)
  {
    // The send pointer is behind the store pointer so there must have been a value written that we can send

    //Serial.print(mTimesBufferStorePtr - mTimesBufferSendPtr); // Send how far the send pointer is behind the store pointer, if this gets higher then mTimeBufferSize a buffer overflow has occured and the data will not be accurate
    //Serial.print(",");
    //Serial.print(mTimesBuffer[mTimesBufferSendPtr & (unsigned long)(mTimeBufferSize-1)]); // Send the next micros value in the buffer, buffer is incremented later.
    //Serial.print(",");
    Serial.println(mTimesBuffer[mTimesBufferSendPtr & (unsigned long)(mTimeBufferSize-1)] - lastSent); // Subtract the previous micros from this micros to get the pulse time and send across serial port

    lastSent = mTimesBuffer[mTimesBufferSendPtr++ & (unsigned long)(mTimeBufferSize-1)];
  }
}


// Function called on every interrupt
void onChangeX()
{
  mTimesBuffer[mTimesBufferStorePtr & (unsigned long)(mTimeBufferSize-1)] = micros(); // Put the current micros() value into the next space in the buffer
  mTimesBufferStorePtr++; // Increment the buffer store pointer to the next location
}

Данное решение нашел на форуме arduino.cc.