Generating several frequency range of PWM signal with varying duty cycle by taking values through Pyserial

Hi I would like to generate several freq of PWM signals with varying Duty cycles. The Frequency/Duty values are given by Python code (transmitting through serially UART-Pyserial.

I am sharing the code of Python here. I would like to request you to build an Arduino code that can accept values(read values) from Python serially and then generate PWM freq and duty cycle. Please suggest the arduino code.

Python code:

def arduinosignal_default_setting(env):
    duty = [x1,x2,x3,x3]  # 4 elements (x1,x2,x3,x4 are integer values for  different Duty)
    frequency = [y1, y2, y3, y4] # 4 elements (y1,y2,y3,y4 are integer values for  different Frequencies)

    f_index = 0
    f_length = len(frequency)
    d_length = len(duty)

    # First while loop to iterate over frequency array
    while f_index < f_length:
        # Get current frequency
        f_value = frequency[f_index]

        # Second while loop to iterate over duty array
        d_index = 0
        while d_index < d_length:
            # Keep environment running and check measurements
            env.multimeter_default_setting()

            if env.mult_measure > 20:
                # Skip this d_index value and continue with the next one
                print(f"Skipping duty cycle {d_index} because measurement is {env.mult_measure} (greater than 20)")
                d_index += 1
                continue  # Skip to the next iteration of the inner while loop

            # Get current duty
            d_value = duty[d_index]

            # Simulate sending data to Arduino through serial
            data_to_send = f"Frequency: {f_value}, Duty: {d_value}\n"
            SerialObj = serial.Serial('COM6')  # Ensure the correct port
            SerialObj.baudrate = 9600
            SerialObj.bytesize = 8
            SerialObj.parity = 'O'
            SerialObj.stopbits = 1
            SerialObj.timeout = None
            TransmitString = SerialObj.write(data_to_send.encode())
            print(f"Sent -> {data_to_send.strip()}")
            ReceivedString = SerialObj.readline().decode()
            print(f"Received -> {ReceivedString.strip()}")

            d_index += 1  # Increment the duty index
            time.sleep(0.1)  # Delay between operations

        # Increment the frequency index after processing all duty cycles
        f_index += 1

    SerialObj.close()

The Arduino code would depend on which Arduino you have.

Furthermore, there are severe limitations on the possible frequencies and duty cycles, also depending on which Arduino you have, so you will need to do a bit more research on the topic.

If you would like someone to write code for you, post on the Jobs and Paid Collaboration forum section.

Arduino UNO i have it..

Could you please tell the range of freq/duty i can generate through Arduino UNO?
any formula for setting the Freq/duty range in Arduino UNO?

It depends on which of the three timers you use (all different).

The timers are fully described in the ATmega328P data sheet.

Example code can be found in this excellent tutorial.

In Arduino, the frequency and duty cycle of PWM (Pulse Width Modulation) signals can be adjusted using various timers and settings, depending on the pins you are working with. Below, I will outline the general concepts and formulas for setting the frequency and duty cycle on an Arduino UNO.

PWM Frequency and Duty Cycle on Arduino UNO

The Arduino UNO uses Timer0, Timer1, and Timer2 to generate PWM signals on different pins. Each timer has different default settings and capabilities.

1. Frequency Calculation:

The frequency of the PWM signal depends on the clock speed of the microcontroller and the settings of the timer's prescaler and TOP value. The general formula for calculating the PWM frequency is:

Frequency=Clock SpeedPrescaler×(TOP+1)\text{Frequency} = \frac{\text{Clock Speed}}{\text{Prescaler} \times (\text{TOP} + 1)}Frequency=Prescaler×(TOP+1)Clock Speed​

  • Clock Speed: The default clock speed for the Arduino UNO is 16 MHz (16,000,000 Hz).
  • Prescaler: This value determines how much the clock speed is divided. Common prescaler values are 1, 8, 64, 256, and 1024.
  • TOP: The maximum value the timer counts to before resetting. In the default fast PWM mode on Arduino, TOP is typically 255.

2. Duty Cycle Calculation:

The duty cycle is the proportion of the PWM period that the signal remains HIGH. It is usually expressed as a percentage.

Duty Cycle (%)=(PWM ValueTOP)×100\text{Duty Cycle (%)} = \left(\frac{\text{PWM Value}}{\text{TOP}}\right) \times 100Duty Cycle (%)=(TOPPWM Value​)×100

  • PWM Value: The value set using analogWrite(). For an 8-bit timer, this can range from 0 to 255.
  • TOP: For an 8-bit timer, this is 255 by default.

Example: Setting PWM Frequency and Duty Cycle on Arduino UNO

Here's an example of how to adjust the frequency and duty cycle using Timer1, which controls pins 9 and 10.

void setup() {
  // Set pin 9 as output
  pinMode(9, OUTPUT);

  // Set Timer1 to Fast PWM mode, 8-bit
  TCCR1A = _BV(WGM10) | _BV(COM1A1);
  TCCR1B = _BV(WGM12) | _BV(CS11); // Set prescaler to 8

  // Set Duty Cycle: 50%
  OCR1A = 128; // 50% of 255
}

void loop() {
  // Nothing needed here; PWM is handled by Timer1
}

Explanation of the Example:

  • TCCR1A and TCCR1B: These registers configure Timer1's mode and prescaler.
  • _BV(WGM10) and _BV(WGM12): Set Timer1 to Fast PWM, 8-bit mode.
  • _BV(CS11): Sets the prescaler to 8.
  • OCR1A = 128;: Sets the duty cycle to 50% (128/255).

Key Points:

  • Changing the prescaler will affect the frequency.
  • Adjusting OCR1A will change the duty cycle.

Using these formulas and adjusting the timer registers will allow you to set the PWM frequency and duty cycle on the Arduino UNO according to your requirements.

Take a look at:

https://www.pjrc.com/teensy/td_libs_TimerOne.html

It does a pretty good job of setting a wide range of frequencies and duty cycles on an Uno's pins 9 & 10.