|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
  Raspberry Pi Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  AutoIt (Programación) Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


.

Arduino en español
Circuitos con Arduino - Juan Antonio Villalpando

-- Tutorial de iniciación a Arduino --

Volver al índice del tutorial

____________________________

6B.- Frecuencímetro. Emisor común con saturación.

- Código para que el Arduino se comporte como un frecuencímetro. Observaremos el resultado en el Monitor Serie.

- Medirá desde unos 50 Hz hasta unos 30 kHz con un error de un 2 % aproximadamente.

- Conectamos un generador a la entrada 12 del Arduino y observamos su frecuencia en el Monitor Serie.

- La señal de entrada debe tener niveles entre 1 V y 4 V, aproximadamente, para poder ser medida.

- Aunque puede medir señales sinusoidales, mide mejor señales cuadradas.

 

frecuencimetro.ino

// Frecuencímetro
// kio4.com			

int input=12;

int high_time;
int low_time;
float time_period;
float frequency;

void setup()
{
Serial.begin(9600);
pinMode(input,INPUT);
}

void loop(){
high_time=pulseIn(input,HIGH);
low_time=pulseIn(input,LOW);

time_period=high_time+low_time;
time_period=time_period/1000;
frequency=1000/time_period;
Serial.println(frequency);
delay(1000);
}		

- Utiliza un Arduino para crear un PWM y otro Arduino para medir su frecuencia.

____________________________________
- Amplificador Emisor Común con saturación y corte.

- Supongamos que queremos medir señales pequeñas, por ejemplo de 30 mV, esta señal no activará alternadamente los estados ALTO y BAJOS del terminal de entrada del Arduino, ya que es demasiado pequeña.

- Podemos convertir esa señal a otra de mayor nivel, entre 1 V y 4 V, aproximadamente mediante un amplificador.

- Observa el amplificador, se suministramos una señal sinusoidal de 30 mVp y obtenemos una señal entre 4,5 V y 0,9 V

- Si en vez de introducir una señal de 30 mVp, introducimos otra de 300 mVp, el transistor funcionará en corte-saturación y obtendremos la señal siguiente.

- Nos servirá esta señal, ya que queremos obtener señales grandes, no nos importa que la señal haya sido distorsionada a cuadrada como indica la imagen.

- El máximo nivel de audio de los móviles, es de unos 200 mV.

____________________________________
- Construcción de la placa del circuito impreso con PCBWizard.


- Lado de los componentes. No está a escala. He añadido un condensador electrolítico en la salida.

____________________________________
- Conexión al Arduino.

- Conectamos al conector del auricular mediante un jack de 3,5 mm

____________________________________
- Conexión al Arduino con el módulo del LM386.

- Si no queremos construir el amplificador anterior, compramos este módulo con el amplificador LM386, tiene un precio inferior a 1 €.

- Por su facilidad, esta es la mejor propuesta:

 

 

_________________________________________________
- Vamos a crear nuestro propio generador de tonos:

____________________________________
- Generador de tonos con JavaScript.

- Vamos a ver un par de ejemplos de un generador de tonos mediante JavaScript.

1.- Este código es una adaptación de: https://www.the-art-of-web.com/javascript/creating-sounds/

- Necesita el archivo soundplayer.js

sonido.html
Sound Player




sonido.html

<!DOCTYPE html>
<head>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form id="soundForm" style="width: 48%">
<fieldset>
<legend>Sound Player  </legend>
<label>Frequency</label><span><input type="range" name="freq" value="261" min="22" max="20000" oninput="myPlayer.setFrequency(this.value);"></span>
<label>Volume</label><span><input type="range" name="vol" value="50" min="0" max="200" oninput="myPlayer.setVolume(this.value/100);"></span><br>
<label><input type="radio" name="wave" value="sine" checked="" onclick="myPlayer.setWaveType(this.value);"> sine</label><br>
<label><input type="radio" name="wave" value="square" onclick="myPlayer.setWaveType(this.value);"> square</label><br>
<label><input type="radio" name="wave" value="sawtooth" onclick="myPlayer.setWaveType(this.value);"> sawtooth</label><br>
<label><input type="radio" name="wave" value="triangle" onclick="myPlayer.setWaveType(this.value);"> triangle</label><br>
</span>
<span>
<input name="play" type="button" onclick="
  myPlayer.play(form.freq.value, form.vol.value/100, checkRadio(form.wave));
  this.style.display = 'none';
  form.stop.style.display = 'inline';
