Hi, is it possible for Arduino to output square waves with different frequencies at the same time? Like say 200 Hz on pin 2, 300 Hz on pin 3 and so on.
Yes, it is.
Perhaps you can do it with the tone function or maybe even with the NewTone library. However, I am not sure if they can do multiple pins at the same time. (not that the arduino is capable of doing anything at the exact same time) But its worth looking into.
Sure. Check this thread, I created up to 13 tones (square waves) at one time with blink without delay using a '1284P, 13 pins to read button presses and 13 outputs.
Could do the same with an Uno with 9 in & out & leaving the serial pins free still.
Code, schematics, youtube video:
Wow, actually this very close to what I want to do but I want to do it with Arduino Mega. Could you explain what your program does so I can adapt it to Mega? Thanks very much.
What's left to explain? The code is very well commented, I did that so I could make changes in the future if needed.
For a Mega, you need to change the PORT A, B, C, D references to the appropriate Mega pin numbers.
On the Mega, not all Port D pins are broken out to headers, I would change that to another port, such as F, K, or L:
byte keyArray[]={
2,3,30,8,9,31,4,5,6,7,10,11,12,13,}; //Ports D2,D3,D4,D5,D6,D7,B0,B1,B2,B3,B4,B5,B6, added b7 - notes 48, 47,46,45,44,43,42,41,40,39,38,37,36
byte outputArray[] = {
14,15,16,17,18,19,22,23,24,25,26,27,28, 21,22,29}; // Ports A0,A1,A2,A3,A4,A5,C0,C1,C2,C3,C4,C5,C6, added a6, a7, c7
byte portDkeys;
byte portBkeys;
byte portAnotes;
byte portCnotes;
portDkeys = PIND; // Read the input keys - using direct port manipulation for speed
portBkeys = PINB;
Then change each of these to agree with the ports you selected:
/* Check if key for note C4 is pressed, key0 */
if ((portDkeys & 0x04) == 0){ // key is pressed D2 -> A2
if (keyActive[0]==0){
keyActive[0] = 1;
changeTime[0] = currentTime;
}
// see if time to change hi to lo, or lo to hi
if ( (currentTime - changeTime[0])>=noteArray[48]){ // time for a period toggle?
changeTime[0] = changeTime[0] + noteArray[48]; // setup time for the next toggle
PINA=0x04; // write a 1 to PINx toggles an output bit - NickGammon to the rescue again!
}
}
else{keyActive[0] = 0;}