Creating a Palm-Sized Electronic Piano with a Stepper Motor

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 1 Stepper Motor Piano

#Project Origin#

Stepper motors are commonly encountered in various small to medium processing equipment, such as laser cutters or 3D printers. When using the laser cutter, I discovered that the stepper motor emits sounds similar to musical instruments while cutting circular patterns. Why does this phenomenon occur?

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 2 Stepper Motor of the Laser Cutter

We all know that sound generation is related to frequency; the higher the frequency, the sharper the sound. Speakers emit different sounds because they respond to different frequencies.
If we want to control the stepper motor of the laser cutter, we need to change the frequency. Can changing the frequency allow the stepper motor to produce different sounds?
If that’s the case, theoretically, a complete piece of music can also be played using a stepper motor. In this article, we will explore this issue by creating an electronic piano with a stepper motor. Since it is made from a stepper motor, I named it Stepper Music.

Let’s first watch a video to see how the stepper motor electronic piano is designed and made.

#Video Display#

#Design and Production#

The first step in designing the project is to determine the design scheme. This stepper motor electronic piano needs to use the stepper motor to produce sound and also requires keys similar to a piano, with a pressing and rebounding effect. Based on the analysis above, we can break down the stepper motor piano into three parts: the stepper motor, the appearance structure, and the electronic control part.
Electronic Control Part

Unlike a real piano, this project will use a stepper motor to produce sound. To control the stepper motor, we need a stepper motor driver. The common stepper motor driver is the A4988 driver, which is often used in early 3D printers. Due to the high noise of the A4988 driver, it has gradually been replaced by better solutions. However, our main purpose this time is to make the stepper motor produce sound, so the noise is actually beneficial for us. After determining the driver model, we then choose the controller, which is the commonly used Arduino microcontroller. To reduce size, we select the Nano series version. To simplify wiring and make it more convenient to use, we integrate the controller, stepper motor driver, and keys into one circuit board. The simulation effect diagram of the circuit board is as follows:

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 3Stepper Motor Piano Circuit Board

The schematic of this circuit board is as follows, mainly containing a power supply circuit, controller, driver circuit, etc.
The tactile switch in the circuit is designed with a pull-up resistor to stabilize its signal.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 4 Schematic Diagram

Once the schematic is completed, we can generate the PCB file from it. Next, we will proceed with the wiring according to the schematic. To ensure the current when the stepper motor operates, the wiring width parameters need to be set larger.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 5 PCB Wiring

After completing the PCB design, switch to 3D mode to view the 3D effect.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 6 PCB 3D View

Finally, after checking that there are no issues, we can send it for prototyping.

While the PCB is being prototyped, we can prepare the soldering components needed, the components, materials, and BOM list are as follows:

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 7 Parts List

After completing the prototype, the actual PCB is shown in the image below.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 8 Actual PCB

Once the components are ready, we will solder them onto the circuit board one by one.

After soldering is complete, the finished product is shown in the image below, where the A4988 driver and Arduino Nano controller need to be purchased separately.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 9 Completed PCB Soldering

The electronic control part is completed, and next, we will design the appearance structure for the stepper motor electronic piano.

Appearance Structure

The appearance structure of the stepper motor electronic piano is designed based on the appearance of a real piano, using laser cutting technology for processing. Figure 10 shows the effect image.
The characteristic of the stepper motor electronic piano we are making this time is that its size is only palm-sized, while a real piano may have as many as 80 keys. We need to ensure that it has a rich tone while maintaining its size. Here, we use a potentiometer to adjust the tone. When the potentiometer is adjusted to different levels, pressing the keys will produce different tones, thus simulating multiple tones using 7 keys.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 10 Simulation Image of Stepper Motor Piano

The key part of the appearance structure of the stepper motor electronic piano is the keys, which need to meet the requirements of producing sound and having a pressing and rebounding feeling. Here, we use micro switches (tactile switches) as keys and incorporate a flexible design structure to allow the keys to rebound.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 11Key Design

Stepper Motor