" value="Play ?" style="">
<input name="stop" style="display: none;" type="button" onclick="
  myPlayer.stop();
  form.play.style = 'inline';
  this.style.display = 'none';
" value="Stop ??"></span>
</fieldset>
</form>

<button onclick="(new SoundPlayer(audio)).play(440.0, 0.8, "sine").stop(0.5);">Run Example ?</button>
<button onclick="(new SoundPlayer(audio)).play(440, 0.5, "square").setFrequency(880, 0.1).stop(0.2);">Run Example ?</button>

<script src="soundplayer.js"></script>
<script>
  const checkRadio = (field) => {
    if((typeof field.length == "undefined") && (field.type == "radio")) {
      if(field.checked) return field.value;
    } else {
      for(let i=0; i < field.length; i++) {
        if(field[i].checked) return field[i].value;
      }
    }
    return false;
  };

  const AudioContext = window.AudioContext || window.webkitAudioContext;
  const audio = new AudioContext();
  myPlayer = new SoundPlayer(audio);
</script>
</body>			
			
soundplayer.js

// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.

function SoundPlayer(audioContext, filterNode) {
  this.audioCtx = audioContext;
  this.gainNode = this.audioCtx.createGain();
  if(filterNode) {
    // run output through extra filter (already connected to audioContext)
    this.gainNode.connect(filterNode);
  } else {
    this.gainNode.connect(this.audioCtx.destination);
  }
  this.oscillator = null;
}

SoundPlayer.prototype.setFrequency = function(val, when) {
  if(this.oscillator !== null) {
    if(when) {
      this.oscillator.frequency.setValueAtTime(val, this.audioCtx.currentTime + when);
    } else {
      this.oscillator.frequency.setValueAtTime(val, this.audioCtx.currentTime);
    }
  }
  return this;
};

SoundPlayer.prototype.setVolume = function(val, when) {
  if(when) {
    this.gainNode.gain.exponentialRampToValueAtTime(val, this.audioCtx.currentTime + when);
  } else {
    this.gainNode.gain.setValueAtTime(val, this.audioCtx.currentTime);
  }
  return this;
};

SoundPlayer.prototype.setWaveType = function(waveType) {
  this.oscillator.type = waveType;
  return this;
};

SoundPlayer.prototype.play = function(freq, vol, wave, when) {
  this.oscillator = this.audioCtx.createOscillator();
  this.oscillator.connect(this.gainNode);
  this.setFrequency(freq);
  if(wave) {
    this.setWaveType(wave);
  }
  this.setVolume(1/1000);
  if(when) {
    this.setVolume(1/1000, when - 0.02);
    this.oscillator.start(when - 0.02);
    this.setVolume(vol, when);
  } else {
    this.oscillator.start();
    this.setVolume(vol, 0.02);
  }
  return this;
};

SoundPlayer.prototype.stop = function(when) {
  if(when) {
    this.gainNode.gain.setTargetAtTime(1/1000, this.audioCtx.currentTime + when - 0.05, 0.02);
    this.oscillator.stop(this.audioCtx.currentTime + when);
  } else {
    this.gainNode.gain.setTargetAtTime(1/1000, this.audioCtx.currentTime, 0.02);
    this.oscillator.stop(this.audioCtx.currentTime + 0.05);
  }
  return this;
};					
			

2.- Este código es una adaptación de: https://stackoverflow.com/questions/6343450/generating-sound-on-the-fly-with-javascript-html5

frequency
type
volume
duration

sonido2B.html

<!DOCTYPE html>
<head>
<html lang="es"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
frequency
<input type="range" id="fIn" min="40" max="6000" oninput="show()" />
<span id="fOut"></span><br>
type
<input type="range" id="tIn" min="0" max="3" oninput="show()" />
<span id="tOut"></span><br>
volume
<input type="range" id="vIn" min="0" max="100" oninput="show()" />
<span id="vOut"></span><br>
duration
<input type="range" id="dIn" min="1" max="5000" oninput="show()" />
<span id="dOut"></span>
<br>
<button onclick='beep();'>Play</button>

