#define led1 19
#define led2 18
#define sw1 25
int old1, new1 ;
unsigned long t1;
void setup() {
pinMode(sw1, INPUT_PULLUP);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(115200);
digitalWrite(led1, 0);
digitalWrite(led2, 0);
old1 = digitalRead(sw1); // เก็บค่าเก่าของ sw1 ก่อนเข้า loop
}
void pwm_bit_bang_millis_dac(int freq, int pin, int duty_cycle)
{
// Calculate the period and high time of the PWM signal in milliseconds.
int period = 1000 / freq;
int high_time = period * duty_cycle / 100;
int low_time = period - high_time;
Serial.printf("Frequency: %d\n",high_time);
Serial.printf("Duty %d\n",low_time);
// Start a timer to track the elapsed time in milliseconds.
unsigned long start_time = millis();
// If the high time has elapsed, set the pin low.
if (millis() - start_time >= high_time)
{
// digitalWrite(pin, LOW);
digitalWrite(led1, 0); // ส่ง 1 ออกที่ led1 (led1 สว่าง)
}
// If the low time has elapsed, set the pin high.
if (millis() - start_time >= period)
{
// digitalWrite(pin, HIGH);
digitalWrite(led1, 1); // ส่ง 1 ออกที่ led1 (led1 สว่าง)
start_time = millis();
}
}
void togglePinNonBlocking(int pin, unsigned long frequency, unsigned int dutyCycle) {
static unsigned long lastToggleTime = 0; // Keeps track of the last toggle time
static bool pinState = LOW; // Current state of the pin
// Calculate high and low durations based on frequency and duty cycle
unsigned long period = 1000000UL / frequency; // Period in microseconds
unsigned long highTime = period * dutyCycle / 100; // High duration
unsigned long lowTime = period - highTime; // Low duration
unsigned long currentTime = micros(); // Current time in microseconds
// Check if it's time to toggle the pin
if ((pinState == HIGH && currentTime - lastToggleTime >= highTime) ||
(pinState == LOW && currentTime - lastToggleTime >= lowTime)) {
pinState = !pinState; // Toggle the state
digitalWrite(pin, pinState); // Update the pin state
lastToggleTime = currentTime; // Update the last toggle time
}
}
void loop() {
togglePinNonBlocking(led2, 2, 10); // Replace YOUR_PIN, YOUR_FREQUENCY, and YOUR_DUTY_CYCLE with your values
}