Adafruit I2S mems microphone not working with Contune Speech recognition. (Google cloud speech api) - raspberry-pi

I am using this library with Raspberry pi 3 with Raspbian and Adafruit I2S mems microphone. I am able to work i2s mic with raspberry pi and it is working working perfectly for normal recording, but while using Speech_Recognition with Google Speech Cloud API it was not working so, I did some Trickery and it is working perfect with microphone_recognition.py.
The trick I used is in
microphone_recognition.py
r = sr.Recognizer()
with sr.Microphone(device_index = 2, sample_rate = 48000) as source:
print("Say something!")
audio = r.record(source, duration = 5)
speech_recognition/__init__.py
self.device_index = device_index
self.format = self.pyaudio_module.paInt32
and it worked perfectly output
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM bluealsa
connect(2) call to /tmp/jack-1000/default/jack_0 failed (err=No such
file or directory) attempt to connect to server failed Say something!
Google Cloud Speech thinks you said hello
But while trying background_listening.py
import time
import speech_recognition as sr
# this is called from the background thread
def callback(recognizer, audio):
GOOGLE_KEY= r"""{ MY KEY }"""
# received audio data, now we'll recognize it using Google Speech Recognition
try:
print("Google Speech Recognition thinks you said " + recognizer.recognize_google_cloud(audio, credentials_json=GOOGLE_KEY))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
r = sr.Recognizer()
with sr.Microphone(device_index=2, sample_rate = 48000) as source:
r.adjust_for_ambient_noise(source) # we only need to calibrate once, before we start listening
# start listening in the background (note that we don't have to do this inside a `with` statement)
stop_listening = r.listen_in_background(source, callback)
# `stop_listening` is now a function that, when called, stops background listening
# do some unrelated computations for 5 seconds
for _ in range(50): time.sleep(0.1) # we're still listening even though the main thread is doing other things
# calling this function requests that the background listener stop listening
stop_listening(wait_for_stop=False)
# do some more unrelated things
while True: time.sleep(0.1)
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM bluealsa
connect(2) call to /tmp/jack-1000/default/jack_0 failed (err=No such
file or directory) attempt to connect to server failed
I am using the same settings of speech_recognition/init. Not giving the output.
Addition to the question after debugging
I stay in the loop given below and don't go forward and dont get to call the callback(recognizer, audio) I am using ### init.py self.format = self.pyaudio_module.paInt32 and the belove code is also from the same.
Some debugging -
print(format(energy))
print(format(self.energy_threshold))
if energy > self.energy_threshold:
print("inside energy")
print(format(energy))
print(format(self.energy_threshold))
break
# dynamically adjust the energy threshold using asymmetric weighted average
if self.dynamic_energy_threshold:
print(" inside dynamic_energy_threshold")
damping = self.dynamic_energy_adjustment_damping ** seconds_per_buffer
target_energy = energy * self.dynamic_energy_ratio
self.energy_threshold = self.energy_threshold * damping + target_energy * (1 - damping)
print(format(self.energy_threshold))
print("end dynamic_energy_threshold")
102982050
117976102.818 - Beginng and always high so never gone break this loop, Even after speaking, inside dynamic_energy_threshold
119548935.608 end dynamic_energy_threshold inside listen -6.1.1 97861662
119548935.608 inside dynamic_energy_threshold
120722993.56 end dynamic_energy_threshold inside listen -6.1.1 84062664
120722993.56
Here I tried equalling energy and trishold energy and break the loop.
print(format(energy))
print(format(self.energy_threshold))
**self.energy_threshold = float(energy)**
if energy >= self.energy_threshold:
**print("inside energy")**
print(format(energy))
print(format(self.energy_threshold))
break
Output
105836705
116487614.952 = This is the Energy threshold Which is always High. and continue looping inside energy
105836705
105836705.0

So i did a work around,
Soltion -
speech_recognition/__init__.py - Lib
Microphone.__init__() - Method
self.format = self.pyaudio_module.paInt32
Recognizer/adjust_for_ambient_noise - Method
energy = audioop.rms(buffer, source.SAMPLE_WIDTH)/1000000
And it is working really perfect but now i have to find a way to stop sending request to Google speech api if there no Speech.

Related