The stepper motor we are using this time is the most common 42 two-phase four-wire stepper motor (42 refers to the length and width dimensions in mm, two-phase means two sets of coils).
Once the plan is determined, we can start designing and making it.
First, we will design the appearance structure drawings.

Drawing Design

To verify the assembly details, we will first use Fusion360 CAD software to design a 3D model, and then convert the model into a 2D drawing suitable for laser cutting. The material chosen is 3mm linden wood.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 12 3D Simulation Effect Image

After the 3D model is completed, load the drawing into the LaserMaker laser modeling software for processing.
For the LaserMaker modeling software, you can download it from the official website:
https://www.lasermaker.com.cn/

In the software, set the text and patterns for shallow engraving processing. The stepper motor will rotate while working, so we design a turntable engraved with two fish to enhance the rotation effect. The processed design diagram is as follows:

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 13 Stepper Motor “Piano” Design Drawing

Processing Parts

After completing the drawing design, we will use a laser cutter to process it. The parts after cutting are shown in Figure 14.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 14 Actual Parts After Laser Cutting

Equipment List

In addition to the appearance structure mentioned above, the stepper motor electronic piano also requires the following parts:
  1. Arduino Nano Controller and Expansion Board*1
  2. A4988Driver*2
  3. 42Stepper Motor*1
  4. Potentiometer*1
  5. 3mm Linden Wood*1(40cm * 60cm)
  6. Dupont Wires (several)
  7. Hardware Parts (several)

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 15 Parts List of Stepper Motor Piano

With the equipment ready, let’s see how to connect the electronic control part.

Wiring Circuit

This time, we will divide the circuit design into PCB design and wiring.
The PCB circuit board for the stepper motor “piano” has been designed earlier, and now let’s see how the potentiometer and stepper motor are connected to the control board.
The wiring diagram is as follows. From the wiring diagram, we can see that the control board reserves two connection ports for the stepper motor. We can connect one or two stepper motors. The potentiometer can be connected to the A0 analog pin, while the onboard 7 tactile switches correspond to digital pins D6 to D12.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 16 Wiring Diagram of Stepper Motor Electronic Piano

Once everything is ready, we can start the exciting assembly stage.

#Assembly#

The assembly of the stepper motor electronic piano is not very complicated; it can be completed in just a few steps.

Step 1: Install Electronic Components
First, we install the circuit board part, with the tactile switch part facing up and combined with the wooden board, using 3mm diameter screws, nuts, and nylon pillars to secure it, as shown in Figures 17 and 18.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 17 Circuit Board Installation

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 18 Circuit Board Installation Completed

Next, we install the potentiometer. The required parts are shown in Figure 19.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 19 Installing Potentiometer

First, install the potentiometer in the corresponding square hole, then put on the knob cap. The potentiometer installation is completed as shown in Figure 20.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 20 Potentiometer Installation Completed

Next, we will install the circular turntable engraved with small fish together with the stepper motor, as shown in Figure 21.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 21 Small Fish Turntable with Stepper Motor

Step 2: Assemble the Framework Structure

After completing the installation of electronic components, the next step is to assemble the framework. First, we install the following parts of the framework.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 22 Parts Needed for Framework Assembly

The partial framework assembly is completed as shown in Figure 23.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 23 Framework Assembly Completed

Next, we will install the key wooden board and the vertical plate in the middle based on the previous assembly, as shown in Figure 24.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 24Installing Keys and Vertical Plate

The key and vertical plate assembly is completed as shown in Figure 25.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 25 Key and Vertical Plate Assembly Completed

Next, we will install the top plate to secure the potentiometer and stepper motor, as shown in Figure 26.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 26 Installing Top Plate

The top plate installation is completed as shown in Figure 27. Please pay attention to the direction of the potentiometer’s knob indicator during installation.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 27 Top Plate Installation Completed

Next, we need to install the left wooden plate onto the framework.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 28 Installing Left Wooden Plate

The left wooden plate is installed as shown in Figure 29.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 29 Left Wooden Plate Installation Completed

Finally, we will install the back plate onto the framework.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 28 Installing Back Plate

