7-Segment-Display stuttering when showing sensor output due to delays

Hello,

I built a simple distance sensor box for a bigger project. It measures distance with an ultrasonic sensor and sends it to another Arduino via RF. All of that works fine, however I thought it would be neat to have the measured distance output to a 7-segment-display so I connected that too. Due to the nature of SevSeg.h's refreshDisplay(), I can't use any delays in the main loop, however my sensor does need delays to properly measure the distance. Is there a way to get the seven segment display to display the measured distance properly? Right now it flickers once I activate all the delays and works fine when they're off, however the sensor stops working.

Here is my code: http://pastebin.com/Y6fB43C6

Thank you in forward!

Please post your code here - don't forget the code tags

Sure thing, here it is:

#include <VirtualWire.h>
#include <SevSeg.h>

#define trigPin A0
#define echoPin A1

//RF-Transmitter
char Sensor1CharMsg[4];
long distance;

static unsigned long timer = millis();

void setup() {
  Serial.begin(9600);      // open the serial port at 9600 bps:

  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(80);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  vw_set_ptt_inverted(false);
  vw_set_tx_pin(A2);
  vw_setup(4000); // speed of data transfer Kbps
}

void loop() {

  if (millis() >= timer) {
    if (distance >= 200 || distance <= 0) {
      sevseg.setNumber(0);
    } else {
      sevseg.setNumber(distance);
    }
	sevseg.refreshDisplay();
    timer += 250;
  } else {
    long duration;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration / 2) / 29.1;

    itoa(distance, Sensor1CharMsg, 10);
    vw_send((uint8_t *)Sensor1CharMsg, strlen(Sensor1CharMsg));
    vw_wait_tx(); // Wait until the whole message is gone
  }
}

It's hard to believe that 12 microseconds of delays (two microseconds of which are unnecessary) is causing your problem - more likely "pulseIn".
Try the NewPing library.

Thanks for the suggestion, NewPing looks much more elegant than my solution. I've implemented it but the refresh rate is still too low for refreshDisplay(). I commented out line for line and it seems that just the vw_send command is enough to have it flicker too much to make out any numbers.