How Do I Make A Pi Pico W Connect To A Network With Wps?

First time using Stack overflow so I'll do my best to explain.
TLDR - HOW DO I MAKE A PI PICO W CONNECT TO A NETWORK WITH WPS?
I'm making a thing, that basically checks whether the value of a particular stock has gone up or down and lights up green or red LED's based on whether the price is up or down. That's all well and good, but to do this it needs to connect to wifi, and being that the thing I'm making has no screen, or keyboard, all we have to accomplish this is the LED's (for the device to communicate with us) and whatever button I put on there.
My plan was to have the device look at a file called "your_wifi_details.txt" for the SSID and pass, and if it finds them, connect - if nothing is there, or if it cannot connect using those details, it is to enter "WPS mode" where the lights will flash, and the user presses the WPS button on their router then presses a button on the device.
Everything is wired up and working perfectly aside from I cannot work out how to get WPS to work on a Pi Pico W. I think I've gotten really close, but i'm getting the error "'CYW43' object has no attribute 'scan_wps'"
(The lines of code are:
# If the button is pressed, scan for WiFi networks that support WPS
if not button.value():
sta_if.scan_wps()
# Connect to the first WiFi network that supports WPS
sta_if.connect_wps()
)
Then it goes on to connect to the API's and such to get the stock price and from there everything is good.
Literally everything works, if I manually go into the "your_wifi_details.txt" and put in a correct SSID and password, we're golden, but I can't have users required to download thonny and connect to the device and edit files and yada yada... so I am really hoping this WPS thing can work.
This is the first 'proper' program i've written since starting to learn python so apologies if this is a stupid approach, it's taken a lot or time and confusion to get this far but it's so nearly working, I just need a little help over the finish line so if anyone has faced this problem or can help me toward a solution I'd be super grateful
Here's excerpts from the relevant bits of code that are connected to the problem. There's a lot of "print" debugging commands so I can see in the terminal in Thonny where the program is at and what it's doing, obviously in the final use case there won't be a screen or keyboard so all that stuff will be taken out once development is complete:
import urequests
import network
import time
import machine
#--------------(Stackoverflow comment) then further down
#stackoverflow comment: I don't know why this next line is in bold, it shouldn't be
# Set up the button (connected to pin 15)
button = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP)
print ('pin 15 set as button')
#--------------(Stackoverflow comment) then further down still
while True:
print ('enter while true loop')
# Connect to the WiFi network
sta_if = network.WLAN(network.STA_IF)
#print ('firstline passed, sleeping for 10 seconds')
#ignore this, unnecessary now
#for i in range (0, 20):
# time.sleep(0.55)
# print ('sleeping...')
#print ('nap over, trying to continue..')
sta_if.active(True)
print ('firing up connection')
# Read the WiFi SSID and password from the text file
with open("your_wifi_details.txt", "r") as f:
ssid = f.readline().strip()
password = f.readline().strip()
print ('read your_wifi_details.txt successfully')
# Try to connect to the WiFi network
sta_if.connect(ssid, password)
print ('attempting to connect to wifi')
# Wait until the device is connected to the WiFi network
while not sta_if.isconnected():
# Flash the LEDs to indicate that the device is unable to connect
print ('connection failed, attempting to flash LEDs')
green_led.on()
red_led.on()
time.sleep(0.5)
green_led.off()
red_led.off()
time.sleep(0.5)
# Set up the button (connected to pin 0)
print ('setting up button for WPS')
button = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP)
# If the button is pressed, scan for WiFi networks that support WPS
if not button.value():
sta_if.scan_wps()
# Connect to the first WiFi network that supports WPS
sta_if.connect_wps()
# Save the WiFi SSID and password to the "your_wifi_details.txt" file
with open("your_wifi_details.txt", "w") as f:
f.write(sta_if.config("essid") + "\n")
f.write(sta_if.config("password") + "\n")
print ('wifi details written to file')
# Print the WiFi connection status in the terminal so I can see if it worked
print("Connected to WiFi:", sta_if.isconnected())

Audio widget within Jupyter notebook is **not** playing. How can I get the widget to play the audio?