Using two pins to secure it, the installation is completed as shown in Figure 29.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 29Back Plate Installation Completed

The framework assembly is completed, and the effect display is as follows.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 30Framework Assembly Completed

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 31Framework Assembly Completed

Step 3: Place the Stepper Motor

In the third step, place the stepper motor in the piano as shown in the following images. Note that the circuit connection should be completed before placing it in the piano.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 32 Placing Stepper Motor

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 33 Stepper Motor “Piano” Front Display

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 34 Stepper Motor “Piano” Back Display

If you also like the compact stepper motor electronic piano but don’t want to make it yourself, you can click the mini-program below to purchase it.

The assembly of the project is completed, and next, we will write a program to give the project its soul.

#Program Design#

To ensure the response speed of the stepper motor, the program for this stepper motor electronic piano needs to be programmed directly on the microcontroller’s registers, without using functions like digitalWrite provided in the Arduino library.
Therefore, the program design for this project uses Arduino IDE as the programming environment. You can download the programming environment from the official website arduino.cc.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 35

You can also download the latest Mixly graphical programming software from the mixly.org website, which integrates the Arduino IDE programming environment, saving you a lot of configuration hassle.

Programming Ideas

The focus of the program design for the stepper motor electronic piano (Stepper Music) is how to make the stepper motor quickly respond to different frequencies and produce different sounds.
Below is the programming idea, and we will complete it step by step based on this idea.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 36 Program Design Mind Map

Driving Method of Stepper Motor

Before learning the driving method of the stepper motor, let’s supplement some background knowledge about the stepper motor.

Background Knowledge of Stepper Motor

Creating a Palm-Sized Electronic Piano with a Stepper Motor

The stepper motor we are using is a 42 stepper motor, which is formally known as a NEMA bipolar two-phase four-wire stepper motor. NEMA stands for National Electrical Manufacturers Association, which established a series of standards for motor sizes in 1984. Among these standards is the “NEMA17” stepper motor, where 17 refers to the motor’s frame size of 1.7 inches (approximately 42mm), so the NEMA17 stepper motor is often referred to as a 42 stepper motor. This standard is still in use today. The term two-phase indicates that it consists of two sets of coils. The NEMA17 stepper motor is widely used in the field of 3D printing.
Additionally, larger NEMA23 stepper motors, commonly referred to as 57 stepper motors, are more frequently used in laser cutting machines.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 37 42Stepper Motor

Understanding the size of the stepper motor, we also need to know its basic parameters.

1. Step Angle of Stepper Motor

The step angle of the 42 stepper motor we are using is 1.8°. In simple terms, the step angle is the angle the motor rotates for each step pulse signal sent by the controller. This value is given at the factory, and it can also be adjusted through the driver during operation. The reason the step angle is 1.8° is related to the number of teeth in the motor. The more subdivided the teeth, the smaller the step angle.

2. Phase of Stepper Motor

The phase of the stepper motor refers to the number of coils inside the motor. Common types include two-phase, three-phase, four-phase, and five-phase. A common small stepper motor is a four-phase five-wire stepper motor, suitable for applications that do not require high torque.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 38

This time we are using a two-phase four-wire stepper motor. As shown in the figure, the two-phase four-wire stepper motor has 8 coils, with every four coils constituting a phase.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 39 42Stepper Motor Coils

Having a stepper motor alone is not enough; we also need a stepper motor driver to make it work.

A4988 Driver
From previous discussions, we know that we chose the A4988 stepper motor driver for this project. It is a very popular and cost-effective driver board, especially common in 3D printing and small CNC machine tools.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 40 A4988Driver

To use the driver to drive the stepper motor, we need to understand the function of each pin of the A4988 driver. The pin function diagram of the A4988 is as follows:

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 41 A4988Driver

From the table below, we can see the function of each pin of the driver. The stepper motor needs to connect to pins 1A, 1B, 2A, and 2B, and we can use the default full-step mode for the step angle. In the program, we only need to set the STEP and DIR pins to control the stepper motor.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 42 Driver Pin Functions

