電位器及示例
本文將透過兩個不同的示例演示如何使用ESP32使用電位器。第一個示例使用微調電位器將電壓變化範圍控制在0到3V之間。第二個示例在Wokwi模擬器上使用滑桿電位器來控制伺服電機。Wokwi模擬器是一款軟體,可用於執行程式碼並虛擬測試結果,而無需購買元件。實際元件圖通常與Wokwi中使用的元件圖不同,因此圖1給出了實際滑桿電位器的外觀。
示例1:使用微調電位器將電壓更改為0到3V/5V之間。
電路設計步驟和編碼
步驟1 − 首先將ESP32微控制器放置在麵包板上。
步驟2 − 現在將電位器插入麵包板。
步驟3 − 將電位器的正極連線到ESP32的3V3/Vin引腳。將電位器的負極連線到ESP32的GND引腳。電位器的側引腳是可以互換的。
步驟4 − 使用Arduino編寫C程式來控制電壓,並將電位器的中間引腳連線到ESP32的D13引腳。
步驟5 − 使用USB資料線將ESP32連線到計算機。
步驟6 − 編譯並將程式碼傳輸到ESP32,並在序列埠監視器上檢查結果。
示例2:使用滑桿電位器控制伺服電機。
電路設計步驟和編碼
步驟1 − 在Wokwi模擬器上啟動一個新的ESP32專案。
步驟2 − 將ESP32放置在虛擬電路區域。
步驟3 − 將電位器連線到ESP32。將其GND連線到ESP32的GND,將其Vin連線到ESP32的3V3,將其第三個引腳連線到ESP32的D26。
步驟4 − 將伺服電機連線到ESP32。將其GND連線到ESP32的GND,將其Vin連線到ESP32的3V3,將其第三個引腳連線到ESP32的D27。
步驟5 − 使用Wokwi編寫C程式,並從庫選項卡中包含庫<ESP32Servo.h>。
步驟6 − 使用Wokwi上的播放按鈕編譯程式。
步驟7 − 透過更改滑塊設定來檢查伺服電機角的運動結果。
電位器的型別
電位器是一種可以控制和調節電壓的裝置。它有多種形式,例如滑桿式、微調式和旋鈕式。
示例1:使用微調電位器將電壓更改為0到3V/5V之間
微調電位器通常用於一次性固定電位器的控制設定,因為旋轉螺絲很困難,但是,在這個程式設計示例中,旋轉螺絲的任務用於在檢視結果的同時更改電壓。電路是使用Arduino軟體製作的,程式也是使用Arduino軟體編寫的。
圖2:電位器電路圖。
程式碼
// function for mapping input range to output range
float mapTwoRanges(float reading_x, float minInput, float maxInput, float minOutput, float maxOutput) {
return (reading_x - minInput) * (maxOutput - minOutput) / (maxInput - minInput) + minOutput;
}
void setup() {
//baud rate setting
Serial.begin(9600);
}
void loop() {
// reading the analog value using ESP32 pin D4 or D13
//int analog_val = analogRead(4);
int analog_val = analogRead(13);
// get the voltage between 0 and 3 V by rotating the screw of the potentiometer
float result_volts = mapTwoRanges(analog_val, 0, 4095, 0, 3);
// Check these readings below in the Serial Monitor
Serial.print("Analog: ");
Serial.print(analog_val);
Serial.print(", Voltage: ");
Serial.println(result_volts);
delay(1000);
}
檢視結果 - 示例1
一旦程式碼編譯並傳輸/上傳到ESP32,就可以看到結果。
示例2:使用滑桿電位器控制伺服電機
滑桿電位器通常用於透過滑動來固定或調整電位器的設定。在這個程式設計示例中,滑桿用於在檢視結果的同時更改伺服電機角的位置。電路使用Wokwi模擬器虛擬製作,程式使用C語言編寫。
程式碼
//The required library
#include <ESP32Servo.h>
const byte servoObjMotorPin = 27;
const byte potentiometerReadingentiometerPin = 26;
Servo servoObj;
void setup(){
// baud rate specification
Serial.begin(115200);
// attach the 27 ESP32 pin
servoObj.attach(servoObjMotorPin);
servoObj.write(0);
delay(1000);
}
void loop(){
//Getting the analog reading of the potentiometer
int potentiometerReading = analogRead(potentiometerReadingentiometerPin);
//getting the resulting angle by mapping the potentiometer analog reading
int angleResult = map(potentiometerReading , 0 , 4095 , 0 , 180);
//Changing the angle for the horn of the servomotor
servoObj.write(angleResult);
delay(10);
}
檢視結果 - 示例2
圖3:顯示Wokwi線上模擬器上用於電位器和伺服電機控制的虛擬電路。
本文透過兩個不同的示例介紹了使用ESP32使用電位器的方法。首先,介紹了將微調電位器與ESP32模擬引腳連線的方法。在第二個示例中,使用Wokwi線上模擬器製作了一個帶有電位器和伺服電機的虛擬電路。首先,使用電位器控制電壓,並將其對映到0到180度之間的角度,然後將其用於控制伺服電機的角位置。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP