Single Supply Logic Level Converter Hookup Guide

Pages
Contributors: bboyho, LightningHawk
Favorited Favorite 0

Example Code

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE.

The single supply logic level converter can be used to shift data in either direction. In this example, we are going to shift levels from a 3.3V Arduino microcontroller and a 5V sensor.

Level Shifting Between a 3.3V Microcontroller w/ 5V Sensor

Copy the code below and paste it into the Arduino IDE. Since we are using an Arduino Pro Mini 3.3V/8MHz, make sure that you are selecting the correct board. Additionally, make sure to have the correct COM port selected when uploading. When ready, upload the example code!

language:c
/*
Single Supply Logic Level Converter Hookup Guide

This project will beep continuosly with a frequency proportional
to distance. As objects get closer, the beep gets faster.

Hardware:
 HC-SR04 Ultrasonic Sensor
 Arduino Pro Mini 3.3V/8MHz
 SparkFun Single Supply Logic Level Converter
 Piezo Buzzer

*/


#define TRIG_PIN 10
#define ECHO_PIN 11
#define Beep 3

void setup() {
  Serial.begin (9600);
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);
  pinMode(Beep, OUTPUT);
}

void loop() {
  unsigned long t1;
  unsigned long t2;
  unsigned long pulse_width;
  float cm1;


  // Hold the trigger pin high for at least 10 us
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait for pulse on echo pin
  while (digitalRead(ECHO_PIN) == 0 );

  // Measure how long the echo pin was held high (pulse width)
  // Note: the micros() counter will overflow after ~70 min
  t1 = micros();
  while (digitalRead(ECHO_PIN) == 1);
  t2 = micros();
  pulse_width = t2 - t1;

  // Calculate distance in centimeters.
  cm1 = pulse_width*0.034/2;
  if (cm1 >= 200 || cm1 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(cm1);
    Serial.println(" cm");

    tone(Beep,528);
    delay(100);
    noTone(Beep);
    delay(cm1);


  }
}

After uploading, place your hand in front of the ultrasonic sensor. When your hand is within a certain range, the buzzer will begin beeping! As you move your hand toward the sensor, the buzzer will beep faster. Moving your hand away from the sensor will slow down the beeping until you are out of range.

Circuit for shifting logic between a 3.3V microcontroller and 5V sensor