After understanding the function of the stepper motor pins, it is not difficult to understand that the stepper motor driver acts as a bridge between the microcontroller (Arduino Nano) and the stepper motor. The microcontroller sends pulse signals to the driver, and when the driver receives the signals, it interprets them as the order of energizing the stepper motor coils, thus driving the motor to rotate.
Now that we understand the pin functions of the A4988 driver, we only need to install the A4988 driver onto the designed circuit board, taking care of the orientation during installation.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 43 Circuit Board without Installed Stepper Motor Driver

The red-green-blue-black wires of the stepper motor connect to the M1 or M2 terminal of the circuit board.
The STEP and DIR pins of the M1 terminal correspond to the digital pins D3 and D2 of the Arduino Nano controller, while the STEP and DIR pins of the M2 terminal correspond to the digital pins D5 and D4 of the Arduino Nano controller.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 44 Stepper Motor Driver Installed in Circuit Board

Having understood the working principles of the stepper motor and A4988 driver, we can start writing the program.
In addition to driving the stepper motor, we will also use the potentiometer and tactile switches. Let’s first understand how to use the tactile switches.

Using the Switches

The tactile switches used in this stepper motor electronic piano are typical digital signals. We only need to know the state values when the tactile switches are pressed and released to play music.
We input the following program in the programming environment.
void setup() {    Serial.begin(9600);}void loop() {  Serial.println(digitalRead(6));//Print the value of digital pin 6  delay(1000);}

After downloading the program, open the serial monitor to see the testing effect below.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 45 Serial Print Test Result

When the tactile switch is pressed, the output state value is 1, and the output value after releasing is 0.
Knowing the state value of one tactile switch, the remaining 6 tactile switches operate on the same principle, so we can play music by detecting the states of the 7 tactile switches.

Using the Potentiometer

Having mastered the playing method of the keys, let’s learn how to adjust the tone using the potentiometer. The potentiometer used in this stepper motor electronic piano is a typical analog signal. We need to divide the analog signal into several intervals to adjust different tones.
We input the following program in the programming environment to test the value range of the potentiometer.
void setup() {    Serial.begin(9600);}void loop() {  Serial.println(analogRead(A0));//Print the value of analog pin A0  delay(1000);}

After downloading the program, open the serial monitor to see the testing effect below.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 46 Serial Print Potentiometer Values

From the results in the above figure, we can see that the value range of the potentiometer knob is 0-1023. If we need 5 different tones, we need to divide the value range of 0-1023 into five parts. Under different interval levels, pressing the keys can produce different sounds. Regarding various tones of the piano (the actual term is pitch) corresponding to frequencies, we can refer to the figure below. This time we take O3-O7 as five pitches.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 47 Piano Pitch and Frequency Comparison Table

Once the pitches are determined, we need to correlate the potentiometer values with the five pitches. There are two methods to achieve this: the first method is to reduce the value range by 250 times, as shown in the code below.
void setup() {    Serial.begin(9600);}void loop() {  Serial.println(analogRead(A0)/250);//Print the value of analog pin A0 after reducing the range  delay(1000);}

The second method is to use the map function to map the potentiometer’s value range to 0-4, as shown in the code below.

int num;void setup() {    Serial.begin(9600);}void loop() {   num = map(analogRead(A0),0,1023,0,4);  Serial.println(num);//Print the value of analog pin A0 after mapping the range  delay(1000);}

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 48 Results After Mapping Potentiometer Values

We can also store the frequencies corresponding to the pitches O3 to O7 in an array for easy indexing. This way, we can switch between different tones through potentiometer adjustments, and we will also use a structure with the array, as shown in the code below.
typedef struct {    float xfr;}MUSIC;//Pitch and frequency#define PITCHES_LENGTH 35const MUSIC pitches[PITCHES_LENGTH] PROGMEM = {   130.813,//O3  146.832,  164.814,  174.614,  195.998,  220.000,  246.942,   261.626,//O4  293.665,  329.629,  349.228,  391.995,  440.000,  493.883,   523.251,//O5  587.330,  659.255,  698.456,  783.991,  880.000,  987.767,   1046.502,//O6  1174.659,  1318.520,  1396.913,  1567.982,  1760.000,  1975.533,  2093.004,//O7  2349.318,  2637.020,  2793.826,  3135.437,  3520.000,  3951.066,};

Once we correlate the potentiometer values with the pitches, the next step is to get the stepper motor to produce sound.

Producing Sound with the Stepper Motor

How can we use the stepper motor to produce sound? We know that sound is generated by the vibration of objects, and the higher the vibration frequency, the higher the corresponding pitch. The stepper motor can rotate because it responds to different frequencies.
The process of the stepper motor producing sound can be understood as follows: the microcontroller sends a pulse to the stepper motor driver, and the stepper motor rotates a certain angle, which is the step angle. If the microcontroller keeps sending pulses, the stepper motor will keep rotating. The higher the pulse frequency, the faster the motor rotates. How does the stepper motor produce the notes of Do, Re, Mi, Fa, Sol, La, Si? Since the sound produced by the stepper motor is related to frequency, let’s first look at the correspondence between C major notes and frequencies.

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 49 Correspondence Between C Major Notes and Frequencies

From the frequency table corresponding to the C major notes, we can see that the frequency of Do is 523Hz, which means that we need to send 523 pulses to the stepper motor driver per second. The time for each pulse is 1/523 seconds. Sending a high level and a low level forms one pulse. The sum of the durations of the high and low levels is exactly 1/523 seconds. If the duration of the high and low levels changes, the frequency will change. Therefore, we only need to modify the duration of the high and low levels to switch between different pulse frequencies.
Now, how can we accurately calculate the time corresponding to each frequency? Here, we need to use the microcontroller’s timer.
The programming idea is to use the microcontroller’s timer to interrupt at a certain frequency (which is the time interval). For example, we can use the timer to interrupt at a speed of 60000Hz.If we want to generate a 30Hz pulse square wave on pin 2, we can use a variable to count. The variable will count to 60000/30=2000, and then generate a 30Hz square wave.If we want to send pulse signals to more stepper motors, we can use more variables to count.
Some friends may wonder why the frequency is set to 60000Hz. When we generate the frequency of the stepper motor using the timer, if the frequency we want to generate is very close to the timer interrupt frequency, it will produce a large error. The maximum frequency that the stepper motor can produce will not exceed 4000Hz, and through testing, it has been found that setting the timer frequency to 60000Hz produces sounds that are close to the auditory effect.
After understanding the basic principles of how the timer generates pulse frequencies, let’s learn how to operate the timer on the microcontroller.

Basic Timer Operation Methods

This Arduino Nano microcontroller uses the atmega328p chip, which has three timers: Timer 0 (8-bit), Timer 1 (16-bit), and Timer 2 (8-bit). Functions such as delay(), millis(), and Serial rely on Timer 0, so we cannot use Timer 0 for this project. We will choose Timer 2, but Timer 1 can also be used.
Steps to Set Up Arduino Timer:
  1. Set the initial value and timing for the timer;
  2. Set the timer matching mode;
  3. Set the prescaler mode, which is related to the timing.
The matching modes of the Arduino timers include normal mode, CTC mode, fast PWM mode, and phase-correct PWM mode. This project adopts CTC mode, which is used for outputting square wave signals with a 50% duty cycle.
Each timer has a counter that increments with each clock cycle. When the counter reaches a specified value stored in a register, it triggers the CTC timer interrupt. Once the counter of the timer reaches that value, it will reset to zero at the next timer clock, and then it will continue counting again, repeating this process. By selecting the comparison matching value and setting the speed of the timer’s incrementing counter, we can control the frequency of the timer interrupt.

Prescaler and Comparison Matcher

The Arduino clock runs at 16MHz. One count value of the counter represents 1/16000000 seconds (~63ns), and it takes 16000000 counts to complete 1 second.
1. Timer 0 and Timer 2 are 8-bit timers, which can store a maximum counter value of 255.
2. Timer 1 is a 16-bit timer, which can store a maximum counter value of 65535.
Once the counter reaches its maximum value, it will return to zero (this is called overflow). Therefore, it is necessary to perform frequency division on the clock frequency, which is done by the prescaler. The prescaler controls the increment speed of the timing counter.
The relationship between the timer speed (Hz) and the Arduino clock speed (16MHz) is as follows:
Timer Speed (Hz) = Arduino Clock Speed (16MHz) / Prescaler Coefficient
Therefore, a prescaler of 1 will increment the counter at 16MHz, a prescaler of 8 will increment at 2MHz, a prescaler of 64 will increment at 250kHz, and so on.
This time, we set the timer to 64 prescaler, with an interrupt frequency of 60000Hz, within the maximum frequency range of the timer.

Basic Timer Instructions

#define FRQ_TIMER2 (60000) //Timer 2 overflow speedTIMSK2 = _BV(OCIE2A);//Enable Timer 2 interruptTIMSK2 = 0;//Disable Timer 2 interruptTCCR2A = _BV(WGM21);//CTC mode for outputting square wave signal with 50% duty cycleTCCR2B = _BV(CS22);//64 prescalerTCNT2 = 0;//Clear Timer 2 counter registerOCR2A = 1;//Set comparison register to 1
After understanding the basic instructions for the timer, let’s look at how to count the timer. By modifying the count value, we can send different frequencies, as shown in the code below.

Counting Timer

int  xFrequency = 0;//Square wave frequency variableint  xCounter = 0;//Counting variableISR(TIMER2_COMPA_vect) {    if (xFrequency != 0)    {        if (++xCounter>= (xFrequency))        {            xCounter = 0;            if (bitRead(PORTD, xMOTOR)) //Read bit from value            {                bitClear(PORTD, xMOTOR);//Clear a certain bit of the value to 0            }            else            {                bitSet(PORTD, xMOTOR); //Set a certain bit of the value to 0            }        }    }}
Having learned how to generate pulse square waves using timers, we also need to control the stepper motor. To control the stepper motor, we need to have a good understanding of the microcontroller’s pins. Below is the pin diagram of the Arduino Nano microcontroller used in this project. This time, we need to quickly provide interrupt signals to external devices, so we will use the PCINT pin numbers for programming, rather than the commonly used Arduino PIN pins (brown icon).

Creating a Palm-Sized Electronic Piano with a Stepper Motor

Figure 50 ATMEGA328 Chip Pin Definition

For example, in this project, we connect the stepper motor to the M1 terminal of the circuit board, so the corresponding enable pin ENABLE of the circuit board is D13 (PCINT5), the step pin STEP is D3 (PCINT19), and the direction pin DIR is D2 (PCINT18); if we use the PCINT number setting method, it is as follows:
#define ENABLE PCINT5  //Enable pin#define xMOTOR PCINT19  //Step pin#define xDIR PCINT18   //Direction pinDDRB = _BV(ENABLE);//Set enable pinDDRD = _BV(xMOTOR) | _BV(xDIR) ;

Key Detection

Earlier, we learned how to use the keys and the potentiometer. Now we will set up the program to detect when any of the seven keys are pressed to produce different frequencies. The time for different frequencies is calculated using the following formula:
xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[0+num*7])
FRQ_TIMER2 is the interrupt frequency of the timer, and pgm_read_float(&pitches[0+num*7]) is the frequency corresponding to different pitches. Dividing the two gives us the time needed to send that square wave pulse.

The code is as follows:

#define FRQ_TIMER2 (60000) //Timer 2 overflow speedvoid loop() {  num = map(analogRead(A0),0,1023,0,4);  if ((digitalRead(12) || digitalRead(11)) || (digitalRead(10) || (digitalRead(9) || (digitalRead(8) || (digitalRead(7) || digitalRead(6)))))) {    TIMSK2 = _BV(OCIE2A);//Enable Timer 2 interrupt    if (digitalRead(12)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[0+num*7]);    }    if (digitalRead(11)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[1+num*7]);    }    if (digitalRead(10)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[2+num*7]);    }    if (digitalRead(9)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[3+num*7]);    }    if (digitalRead(8)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[4+num*7]);    }    if (digitalRead(7)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[5+num*7]);    }    if (digitalRead(6)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[6+num*7]);    }  } else {    TIMSK2 = 0;//Disable Timer 2 interrupt  }}

Complete Code

Finally, here is the complete code for the stepper motor electronic piano.

typedef struct {    float xfr;}MUSIC;//Pitch and frequency#define PITCHES_LENGTH 35const MUSIC pitches[PITCHES_LENGTH] PROGMEM = {   130.813,//O3  146.832,  164.814,  174.614,  195.998,  220.000,  246.942,   261.626,//O4  293.665,  329.629,  349.228,  391.995,  440.000,  493.883,   523.251,//O5  587.330,  659.255,  698.456,  783.991,  880.000,  987.767,   1046.502,//O6  1174.659,  1318.520,  1396.913,  1567.982,  1760.000,  1975.533,  2093.004,//O7  2349.318,  2637.020,  2793.826,  3135.437,  3520.000,  3951.066,};#define FRQ_TIMER2 (60000) //Timer 2 overflow speedint  xFrequency = 0;//Square wave frequency variableint xCounter = 0;//Counting variableint num;  //Pitch variable#define ENABLE PCINT5  //Enable pin#define xMOTOR PCINT19  //Step pin#define xDIR PCINT18   //Direction pinvoid setup() {    TCCR2A = _BV(WGM21);//CTC mode for outputting square wave signal with 50% duty cycle    TCCR2B = _BV(CS22);//64 prescaler    TCNT2 = 0;//Clear Timer 2 counter register    OCR2A = 1;//Set comparison register to 1    TIMSK2 = _BV(OCIE2A);//Enable Timer 2 interrupt    DDRB = _BV(ENABLE);//Set enable pin    DDRD = _BV(xMOTOR) | _BV(xDIR) ;    PORTD = 0;    Serial.begin(9600);}void loop() {  num = map(analogRead(A0),0,1023,0,4);  if ((digitalRead(12) || digitalRead(11)) || (digitalRead(10) || (digitalRead(9) || (digitalRead(8) || (digitalRead(7) || digitalRead(6)))))) {    TIMSK2 = _BV(OCIE2A);//Enable Timer 2 interrupt    if (digitalRead(12)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[0+num*7]);      Serial.println(xFrequency);    }    if (digitalRead(11)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[1+num*7]);    }    if (digitalRead(10)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[2+num*7]);    }    if (digitalRead(9)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[3+num*7]);    }    if (digitalRead(8)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[4+num*7]);    }    if (digitalRead(7)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[5+num*7]);    }    if (digitalRead(6)) {      xFrequency = FRQ_TIMER2/pgm_read_float(&pitches[6+num*7]);    }  } else {    TIMSK2 = 0;//Disable Timer 2 interrupt  }}ISR(TIMER2_COMPA_vect) {    if (xFrequency != 0)    {        if (++xCounter>= (xFrequency))        {            xCounter = 0;            if (bitRead(PORTD, xMOTOR))            {                bitClear(PORTD, xMOTOR);            }            else            {                bitSet(PORTD, xMOTOR);            }        }    }}

With this, the stepper motor electronic piano is completed.

#Summary#

In this stepper motor piano project, we learned about some programming methods on Arduino registers, understood the technique of using timers to improve the speed of program execution, mastered the method of adding pull-up resistors to tactile switches to stabilize signals, and learned how to adjust tones using potentiometers. By understanding these basic knowledge and skills, we can easily add more stepper motors. Theoretically, the more stepper motors there are, the richer the music that can be played. Friends who are interested can give it a try, and we look forward to your wonderful creativity.
That’s all for this sharing.
Making life better through creation, see you next time!
If you also like the compact stepper motor electronic piano but don’t want to make it yourself, you can click the image below to purchase it.
Creating a Palm-Sized Electronic Piano with a Stepper Motor

Leave a Comment

×