I am trying to convert the following code to output to pin 7 (PH4, OC4B) on an Arduino Mega. The code outputs to pin 6. This code is from a GitHub for the GRBL on the Mega "https://github.com/fra589/grbl-Mega-5X" out of the cpu_map.h It is clear that PH6 and PH7 are on the same PORTH but I just do not know what bits need changing to get GRBL to output on pin 7.Any help would be welcome.

#elif defined (SPINDLE_PWM_ON_D6)

    // Set Timer up to use TIMER4C which is attached to Digital Pin 6 - Ramps Servo 2
    #define SPINDLE_PWM_MAX_VALUE     255.0 // Translates to about 1.9 kHz PWM frequency at 1/8 prescaler
      #define SPINDLE_PWM_MIN_VALUE   1   // Must be greater than zero.
    #define SPINDLE_PWM_OFF_VALUE     0

    //Control Digital Pin 6 which is Servo 2 signal pin on Ramps 1.4 board
    #define SPINDLE_COMB_BIT          COM4A1

    // 1/8 Prescaler, 16-bit Fast PWM mode
    #define SPINDLE_TCCRA_INIT_MASK (1<<WGM41)
    #define SPINDLE_TCCRB_INIT_MASK ((1<<WGM42) | (1<<WGM43) | (1<<CS41))
    #define SPINDLE_OCRA_REGISTER   ICR4 // 8-bit Fast PWM mode requires top reset value stored here.
    #define SPINDLE_OCRA_TOP_VALUE  0xFF // PWM counter reset value. Should be the same as PWM_MAX_VALUE in hex.

    // Define spindle output pins.
    #define SPINDLE_PWM_DDR   DDRH
    #define SPINDLE_PWM_BIT   3 // MEGA2560 Digital Pin 6

1 Answer 1


You want to replace pin 6 (PH3, OC4A) with pin 7 (PH4, OC4B). There are three things you have to change. First, the output compare register, which is OCR4A for pin OC4A and OCR4B for pin OC4B. Thus:


Then, the configuration bit that enables the output:

-#define SPINDLE_COMB_BIT          COM4A1
+#define SPINDLE_COMB_BIT          COM4B1

Last, the bit to set in the data direction register, which is 3 for PH3 and 4 for PH4:

-#define SPINDLE_PWM_BIT   3 // MEGA2560 Digital Pin 6
+#define SPINDLE_PWM_BIT   4 // MEGA2560 Digital Pin 7

Note: as in diff -u format, the prefix - means “remove this”, the prefix + means “add this”.

  • Thanks for the help. I spent hours trying to figure out the datasheet.
    – Mr.Spriggs
    Commented Jan 10, 2022 at 6:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.