3 * For that authentic retro sound...
4 * Er... A little experiment to produce tones out of a Pi using
5 * one (or 2) GPIO pins and a piezeo "speaker" element.
6 * (Or a high impedance speaker, but don'y blame me if you blow-up
8 * Copyright (c) 2012 Gordon Henderson
9 ***********************************************************************
10 * This file is part of wiringPi:
11 * https://projects.drogon.net/raspberry-pi/wiringpi/
13 * wiringPi is free software: you can redistribute it and/or modify
14 * it under the terms of the GNU Lesser General Public License as
15 * published by the Free Software Foundation, either version 3 of the
16 * License, or (at your option) any later version.
18 * wiringPi is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with wiringPi.
25 * If not, see <http://www.gnu.org/licenses/>.
26 ***********************************************************************
37 #define PULSE_TIME 100
39 static int freqs [MAX_PINS] ;
40 static pthread_t threads [MAX_PINS] ;
42 static int newPin = -1 ;
47 * Thread to do the actual PWM output
48 *********************************************************************************
51 static PI_THREAD (softToneThread)
53 int pin, freq, halfPeriod ;
54 struct sched_param param ;
56 param.sched_priority = sched_get_priority_max (SCHED_RR) ;
57 pthread_setschedparam (pthread_self (), SCHED_RR, ¶m) ;
71 halfPeriod = 500000 / freq ;
73 digitalWrite (pin, HIGH) ;
74 delayMicroseconds (halfPeriod) ;
76 digitalWrite (pin, LOW) ;
77 delayMicroseconds (halfPeriod) ;
87 * Write a frequency value to the given pin
88 *********************************************************************************
91 void softToneWrite (int pin, int freq)
97 else if (freq > 5000) // Max 5KHz
106 * Create a new tone thread.
107 *********************************************************************************
110 int softToneCreate (int pin)
115 pinMode (pin, OUTPUT) ;
116 digitalWrite (pin, LOW) ;
118 if (threads [pin] != 0)
124 res = pthread_create (&myThread, NULL, softToneThread, NULL) ;
129 threads [pin] = myThread ;
137 * Stop an existing softTone thread
138 *********************************************************************************
141 void softToneStop (int pin)
143 if (threads [pin] != 0)
145 pthread_cancel (threads [pin]) ;
146 pthread_join (threads [pin], NULL) ;
148 digitalWrite (pin, LOW) ;