import time
import machine
import ssd1306
# Define the OLED screen dimensions
SCREEN_WIDTH = 128
SCREEN_HEIGHT = 64
# Define the I2C bus (simulating ESP32 GPIO 21 as SDA and GPIO 22 as SCL)
i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
oled = ssd1306.SSD1306_I2C(SCREEN_WIDTH, SCREEN_HEIGHT, i2c)
# Define the magnetic sensor input pin (simulating ESP32 GPIO 23)
magnetic_sensor_pin = machine.Pin(23, machine.Pin.IN)
# Constants for the number of magnetic pulses per revolution
PULSES_PER_REVOLUTION = 20
# Function to calculate the motor speed
def calculate_motor_speed(pulses, time_interval):
# Calculate the number of revolutions per second
revolutions_per_second = pulses / PULSES_PER_REVOLUTION / time_interval
# Calculate the motor speed in RPM (Revolutions Per Minute)
motor_speed_rpm = revolutions_per_second * 60
return motor_speed_rpm
# Function to display text on the OLED
def display_text(text):
oled.fill(0) # Clear the screen
oled.text(text, 0, 0) # Write the text at (0, 0)
oled.show() # Update the display
# Main loop to continuously measure and display the motor speed
def main():
prev_pulse_count = 0
time_interval = 1 # Time interval in seconds
while True:
# Measure the pulse count at the start of the interval
start_pulse_count = magnetic_sensor_pin.value()
# Wait for the measurement interval
time.sleep(time_interval)
# Measure the pulse count at the end of the interval
end_pulse_count = magnetic_sensor_pin.value()
# Calculate the number of pulses occurred during the interval
pulses = end_pulse_count - start_pulse_count
# Calculate the motor speed
motor_speed_rpm = calculate_motor_speed(pulses, time_interval)
# Display the motor speed on the OLED
display_text("Speed (RPM): {:.2f}".format(motor_speed_rpm))
if __name__ == "__main__":
main()