unable to measure temperature from temperature sensor in arduino ,
its giving wrong temp = Temprature =499.51 * c. im connected tempreture sensor to arduino uno kit . i need the temp value like 35
int val;
int tempPin = 1;
void setup()
{
Serial.begin(9600);
}
void loop()
{
val = analogRead(tempPin);
float mv = ( val / 1024.0) * 5000;
float cel = mv / 10;
float farh = (cel * 9) / 5 + 32;
Serial.print("TEMPRATURE = ");
Serial.print(cel);
Serial.print("*C");
Serial.println();
delay(1000);
/* uncomment this to get temperature in farenhite
Serial.print("TEMPRATURE = ");
Serial.print(farh);
Serial.print("*F");
Serial.println();
*/
}
It is not clear what temperature sensor you are using. From your code, it would seem that you use an analog sensor. If so, you should
a) check the data sheet of the sensor and adjust your code accordingly
OR
b) calibrate your system by taking readings of known temperatures and adjusting your code accordingly.
With the info you give, it is difficult to be more specific.
Related
so I developed an app which will send a series of integers over Bluetooth (for RED, GREEN & BLUE) to a ESP32 which will then change the colour of 3 LED's (WS2811) based on the numbers it receives. It works the first time I send them but when I try to change the colour of the LED's a second time nothing happens.
By using the serial monitor of the Arduino IDE I have verified that the numbers are being received by the ESP32 every time I send the numbers, but I cannot understand why the LEDs are not changing colour after the first send.
The code is as follows :
#include <Arduino.h>
#include <fastled_config.h>
#define NUM_LEDS 3 // was 100
#define LED_TYPE WS2811
#define COLOR_ORDER RGB
#define DATA_PIN 4
//#define CLK_PIN 4
#define VOLTS 12
#define MAX_MA 4000
CRGBArray<NUM_LEDS> leds;
#define LED 2
int myRGB[30];
int counter =0;
int display =-1;
#include "BluetoothSerial.h"
// init Class:
BluetoothSerial ESP_BT;
// Parameters for Bluetooth interface
int incoming;
void setup() {
Serial.begin(115200);
ESP_BT.begin("ESP32_Control"); //Name of your Bluetooth interface -> will show up on your phone
delay( 3000 ); //safety startup delay
FastLED.setMaxPowerInVoltsAndMilliamps( VOLTS, MAX_MA);
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
.setCorrection(TypicalLEDStrip);
}
void loop() {
delay(1000);
Serial.println(myRGB[1]);
Serial.println(myRGB[2]);
Serial.println(myRGB[3]);
leds[0].r = myRGB[1];
leds[0].g = myRGB[2];
leds[0].b = myRGB[3];
leds[1].r = myRGB[4];
leds[1].g = myRGB[5];
leds[1].b = myRGB[6];
leds[2].r = myRGB[7];
leds[2].g = myRGB[8];
leds[2].b = myRGB[9];
FastLED.show();
// -------------------- Receive Bluetooth signal ----------------------
if (ESP_BT.available())
{
incoming = ESP_BT.read(); //Read what we receive
digitalWrite(LED, HIGH);
counter ++;
myRGB[counter] = incoming;
if (counter > 29) counter = 0;
Serial.print("counter :" );
Serial.println(counter);
Serial.print( myRGB[counter]);
}
} // end loop
It looks like the LED colors are being shown before before Bluetooth inputs are received.
I would move FastLED.show() to the end of loop().
FastLED.show();
} // end loop
sorry for the late reply.
Ok the following code works, it not really much different to the original code
apart from this :
enter code hereif (counter < 9)
myRGB[counter] = incoming;
enter code here }
Which I'm guessing did make a difference (although it shouldn't have)
enter code here
#include <Arduino.h>
#include <fastled_config.h>
#define NUM_LEDS 3 // was 100
#define LED_TYPE WS2811
#define COLOR_ORDER RGB
#define DATA_PIN 4
//#define CLK_PIN 4
#define VOLTS 12
#define MAX_MA 4000
CRGBArray<NUM_LEDS> leds;
#define LED 2
int myRGB[30];
int counter =0;
int displayCounter =-1;
#include "BluetoothSerial.h"
// init Class:
BluetoothSerial ESP_BT;
// Parameters for Bluetooth interface
int incoming;
void setup() {
Serial.println("ESP started !!");
Serial.begin(115200);
ESP_BT.begin("ESP32_Control"); //Name of your Bluetooth interface -> will show up on your phone
delay( 3000 ); //safety startup delay
FastLED.setMaxPowerInVoltsAndMilliamps( VOLTS, MAX_MA);
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
.setCorrection(TypicalLEDStrip);
}
void loop() {
delay(20); // WITHOUT THIS LINE MORE LIKELY TO GET INCORRECT DATA FROM BLUETOOTH
displayCounter ++;
if (displayCounter < 4){
Serial.println("***** the following values going into led[0] ( R G B ) *** ");
Serial.println(myRGB[1]);
Serial.println(myRGB[2]);
Serial.println(myRGB[3]);
Serial.println("***** the following values going into led[1] ( R G B ) *** ");
Serial.println(myRGB[4]);
Serial.println(myRGB[5]);
Serial.println(myRGB[6]);
Serial.println("***** the following values going into led[2] ( R G B ) *** ");
Serial.println(myRGB[7]);
Serial.println(myRGB[8]);
Serial.println(myRGB[9]);
}
leds[0].r = myRGB[1];
leds[0].g = myRGB[2];
leds[0].b = myRGB[3];
leds[1].r = myRGB[4];
leds[1].g = myRGB[5];
leds[1].b = myRGB[6];
leds[2].r = myRGB[7];
leds[2].g = myRGB[8];
leds[2].b = myRGB[9];
FastLED.show();
// -------------------- Receive Bluetooth signal ----------------------
if (ESP_BT.available())
{
displayCounter = -1;
incoming = ESP_BT.read(); //Read what we receive
//digitalWrite(LED, HIGH);
counter ++;
if (counter < 9)
myRGB[counter] = incoming;
}
else {counter = 0;
// Serial.println("End of bluetooth data");
}
} // end loop
I am a newbie in Java Sounds. I want to play 2 different frequencies alternatively for 1 second each in a loop for some specified time.
Like, if I have 2 frequencies 440hz and 16000hz and the time period is 10 seconds then for every 'even' second 440hz gets played and for every 'odd' second 16000hz, i.e. 5 seconds each alternatively.
I have learned a few things through some examples and I have also made a program that runs for a single user specified frequency for a time also given by the user with the help of those examples.
I will really appreciate if someone can help me out on this.
Thanks.
I am also attaching that single frequency code for reference.
import java.nio.ByteBuffer;
import java.util.Scanner;
import javax.sound.sampled.*;
public class Audio {
public static void main(String[] args) throws InterruptedException, LineUnavailableException {
final int SAMPLING_RATE = 44100; // Audio sampling rate
final int SAMPLE_SIZE = 2; // Audio sample size in bytes
Scanner in = new Scanner(System.in);
int time = in.nextInt(); //Time specified by user in seconds
SourceDataLine line;
double fFreq = in.nextInt(); // Frequency of sine wave in hz
//Position through the sine wave as a percentage (i.e. 0 to 1 is 0 to 2*PI)
double fCyclePosition = 0;
//Open up audio output, using 44100hz sampling rate, 16 bit samples, mono, and big
// endian byte ordering
AudioFormat format = new AudioFormat(SAMPLING_RATE, 16, 1, true, true);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line matching " + info + " is not supported.");
throw new LineUnavailableException();
}
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
// Make our buffer size match audio system's buffer
ByteBuffer cBuf = ByteBuffer.allocate(line.getBufferSize());
int ctSamplesTotal = SAMPLING_RATE * time; // Output for roughly user specified time in seconds
//On each pass main loop fills the available free space in the audio buffer
//Main loop creates audio samples for sine wave, runs until we tell the thread to exit
//Each sample is spaced 1/SAMPLING_RATE apart in time
while (ctSamplesTotal > 0) {
double fCycleInc = fFreq / SAMPLING_RATE; // Fraction of cycle between samples
cBuf.clear(); // Discard samples from previous pass
// Figure out how many samples we can add
int ctSamplesThisPass = line.available() / SAMPLE_SIZE;
for (int i = 0; i < ctSamplesThisPass; i++) {
cBuf.putShort((short) (Short.MAX_VALUE * Math.sin(2 * Math.PI * fCyclePosition)));
fCyclePosition += fCycleInc;
if (fCyclePosition > 1) {
fCyclePosition -= 1;
}
}
//Write sine samples to the line buffer. If the audio buffer is full, this will
// block until there is room (we never write more samples than buffer will hold)
line.write(cBuf.array(), 0, cBuf.position());
ctSamplesTotal -= ctSamplesThisPass; // Update total number of samples written
//Wait until the buffer is at least half empty before we add more
while (line.getBufferSize() / 2 < line.available()) {
Thread.sleep(1);
}
}
//Done playing the whole waveform, now wait until the queued samples finish
//playing, then clean up and exit
line.drain();
line.close();
}
}
Your best bet is probably creating Clips as shown in the sample code below.
That said, the MHz range is typically not audible—looks like you have a typo in your question. If it's no typo, you will run into issues with Mr. Nyquist.
Another hint: Nobody uses Hungarian Notation in Java.
import javax.sound.sampled.*;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
public class AlternatingTones {
public static void main(final String[] args) throws LineUnavailableException, InterruptedException {
final Clip clip0 = createOneSecondClip(440f);
final Clip clip1 = createOneSecondClip(16000f);
clip0.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) {
clip1.setFramePosition(0);
clip1.start();
}
});
clip1.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) {
clip0.setFramePosition(0);
clip0.start();
}
});
clip0.start();
// prevent JVM from exiting
Thread.sleep(10000000);
}
private static Clip createOneSecondClip(final float frequency) throws LineUnavailableException {
final Clip clip = AudioSystem.getClip();
final AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100f, 16, 1, 2, 44100, true);
final ByteBuffer buffer = ByteBuffer.allocate(44100 * format.getFrameSize());
final ShortBuffer shortBuffer = buffer.asShortBuffer();
final float cycleInc = frequency / format.getFrameRate();
float cyclePosition = 0f;
while (shortBuffer.hasRemaining()) {
shortBuffer.put((short) (Short.MAX_VALUE * Math.sin(2 * Math.PI * cyclePosition)));
cyclePosition += cycleInc;
if (cyclePosition > 1) {
cyclePosition -= 1;
}
}
clip.open(format, buffer.array(), 0, buffer.capacity());
return clip;
}
}
The method I would use would be to count frames while outputting to a SourceDataLine. When you have written one second's worth of frames, switch frequencies. This will give much better timing accuracy than attempting to fiddle with Clips.
I'm unclear if the code you are showing is something you wrote or copied-and-pasted. If you have a question about how it doesn't work, I'm happy to help if you show what you tried and what errors or exceptions were generated.
When outputting to a SourceDataLine, there will have to be a step where you convert the short value (-32768..+32767) to two bytes as per the 16-bit encoding specified in the audio format you have. I don't see where this is being done in your code. [EDIT: can see where the putShort() method does this, though it only works for BigEndian, not the more common LittleEndian.]
Have you looked over the Java Tutorial
Sound Trail?
Is it possible to detect the audio levels from a playing track using background agent or any other way?
What I'm trying to achieve is listen to the track, get a float and change colour based on the levels of the audio being played.
How would you approach?
You need to detect the decibels level of a sound recorded. Actually, in WP7 (I can't find for WP8, yet!) there is no APIs to get decibel level directly. But I can use microphone to get data to simulate decibel. The code like this:
......
microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferReady);
........
void microphone_BufferReady(object sender, EventArgs e)
{
double sum = 0;
for (var i = 0; i < buffer.Length; i = i + 2)
{
double sample = BitConverter.ToInt16(buffer, i) / 32768.0;
sum += (sample * sample);
}
double rms = Math.Sqrt(sum / buffer.Length);
decibel = 92.8 + 20 * Math.Log10(rms);
}
This is the source http://social.msdn.microsoft.com/Forums/windowsapps/en-US/f04e0629-2609-4542-a141-46166f4cbdeb/how-to-get-the-decibel-with-c
I am trying to generate a tone to the sound card (Frequency: 1950 hz, duration: 40 ms, level: -30 db, right-channel (stereo), on steam 1). Eventually, I would like to play two of these tones (one goes to channel 1 and one goes to channel 2).
Any help or direction is greatly appreciated.
Thanks,
DW
Hi Bjorn, I tried this but I am not getting the what I am expecting as a frequency (plus seems sound is not clean). Any ideas what's wrong?
I greatly appreciate any help.
#define SAMPLE_RATE (44100)
#define TABLE_SIZE (200)
float FREQUENCY = 422;
...
for(int i=0; i<TABLE_SIZE; i++ )
{
data.sine[i] = (float) sin( (double)i * ((2.0 * M_PI)/(double)SAMPLE_RATE) * FREQUENCY );
}
data.left_phase = 0;
data.right_phase = 0;
...
... in callback function ...
for(unsigned long i = 0; i < framesPerBuffer; i++ )
{
// fill output buffer with sin wave
*out++ = data->amp * data->sine[data->left_phase]; // left
*out++ = data->amp * data->sine[data->right_phase]; // right
data->left_phase += 1;
if( data->left_phase >= TABLE_SIZE )
data->left_phase -= TABLE_SIZE;
data->right_phase += 1;
if( data->right_phase >= TABLE_SIZE )
data->right_phase -= TABLE_SIZE;
}
PortAudio has sample code for generating tones, you just need to figure out the frequency. See for example this answer:
[portaudio]Transmit and Detect frequency - Windows
Update:
Rather than trying to store a table of sine data, simply calculate the sine value in the callback using this formula:
amplitude[n] = sin( n * desiredFreq * 2 * pi / samplerate )
so (untested) your code will look something like this:
typedef struct
{
long n;
} MyData;
float FREQUENCY = 422;
static int MyCallback(
const void *inputBuffer,
void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData
)
{
MyData *data = (MyData*)userData;
float *out = (float*)outputBuffer;
(void) timeInfo; /* Prevent unused variable warnings. */
(void) statusFlags;
(void) inputBuffer;
for(unsigned long i = 0; i < framesPerBuffer; i++ )
{
// fill output buffer with sin wave
float v = sin( data->n * FREQUENCY * 2 * PI / (float) SAMPLERATE )
*out++ = v; // left
*out++ = v; // right
}
return paContinue;
}
This code is not without problems: eg. eventually n will "wrap around" and I'm not sure if sin remains accurate and efficient as the input gets larger. Nevertheless it's a good starting point, and if you just need to generate a few seconds of a tone on modern hardware, this is really all you need. If you need something fancier, get this working first, then you can worry about making it more efficient and robust with a LUT.
I've been working for some time with image formats and i know that an image is an array of pixels (24- maybe 32 bits long). The question is: what is the way a sound file is represented? To be honest i'm not even sure what i should be googling for. Also i would be interested how do you use the data, i mean actually playing the sounds in the file. For an image file you have all sorts of abstract devices to draw an image on(Graphics:java,c#, HDC:cpp(win32), etc.) .I hope i have been clear enough.
Here's a dandy overview of how .wav is stored. I found it by typing "wave file format" into google.
http://www.sonicspot.com/guide/wavefiles.html
WAV files can also store compressed audio, but I believe most of the time they are not compressed. But the WAV format is designed as a container for a number of options on how that audio is stored.
Here's a snipped of code that I found at another question here at stackoverflow that I like in C# that builds a WAV-formatted audio MemoryStream and then plays that stream (without saving it to a file, like many other answers rely on). But saving it to a file can easily be added with one line of code if you want it saved to disk, but I would think that most of the time, that'd be undesirable.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
{
var mStrm = new MemoryStream();
BinaryWriter writer = new BinaryWriter(mStrm);
const double TAU = 2 * Math.PI;
int formatChunkSize = 16;
int headerSize = 8;
short formatType = 1;
short tracks = 1;
int samplesPerSecond = 44100;
short bitsPerSample = 16;
short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
int bytesPerSecond = samplesPerSecond * frameSize;
int waveSize = 4;
int samples = (int)((decimal)samplesPerSecond * msDuration / 1000);
int dataChunkSize = samples * frameSize;
int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
// var encoding = new System.Text.UTF8Encoding();
writer.Write(0x46464952); // = encoding.GetBytes("RIFF")
writer.Write(fileSize);
writer.Write(0x45564157); // = encoding.GetBytes("WAVE")
writer.Write(0x20746D66); // = encoding.GetBytes("fmt ")
writer.Write(formatChunkSize);
writer.Write(formatType);
writer.Write(tracks);
writer.Write(samplesPerSecond);
writer.Write(bytesPerSecond);
writer.Write(frameSize);
writer.Write(bitsPerSample);
writer.Write(0x61746164); // = encoding.GetBytes("data")
writer.Write(dataChunkSize);
{
double theta = frequency * TAU / (double)samplesPerSecond;
// 'volume' is UInt16 with range 0 thru Uint16.MaxValue ( = 65 535)
// we need 'amp' to have the range of 0 thru Int16.MaxValue ( = 32 767)
// so we simply set amp = volume / 2
double amp = volume >> 1; // Shifting right by 1 divides by 2
for (int step = 0; step < samples; step++)
{
short s = (short)(amp * Math.Sin(theta * (double)step));
writer.Write(s);
}
}
mStrm.Seek(0, SeekOrigin.Begin);
new System.Media.SoundPlayer(mStrm).Play();
writer.Close();
mStrm.Close();
} // public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
But this code shows a bit of insight into the WAV-format, and it is even code that allows a person to build your own WAV-format in C# source code.