I writing my code within a Jupyter notebook in VS Code. I am hoping to play some of the audio within my data set. However, when I execute the cell, the console reports no errors, produces the widget, but the widget displays 0:00 / 0:00 (see below), indicating there is no sound to play.
Below, I have listed two ways to reproduce the error.
I have acquired data from the hub data store. Looking specifically at the spoken MNIST data set, I cannot get the data from the audio tensor to play
import hub
from IPython.display import display, Audio
from ipywidgets import interactive
# Obtain the data using the hub module
ds = hub.load("hub://activeloop/spoken_mnist")
# Create widget
sample = ds.audio[0].numpy()
display(Audio(data=sample, rate = 8000, autoplay=True))
The second example is a test (copied from another post) that I ran to see if it was something wrong with the data or something wrong with my console, environment, etc.
# Same imports as shown above
# Toy Function to play beats in notebook
def beat_freq(f1=220.0, f2=224.0):
max_time = 5
rate = 8000
times = np.linspace(0,max_time,rate*max_time)
signal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)
display(Audio(data=signal, rate=rate))
return signal
v = interactive(beat_freq, f1=(200.0,300.0), f2=(200.0,300.0))
display(v)
I believe that if it is something wrong with the data (this is a well-known data set so, I doubt it), then only the second one will play. If it is something to do with the IDE or something else, then neither will work, as is the case now.
Apologies for the late reply! In the future, please tag the questions with activeloop so it's easier to sort through (or hit us up directly in community slack -> slack.activeloop.ai).
Regarding the Free Spoken Digit Dataset, I managed to track the error with your usage of activeloop hub and audio display.
adding [:,0] to 9th line will help fixing display on Colab as Audio expects one-dimensional data
%matplotlib inline
import hub
from IPython.display import display, Audio
from ipywidgets import interactive
# Obtain the data using the hub module
ds = hub.load("hub://activeloop/spoken_mnist")
# Create widget
sample = ds.audio[0].numpy()[:,0]
display(Audio(data=sample, rate = 8000, autoplay=True))
(When we uploaded the dataset, we decided to upload the audio as (N,C) where C is the number of channels, which happens to be 1 for the particular dataset. The added dimension wasn't added automatically)
Regarding the VScode... the audio, unfortunately, would still not work (not because of us, but VScode), but you can still try visualizing Free Spoken Digit Dataset (you can play the music there, too). Hopefully this addresses your needs!
Let us know if you have further questions.
Mikayel from Activeloop

What am I missing? Send data from Matlab to Arduino to Micro SD

First off. This is not in any way a class assignment. This is my own personal work and research. I just want to get that out of the way.
I am learning how to use Matlab with various Arduino projects. I am a seasoned Matlab user but I am fairly new to the entire Arduino space.
I am trying to send some numerical data from Matlab (via a GUI) to my Arduino Uno and have the Arduino write it to my micro SC card. This is a temporary step to my larger project. However, there is no need to go into those specifics as they are outside of the scope of my issues.
I am fairly confident that the Matlab code works and the Arduino code is slightly modified from another project I did where I wrote and read random numbers from my micro SD card.
However, as I run the Matlab code, the Arduino blinks as if it is receiving the data but after I check the micro SD card it remains blank.
I am confident that my Arduino is wired correctly to my micro SD card adapter since this remains the same from my prior project.
Therefore, I am sure I am missing something trivial to get it to work.
I have researched several websites on the subject and their method and mine seem to align very well.
I am fairly certain the problem is in the conditional statement:
if (Serial.available() > 0) {
As you will see.
The Matlab code is below:
arduinoCom = serial('COM3', 'BaudRate', 115200);
sendData = 5;
fopen(arduinoCom);
fprintf(arduinoCom,'%i',sendData); %this will send 5 to the arduino
fclose(arduinoCom);
delete(arduinoCom);
The Arduino code is as follows:
#include <SD.h> // load SD library
int chipSelect = 4; // Chip select pin for the MicroSD Card Adapter
int incomingByte = 0; // for incoming serial data.
File SDF; // Serial data received is saved here.
void setup() {
Serial.begin(115200); // start serial connection to print out debug messages and data
pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
while (!Serial) {
}
}
void loop() {
// Open file, Write data, Close file only when you receive data
if (Serial.available() > 0) {
incomingByte = Serial.read();
SDF = SD.open("SerialDataFile.txt", FILE_WRITE); // open "SerialDataFile.txt" to write data
SDF.println(incomingByte, DEC); // write ASCII-encoded decimal number to file
SDF.close(); // close file
}
}
The expected result would be a file "SerialDataFile.txt" stored on my micro SD card with the value 5.
Thank you for your help!

Xojo detect input from 2 inputs with interrupts. (Raspberry Pi)

I have a raspberry pi 3 running a program made in Xojo.
My goal is to have two flow sensors which display the amount of water that flows though each sensor on the screen.
I have a program that works for one flow sensor, it uses the GPIO library and a custom module called 'InterruptModule'. I followed a tutorial to make this program.
Tutorial: https://einhugur.com/blog/index.php/xojo-gpio/connecting-button-with-gpio-and-using-interupts/#comment-14
This program works successfully for both flow sensors, but only one at a time. I.e if I change the input pin and run the program again it works.
HOWEVER, when I try combine the two it responds can't differentiate between the two inputs.
I have tried with two GPIO modules and two custom 'InterruptModule' modules but it still counts the inputs under whichever sensor is defined first.
See my attempt here.
Screenshot of Xojo code
One way to differentiate between the two interrupts is to create two separate callback method.
Example:
Const kPin = 14
If GPIO.WiringPiISR(kPin, GPIO.EDGE_RISING, Addressof InteruptModule.ButtonDownInterupt1) = -1 then
MsgBox "Could not register for Interupt1 on kPin14"
End If
Const kPin = 18
If GPIO.WiringPiISR(kPin, GPIO.EDGE_RISING, Addressof InteruptModule.ButtonDownInterupt2) = -1 then
MsgBox "Could not register for Interupt2 on kPin18"
End If
In this example, each pin interruption would have its own callback method with different code to work with each pin.

How to calculate Voice and Data usage in BlackBerry 10 application

Hi I am developing an application in BlackBerry 10 platform which will calculate data usage and voice usage of user device for particular duration.
There are some of the feasibility check need to be done for this which are as follows
Does BB10 API supports data usage calculation? If yes, Can I differentiate 3G/Cellular data from WiFi data?If yes, how can I achieve this?
How can I calculate Voice usage in BB 10 application? Voice usage is nothing but duration of all calls happened within particular timespan
Is there any API BB10 provides through which I can check if device is currently in Roaming or not?
Please let me know if this can be done in BB 10 application
Does BB10 API supports data usage calculation?
Yes, there are a few for API's for this
Can I differentiate 3G/Cellular data from WiFi data?
Yurp you can.
1) Add the following line to your .pro file:
LIBS += -lbbdevice
2) Make sure you include:
#include <bb/device/NetworkDataUsage>
3) Getting data useage for cellular network only
bb::device::NetworkDataUsage *nduCell = new bb::device::NetworkDataUsage("cellular0");
nduCell ->update();
quint64 bytesSent = nduCell ->bytesSent();
quint64 bytesReceived = nduCell ->bytesReceived();
4) Getting data useage for wifi only
bb::device::NetworkDataUsage *nduWifi = new bb::device::NetworkDataUsage("tiw_sta0");
nduWifi ->update();
quint64 bytesSent = nduWifi ->bytesSent();
quint64 bytesReceived = nduWifi ->bytesReceived();
That will give your the data useage since the device has started.
You will need to call ndu->update() regularly to get the most recent data usage statistics.
Extra Info:
Changing the parameter for the NetworkDataUsage changes the interface it minitors:
cellular0 == Cellular
tiw_sta0 == Wifi
ecm0 == USB
To find out which interfaces are available on your device:
1) Add the following line to your .pro file:
QT += network
2) Make sure you include:
#include <QNetworkInterface>
3) Displaying available interfaces
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
for (int i = 0; i < interfaces.size(); i++) {
qDebug() << QString::number(i) + ": " + interfaces.value(i).humanReadableName();
}
How can I calculate Voice usage in BB 10 application? Voice usage is nothing but duration of all calls happened within particular timespan
This can be done using Phone class.
There is signal call void callUpdated (const bb::system::phone::Call &call, ) using which we can get to know if incoming call is received or outgoing call is initiated.
With the combination of this and Timer class we can calculate Voice usage of device. (This code is not tested)