<script>
audioCtx = new(window.AudioContext || window.webkitAudioContext)();
show();
function show() {
  frequency = document.getElementById("fIn").value;
  document.getElementById("fOut").innerHTML = frequency + ' Hz';

  switch (document.getElementById("tIn").value * 1) {
    case 0: type = 'sine'; break;
    case 1: type = 'square'; break;
    case 2: type = 'sawtooth'; break;
    case 3: type = 'triangle'; break;
  }
  document.getElementById("tOut").innerHTML = type;

  volume = document.getElementById("vIn").value / 100;
  document.getElementById("vOut").innerHTML = volume;

  duration = document.getElementById("dIn").value;
  document.getElementById("dOut").innerHTML = duration + ' ms';
}


function beep() {

  var oscillator = audioCtx.createOscillator();
  var gainNode = audioCtx.createGain();
  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);
  
  gainNode.gain.value = volume;
  oscillator.frequency.value = frequency;
  oscillator.type = type;

  oscillator.start();

  setTimeout(
    function() {
      oscillator.stop();
    },
    duration
  );
};
</script>
</body>							
			

____________________________________
- Generador de tono con App Inventor. JavaScript.

p67B_JavaScript_generadortono.aia

- Vamos a utilizar el código anterior sonido2B.html, adaptado a App Inventor, es decir los valores los tomará del bloque CadenaDeWebView.

- Las funciones son: sine, square, sawtooth y triangle.

sonido2.html

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head><body>
<body>
<!-- <button onclick='beep();'>Play</button> -->
<script>
    datos =  window.AppInventor.getWebViewString(); // Entrada de datos.
    datos = datos + ":";  
  
    valores = datos.split(":"); 
    frequency = valores[0];
    type = valores[1];
	volume = valores[2];
    duration = valores[3];

audioCtx = new(window.AudioContext || window.webkitAudioContext)();
function beep() {

  var oscillator = audioCtx.createOscillator();
  var gainNode = audioCtx.createGain();
  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);
  
  gainNode.gain.value = volume;
  oscillator.frequency.value = frequency;
  oscillator.type = type;

  oscillator.start();

  setTimeout(
    function() {
      oscillator.stop();
    },
    duration
  );
};

 beep()
</script>
</body>							
			

____________________________________
- Diseño.

- Observamos un error en la medida.

____________________________________
- Bloques.

___________________________________________________

- Generador de tonos mediante una extensión.

239.- Generador de sonido con tiempo y frecuencia. Sonidos pre establecidos en Android.

___________________________________________________

- Otra forma de generar sonido indicando los tiempos de los niveles.

https://stackoverflow.com/questions/32630211/javascript-generate-square-wave-sound

- En este caso tenemos una frecuencia de 1000 Hz, según entre un 1 o un 0, el tiempo entre los datos será el que indique cada sleep.

sonido3.html

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head><body>
<body>
 <button onclick='play();'>Play</button>
<script>
var frequency = 1000;
var data = {
    1: {duration:500, sleep:1000},
    0: {duration:500, sleep:500}
}
var audio = new(window.AudioContext || window.webkitAudioContext)();

//function creates an Oscillator. In this code we are creating an Oscillator for every tune, which help you control the gain. 
//If you want, you can try creating the Oscillator once and stopping/starting it as you wish.
function createOscillator(freq, duration) {
    var attack = 10, //duration it will take to increase volume full sound volume, makes it more natural
        gain = audio.createGain(),
        osc = audio.createOscillator();

    gain.connect(audio.destination);
    // gain.gain.setValueAtTime(0, audio.currentTime); //change to "1" if you're not fadding in/out
    // gain.gain.linearRampToValueAtTime(1, audio.currentTime + attack / 1000); //remove if you don't want to fade in
    // gain.gain.linearRampToValueAtTime(0, audio.currentTime + duration / 1000); //remove if you don't want to fade out
	gain.gain.value = 4;

    osc.frequency.value = freq;
    osc.type = "sine";
    osc.connect(gain);
    osc.start(0);


    setTimeout(function() {
        osc.stop(0);
        osc.disconnect(gain);
        gain.disconnect(audio.destination);
    }, duration)
}

function play() {
    //your pattern
    var song = [1,0,0,0,0];       

    timeForNext = 0;
    for (i=0;i<song.length;i++){            
        duration = data[song[i]].duration;
        //use timeout to delay next tune sound
        window.setTimeout(function(){
            createOscillator(frequency, duration);
        },timeForNext);         
        timeForNext+=data[song[i]].sleep;       
    }
}

//play the music
play();
</script>
</body>										
			

 

https://stackoverflow.com/questions/25684821/how-create-a-50hz-square-wave-on-android-and-play-it

 

________________________________

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información