I have a MPU6050 hooked up to a raspberry pi pico, I am trying to read the data using the i2c protocol. But it only gives 0's, I assume this is due to the fact that its in sleep mode because from what I can tell everything is connected as it should be.
`
#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/i2c.h"
//mpu address
const static uint8_t MPU_ADDRESS = 0x68;
static void mpu6050_reset() {
// Two byte reset. First byte register, second byte data
// There are a load more options to set up the device in different ways that could be added here
//uint8_t buffer [] = {(uint8_t)65, (uint8_t)66};
//i2c_read_blocking(i2c_default, MPU_ADDRESS, buffer[0], 8, false);
//i2c_read_blocking(i2c_default, MPU_ADDRESS, buffer[1], 8, false);
//printf("b1: %d b2: %d \n", buffer[0], buffer[1]);
uint8_t buf[] = {0x6B, 0x00};
i2c_write_blocking(i2c_default, MPU_ADDRESS, buf, 1, false);
//i2c_read_blocking(i2c_default, MPU_ADDRESS, buffer[0], 8, false);
//i2c_read_blocking(i2c_default, MPU_ADDRESS, buffer[1], 8, false);
}
static void mpu6050_read_raw(int16_t accel[3], int16_t gyro[3], int16_t *temp) {
// For this particular device, we send the device the register we want to read
// first, then subsequently read from the device. The register is auto incrementing
// so we don't need to keep sending the register we want, just the first.
uint8_t buffer[6];
// Start reading acceleration registers from register 0x3B for 6 bytes
uint8_t val = 0x3B;
i2c_write_blocking(i2c_default, MPU_ADDRESS, &val, 1, true); // true to keep master control of bus
i2c_read_blocking(i2c_default, MPU_ADDRESS, buffer, 6, false);
printf("buffer accel, 1: %d, 2: %d, 3: %d, 4: %d, 5: %d, 6: %d \n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
for (int i = 0; i < 3; i++) {
accel[i] = (buffer[i * 2] << 8 | buffer[(i * 2) + 1]);
}
// Now gyro data from reg 0x43 for 6 bytes
// The register is auto incrementing on each read
val = 0x43;
i2c_write_blocking(i2c_default, MPU_ADDRESS, &val, 1, true);
i2c_read_blocking(i2c_default, MPU_ADDRESS, buffer, 6, false); // False - finished with bus
for (int i = 0; i < 3; i++) {
gyro[i] = (buffer[i * 2] << 8 | buffer[(i * 2) + 1]);;
}
printf("buffer gyro, 1: %d, 2: %d, 3: %d, 4: %d, 5: %d, 6: %d \n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
val = 0x41;
i2c_write_blocking(i2c_default, MPU_ADDRESS, &val, 1, true);
i2c_read_blocking(i2c_default, MPU_ADDRESS, buffer, 2, false); // False - finished with bus
*temp = buffer[0] << 8 | buffer[1];
}
int main() {
//check that pico is powered and running
const uint LED = PICO_DEFAULT_LED_PIN;
gpio_init(LED);
gpio_set_dir(LED, GPIO_OUT);
gpio_put(LED, 1);
//check that pico can use serial output
stdio_init_all();
printf("hello world \n");
//setup i2c buffer address stuff
uint8_t MPU_ACCELRATION_BUFFER = 0x3B;
uint8_t MPU_GRYOSCOPE_BUFFER = 0x43;
//turn on MPU power
const uint MPU_POWER = 1;
gpio_init(MPU_POWER);
gpio_set_dir(MPU_POWER, GPIO_OUT);
gpio_put(MPU_POWER, 1);
i2c_init(i2c_default, 400 * 1000);
gpio_set_function(PICO_DEFAULT_I2C_SDA_PIN, GPIO_FUNC_I2C);
gpio_set_function(PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C);
gpio_pull_up(PICO_DEFAULT_I2C_SDA_PIN);
gpio_pull_up(PICO_DEFAULT_I2C_SCL_PIN);
// Make the I2C pins available to picotool
bi_decl(bi_2pins_with_func(PICO_DEFAULT_I2C_SDA_PIN, PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C));
//while (1){
mpu6050_reset();
//}
int16_t acceleration[3], gyro[3], temp;
while (1) {
mpu6050_reset();
mpu6050_read_raw(acceleration, gyro, &temp);
// These are the raw numbers from the chip, so will need tweaking to be really useful.
// See the datasheet for more information
printf("Acc. X = %d, Y = %d, Z = %d\n", acceleration[0], acceleration[1], acceleration[2]);
printf("Gyro. X = %d, Y = %d, Z = %d\n", gyro[0], gyro[1], gyro[2]);
printf("Temp. = %f\n", (temp / 340.0) + 36.53);
sleep_ms(100);
}
return 0;
}
`
This is the code, using the raspberry pi c/cpp sdk. A large chunk of it is simply the example for the mpu6050 which all seems to be valid, and there is code included meant to wake up the mpu6050. So are there any other methods of waking the MPU6050 up or does the issue appear to be something else within the code?
Related
The rm3100 is working with Arduino Leonardo. I am trying to make it work with esp32.
I am able to write to the registers of an rm3100 and read them. I tried to write to the register and then read its value - it works as expected.
But the measurement registers not changing and the senior bit of the status register (0x34) is always 0. DRDY line stays low.
I tried continuous mode (wrote 0x71 to the register 0x01) and single measurement (wrote 0x70 to the register 0x00).
uint8_t data[1];
write_i2c_register(0x33, 0x8f); // wrote to the test register 0x33
usleep(1000000);
read_i2c_registers(0x33, data, 1);
printf("Test register is %02x\n", data[0]); // printing 0x8f in 0x33 register
write_i2c_register(0x00, 0x70); // initialize single measurement
usleep(1000000);
read_i2c_registers(0x34, data, 1);
printf("Status register is %02x\n", data[0]); // printing 0x00 in 0x34 register
write_i2c_register(0x01, 0x71); // initialize continuous measurement
usleep(1000000);
read_i2c_registers(0x34, data, 1);
printf("Status register is %02x\n", data[0]); // printing 0x00 in 0x34 register
The following points look suspicious:
According to the datasheet https://www.pnicorp.com/wp-content/uploads/RM3100-RM2100-Sensor-Suite-User-Manual-R09-1.pdf – I need to add 0x80 to the register address when reading.
But it doesn’t work in my case – when I add 0x80 – I am getting 0. But when I read without adding – I am getting correct results.
std::vector<int> regs = {0, 1, 4, 5, 6, 7, 8, 9, 11, 36, 37, 38, 39, 40,
41, 42, 43, 44, 51, 52, 53, 54};
for (auto i: regs)
{
read_i2c_registers(i, data, 1); // when I read without adding 0x80
printf("%02x=%02x ", i, data[0]); // I am getting reasonable values
}
printf("\n");
for (auto i: regs)
{
read_i2c_registers(i + 0x80, data, 1); // when I add 0x80 to the reg address
printf("%02x=%02x ", i, data[0]); // I am getting zeros
}
printf("\n");
According to the datasheet – I need to send “stop” when after sending the register address when reading.
It doesn’t work – I am getting timeout error.
void read_i2c_registers(uint8_t reg, uint8_t* data, const uint8_t bytes){
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
ESP_ERROR_CHECK(i2c_master_start(cmd));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (I2C_ADDRESS_GEO << 1) | I2C_MASTER_WRITE, 1));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, reg, 1));
// ESP_ERROR_CHECK(i2c_master_stop(cmd)); // <-- timeout when uncommented
ESP_ERROR_CHECK(i2c_master_start(cmd));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (I2C_ADDRESS_GEO << 1) | I2C_MASTER_READ, 1));
if (bytes > 1)
ESP_ERROR_CHECK(i2c_master_read(cmd, data, bytes - 1, (i2c_ack_type_t) 0));
ESP_ERROR_CHECK(i2c_master_read_byte(cmd, data + bytes - 1, (i2c_ack_type_t) 1));
ESP_ERROR_CHECK(i2c_master_stop(cmd));
auto err = i2c_master_cmd_begin(I2C_NUM_0, cmd, 1000/portTICK_PERIOD_MS);
i2c_cmd_link_delete(cmd);
if (err != ESP_OK)
{
std::cout << "err=" << int(err) << "\n";
}
}
void write_i2c_register(const uint8_t reg, const uint8_t data){
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
ESP_ERROR_CHECK(i2c_master_start(cmd));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (I2C_ADDRESS_GEO << 1) | I2C_MASTER_WRITE, 1));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, reg, 1));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, data, 1));
ESP_ERROR_CHECK(i2c_master_stop(cmd));
esp_err_t err;
do err = i2c_master_cmd_begin(I2C_NUM_0, cmd, 1000/portTICK_PERIOD_MS);
while (err != ESP_OK);
i2c_cmd_link_delete(cmd);
}
As far as I understand read_i2c_registers should call i2c_master_cmd_begin twice (separately for write part and read part).
I adjusted the code and it works now in continuous mode:
void read_i2c_registers(uint8_t reg, uint8_t* data, const uint8_t bytes){
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
ESP_ERROR_CHECK(i2c_master_start(cmd));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (I2C_ADDRESS_GEO << 1) | I2C_MASTER_WRITE, 1));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, reg, 1));
ESP_ERROR_CHECK(i2c_master_stop(cmd)); // uncommented
ESP_ERROR_CHECK(i2c_master_cmd_begin(I2C_NUM_0, cmd, 1/portTICK_PERIOD_MS)); // line added
i2c_cmd_link_delete(cmd); // line added
cmd = i2c_cmd_link_create(); // line added
ESP_ERROR_CHECK(i2c_master_start(cmd));
ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (I2C_ADDRESS_GEO << 1) | I2C_MASTER_READ, 1));
if (bytes > 1)
ESP_ERROR_CHECK(i2c_master_read(cmd, data, bytes - 1, (i2c_ack_type_t) 0));
ESP_ERROR_CHECK(i2c_master_read_byte(cmd, data + bytes - 1, (i2c_ack_type_t) 1));
ESP_ERROR_CHECK(i2c_master_stop(cmd));
ESP_ERROR_CHECK(i2c_master_cmd_begin(I2C_NUM_0, cmd, 1/portTICK_PERIOD_MS));
i2c_cmd_link_delete(cmd);
}
I am trying to record audio from an INMP441 which is connected to a ESP32 but returning the buffer containing the bytes the microphone read always leads to something which is NULL.
The code for setting up i2s and the microphone is this:
// i2s config
const i2s_config_t i2s_config = {
.mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX), // receive
.sample_rate = SAMPLE_RATE, // 44100 (44,1KHz)
.bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT, // 32 bits per sample
.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, // use right channel
.communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // interrupt level 1
.dma_buf_count = 64, // number of buffers
.dma_buf_len = SAMPLES_PER_BUFFER}; // 512
// pin config
const i2s_pin_config_t pin_config = {
.bck_io_num = gpio_sck, // serial clock, sck (gpio 33)
.ws_io_num = gpio_ws, // word select, ws (gpio 32)
.data_out_num = I2S_PIN_NO_CHANGE, // only used for speakers
.data_in_num = gpio_sd // serial data, sd (gpio 34)
};
// config i2s driver and pins
// fct must be called before any read/write
esp_err_t err = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
if (err != ESP_OK)
{
Serial.printf("Failed installing the driver: %d\n", err);
}
err = i2s_set_pin(I2S_PORT, &pin_config);
if (err != ESP_OK)
{
Serial.printf("Failed setting pin: %d\n", err);
}
Serial.println("I2S driver installed! :-)");
Setting up the i2s stuff is no problem at all. The tricky part for me is reading from the i2s:
// 44KHz * Byte per sample * time in seconds = total size in bytes
const size_t recordSize = (SAMPLE_RATE * I2S_BITS_PER_SAMPLE_32BIT / 8) * recordTime; //recordTime = 5s
// size in bytes
size_t totalReadSize = 0;
// 32 bits per sample set in config * 1024 samples per buffers = total bits per buffer
char *samples = (char *)calloc(totalBitsPerBuffer, sizeof(char));
// number of bytes read
size_t bytesRead;
Serial.println("Start recording...");
// read until wanted size is reached
while (totalReadSize < recordSize)
{
// read to buffer
esp_err_t err = i2s_read(I2S_PORT, (void *)samples, totalBitsPerBuffer, &bytesRead, portMAX_DELAY);
// check if error occurd, if so stop recording
if (err != ESP_OK)
{
Serial.println("Error while recording!");
break;
}
// check if bytes read works → yes
/*
for (int i = 0; i < bytesRead; i++)
{
uint8_t sample = (uint8_t) samples[i];
Serial.print(sample);
} */
// add read size to total read size
totalReadSize += bytesRead;
// Serial.printf("Currently recorded %d%% \n", totalReadSize * 100 / recordSize);
}
// convert bytes to mb
double_t totalReadSizeMB = (double_t)totalReadSize / 1e+6;
Serial.printf("Total read size: %fMb\n", totalReadSizeMB);
Serial.println("Samples deref");
Serial.println(*samples);
Serial.println("Samples");
Serial.println(samples);
return samples;
Using this code leads to the following output:
I2S driver installed! :-)
Start recording...
Total read size: 0.884736Mb
Samples deref
␀
Samples
When I uncomment the part where I iterate over the bytes read part I get something like this:
200224231255255224210022418725525522493000902552550238002241392542552241520020425225508050021624525501286700194120022461104022421711102242271030018010402242510000188970224141930022291022410185022487830021679001127500967200666902241776600246610224895902244757022418353002224802242274302249741022419339009435001223102242432602243322022412120001241402245911022418580084402248325525522461252255044249255224312452552242212372552241272352550342302552241212262552242112212550252216255014621325501682092550112205255224161202255224237198255224235194255224231922552248518725501141832550421812552241951762550144172255018168255034164255224173157255018215525522455152255028148255021014425505214025522487137255014613225522412112825502361252550180120255018011725522451172550252113255224133111255061082550248105255224891042552249910125522439972550138942552242279225503287255224101832552242478125522410178255224231732552244970255224336525501766225501426125502325625522424553255224109492550186[...]
This shows that the microphone is able to record, but I cant return the actual value of the buffer.
While programming this code I looked up at the official doku and some code which seems to work elsewhere.
I am also new to C++ and am not used to work with pointers.
Does anyone know what the problem could be?
I have an Arduino Nano piggybacked on a ENC28j60 ethernet module. I have eight (8) DHT22 sensors (named A, B, C ... H ) and i want to write their temperature and humidity data to Pushingbox.
The program is working great with ONE sensor. So that's good. However when i un-remark (i.e. take out the //'s) for anything more than one sensor, yes even for ONE other sensor, it won't write anything at all.
The arduino IDE complier says:
Sketch uses 23824 bytes (77%) of program storage space. Maximum is 30720 bytes.
Global variables use 1870 bytes (91%) of dynamic memory, leaving 178 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.
FYI, If i un-remark just one other sensor it goes up +2% to 93% of dynamic memory and stops working. So i'm assuming its a memory problem. i have already removed all floats (and made integers *10 to keep one decimal place of accuracy), i need 8 instances of DHT so considered reducing the library size but the .h seems tiny and pretty lean already (within the .h file it even boasts: Very low memory footprint - Very small code. so i havent modified this or the .cpp.
The overall code i have written is not large, maybe there are some in-efficiencies there, but i can't see that it is going to make anything near the amount of memory saving needed for the next 7 sensors.
The full arduino code (written for all 8 sensors, with 'ghosted' bits for 4 sensors and in use only working for one sensor) is below:
#include "DHTesp.h"
//#include <SPI.h>
#include <UIPEthernet.h>
DHTesp dhtA;
//DHTesp dhtB;
//DHTesp dhtC;
//DHTesp dhtD;
//DHTesp dhtE;
//DHTesp dhtF;
//DHTesp dhtG;
//DHTesp dhtH;
const int ledPin = LED_BUILTIN;
int ledState = LOW;
int interval = 10; // this is the number of seconds between reads (120=2mins)
int numReads = 5; // Number of reads between posting to google docs.
int multFact = 10; // multiplication factor 10 = 1 dec. place 100 = 2 dec places
byte mac[] = {0xBE, 0xEF, 0xDE, 0xAD, 0xDE, 0xAD }; //Ethernet shield MAC. Andy's working {0xBE, 0xEF, 0xDE, 0xAD, 0xDE, 0xAD}
byte ip[] = { 192,168,1,12 }; // Arduino device IP address
char devid [] = "vCE3D036xxxxxxxx"; // Gsheets device ID from Pushingbox ('x's for privacy:)
char server[] = "api.pushingbox.com";
EthernetClient client;
void setup()
{
Serial.begin(9600);
Serial.println ("RESTART");
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Trying to connect...");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
while(true);
}
else{
Serial.print("OK, connected. Ethernet ready. ");
// print the Ethernet board/shield's IP address:
Serial.print("IP address: ");
Serial.println(Ethernet.localIP());
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println();
//Serial.println("A-Stat\t\tA-Temp (C)\tA-humdid%\tA-HeatI (C)\tB-Stat\t\tB-Temp (C)\tA-humdid%\tB-HeatI (C)");
Serial.println("\t\t\t\tt-A\th-A\tt-B\th-B\tt-C\th-C\tt-D\th-D\tt-E\th-E\tt-F\th-F\tt-G\th-G\tt-H\th-H");
//hey dB for some reason the Ethernet sheild uses pin D2 :( and pins 10,11,12,13
// https://arduinodiy.wordpress.com/2013/04/07/connect-an-enc28j60-ethernet-module-to-an-arduino/
// assign data pins
dhtA.setup(3);
//dhtB.setup(4);
//dhtC.setup(5);
//dhtD.setup(6);
//dhtE.setup(7);
//dhtF.setup(8);
//dhtG.setup(9);
//dhtH.setup(10); //watchout! i think Ethernet uses this pin too?
pinMode(ledPin, OUTPUT);
//end of void setup
}
void loop()
{
int Ahumid = 0; int Atemp = 0;
int Bhumid = 0; int Btemp = 0;
int Chumid = 0; int Ctemp = 0;
int Dhumid = 0; int Dtemp = 0;
//int Ehumid = 0; int Etemp = 0;
//int Fhumid = 0; int Ftemp = 0;
//int Ghumid = 0; int Gtemp = 0;
//int Hhumid = 0; int Htemp = 0;
int j=0;
for (j = 1; j <= numReads ; j++ ) {
int p = 0;
for (p=1; p <= interval ; p++) {
delay (1000);
// swap the led state
if (ledState == LOW) { ledState = HIGH; } else { ledState = LOW; }
Serial.print (p); //show the seconds passing
Serial.print (",");
digitalWrite(ledPin, ledState);
}
Serial.print (" Reading");
Atemp += dhtA.getTemperature()*multFact; Ahumid += dhtA.getHumidity()*multFact;
//Btemp += dhtB.getTemperature()*multFact; Bhumid += dhtB.getHumidity()*multFact;
//Ctemp += dhtC.getTemperature()*multFact; Chumid += dhtC.getHumidity()*multFact;
//Dtemp += dhtD.getTemperature()*multFact; Dhumid += dhtD.getHumidity()*multFact;
// print the readings
//Serial.print(dhtA.getStatusString());
Serial.print("\t"); Serial.print(Atemp);
Serial.print("\t"); Serial.print(Ahumid);
Serial.print("\t"); Serial.print(Btemp);
Serial.print("\t"); Serial.print(Bhumid);
Serial.print("\t"); Serial.print(Ctemp);
Serial.print("\t"); Serial.print(Chumid);
Serial.print("\t"); Serial.print(Dtemp);
Serial.print("\t"); Serial.print(Dhumid);
Serial.println();
// and so here endeth 'j', the number of reads
}
Serial.print ("Avg...");
Atemp = Atemp/numReads; Ahumid = Ahumid/numReads;
Btemp = Btemp/numReads; Bhumid = Bhumid/numReads;
Ctemp = Ctemp/numReads; Chumid = Chumid/numReads;
Dtemp = Dtemp/numReads; Dhumid = Dhumid/numReads;
// print the averages so we can see what it is going to send
Serial.print("\t\t\t");
Serial.print("\t"); Serial.print(Atemp); Serial.print("\t"); Serial.print(Ahumid);
Serial.print("\t"); Serial.print(Btemp); Serial.print("\t"); Serial.print(Bhumid);
Serial.print("\t"); Serial.print(Ctemp); Serial.print("\t"); Serial.print(Chumid);
Serial.print("\t"); Serial.print(Dtemp); Serial.print("\t"); Serial.print(Dhumid);
Serial.println();
Serial.print ("Prep for upload... ");
if (client.connect(server, 80))
{
Serial.print("Connected OK ... writing...");
client.print("GET /pushingbox?devid=");
client.print(devid);
client.print("&tempA="); client.print(Atemp);
client.print("&tempB="); client.print(Btemp);
client.print("&tempC="); client.print(Ctemp);
client.print("&tempD="); client.print(Dtemp);
client.print("&tempE=29&tempF=39&tempG=49&tempH=59");
//now humidity too
client.print("&humidA="); client.print(Ahumid);
client.print("&humidB="); client.print(Bhumid);
client.print("&humidC="); client.print(Chumid);
client.print("&humidD="); client.print(Dhumid);
client.print("&humidE=26&humidF=27&humidG=28&humidH=29");
client.print("&submit=Submit");
client.println(" HTTP/1.1");
client.println("Host: api.pushingbox.com");
client.println("Connection: close");
client.println();
Serial.println("written OK. & connection closed.");
Serial.println(); //Serial.println();
delay(1000); // maybe take this out to keep time stable?
client.stop();
}
else {
Serial.println("** NO CONNEX **"); Serial.println();
}
//here endeth void loop
}
Extra info (that i dont think is relevant, but maybe): IDE compiler also reports:
WARNING: library DHT_sensor_library_for_ESP32 claims to run on [esp32] architecture(s) and may be incompatible with your current board which runs on [avr] architecture(s).
Use the F macro for double-quoted string literal prints. Instead of this:
Serial.println ("RESTART");
or
client.print("GET /pushingbox?devid=");
... do this:
Serial.println ( F("RESTART") );
or
client.print( F("GET /pushingbox?devid=") );
This will easily save a bunch o' RAM.
I would also suggest using the single quoted literal for single characters, not the double quote:
Serial.print( '\t' );
I am currently trying to learn audio programming. My goal is to open a wav file, extract everything and play the samples with RtAudio.
I made a WaveLoader class which let's me extract the samples and meta data. I used this guide to do that and I checked that everything is correct with 010 editor. Here is a snapshot of 010 editor showing the structure and data.
And this is how i store the raw samples inside WaveLoader class:
data = new short[wave_data.payloadSize]; // - Allocates memory size of chunk size
if (!fread(data, 1, wave_data.payloadSize, sound_file))
{
throw ("Could not read wav data");
}
If i print out each sample I get : 1, -3, 4, -5 ... which seems ok.
The problem is that I am not sure how I can play them. This is what I've done:
/*
* Using PortAudio to play samples
*/
bool Player::Play()
{
ShowDevices();
rt.showWarnings(true);
RtAudio::StreamParameters oParameters; //, iParameters;
oParameters.deviceId = rt.getDefaultOutputDevice();
oParameters.firstChannel = 0;
oParameters.nChannels = mAudio.channels;
//iParameters.deviceId = rt.getDefaultInputDevice();
//iParameters.nChannels = 2;
unsigned int sampleRate = mAudio.sampleRate;
// Use a buffer of 512, we need to feed callback with 512 bytes everytime!
unsigned int nBufferFrames = 512;
RtAudio::StreamOptions options;
options.flags = RTAUDIO_SCHEDULE_REALTIME;
options.flags = RTAUDIO_NONINTERLEAVED;
//¶meters, NULL, RTAUDIO_FLOAT64,sampleRate, &bufferFrames, &mCallback, (void *)&rawData
try {
rt.openStream(&oParameters, NULL, RTAUDIO_SINT16, sampleRate, &nBufferFrames, &mCallback, (void*) &mAudio);
rt.startStream();
}
catch (RtAudioError& e) {
std::cout << e.getMessage() << std::endl;
return false;
}
return true;
}
/*
* RtAudio Callback
*
*/
int mCallback(void * outputBuffer, void * inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void * userData)
{
unsigned int i = 0;
short *out = static_cast<short*>(outputBuffer);
auto *data = static_cast<Player::AUDIO_DATA*>(userData);
// if i is more than our data size, we are done!
if (i > data->dataSize) return 1;
// First time callback is called data->ptr is 0, this means that the offset is 0
// Second time data->ptr is 1, this means offset = nBufferFrames (512) * 1 = 512
unsigned int offset = nBufferFrames * data->ptr++;
printf("Offset: %i\n", offset);
// First time callback is called offset is 0, we are starting from 0 and looping nBufferFrames (512) times, this gives us 512 bytes
// Second time, the offset is 1, we are starting from 512 bytes and looping to 512 + 512 = 1024
for (i = offset; i < offset + nBufferFrames; ++i)
{
short sample = data->rawData[i]; // Get raw sample from our struct
*out++ = sample; // Pass to output buffer for playback
printf("Current sample value: %i\n", sample); // this is showing 1, -3, 4, -5 check 010 editor
}
printf("Current time: %f\n", streamTime);
return 0;
}
Inside callback function, when I print out sample values I get exactly like 010 editor? Why isnt rtaudio playing them. What is wrong here? Do I need to normalize sample values to between -1 and 1?
Edit:
The wav file I am trying to play:
Chunksize: 16
Format: 1
Channel: 1
SampleRate: 48000
ByteRate: 96000
BlockAlign: 2
BitPerSample: 16
Size of raw samples total: 2217044 bytes
For some reason it works when I pass input parameters to the openStream()
RtAudio::StreamParameters oParameters, iParameters;
oParameters.deviceId = rt.getDefaultOutputDevice();
oParameters.firstChannel = 0;
//oParameters.nChannels = mAudio.channels;
oParameters.nChannels = mAudio.channels;
iParameters.deviceId = rt.getDefaultInputDevice();
iParameters.nChannels = 1;
unsigned int sampleRate = mAudio.sampleRate;
// Use a buffer of 512, we need to feed callback with 512 bytes everytime!
unsigned int nBufferFrames = 512;
RtAudio::StreamOptions options;
options.flags = RTAUDIO_SCHEDULE_REALTIME;
options.flags = RTAUDIO_NONINTERLEAVED;
//¶meters, NULL, RTAUDIO_FLOAT64,sampleRate, &bufferFrames, &mCallback, (void *)&rawData
try {
rt.openStream(&oParameters, &iParameters, RTAUDIO_SINT16, sampleRate, &nBufferFrames, &mCallback, (void*) &mAudio);
rt.startStream();
}
catch (RtAudioError& e) {
std::cout << e.getMessage() << std::endl;
return false;
}
return true;
It was so random when I was trying to playback my mic. I left input parameters and my wav file was suddenly playing. Is this is a bug?
Im trying to write a programm in c++ to let my computer communicate with a trinamic steprockerboard.
They already provided an example file, to get you on the way. This works perfect, but is really simplistic.
Now I want to read the results from the usb device, and they made a function for that:
//Read the result that is returned by the module
//Parameters: Handle: handle of the serial port, as returned by OpenRS232
//Address: pointer to variable to hold the reply address returned by the module
// Status: pointer to variable to hold the status returned by the module (100 means okay)
//Value: pointer to variable to hold the value returned by the module
prototype:
UCHAR GetResult(HANDLE Handle, UCHAR *Address, UCHAR *Status, int *Value)
Now I wrote the following:
UCHAR* adr;
UCHAR* stat;
int* val;
SendCmd(RS232Handle, 1, TMCL_MVP, 0, 0, -3200); // move to next position
SendCmd(RS232Handle,1, TMCL_GAP, 8, 0, 0); // tell motor to look if position is reached
GetResult(RS232Handle,adr,stat,val); //ask for the result, value must give a 1 if so
printf("results from USB device: adr=%d, stat=%d, val=%d\n", adr, stat, val);
But when I run the program, and try this option, the program chrashes.
Has anybody got an idea what might cause the problem? (the code I supplied is only a part of my program, the whole code can be find below.
It is not my intention that you read the whole code, the problem should be above, but only for who is interested I also put the rest down here)
// TMCLTest.cpp : Show how to communicate with a TMCM module in TMCL
//
#include "stdafx.h"
#include <iostream>
//Opcodes of all TMCL commands that can be used in direct mode
#define TMCL_ROR 1
#define TMCL_ROL 2
#define TMCL_MST 3
#define TMCL_MVP 4
#define TMCL_SAP 5
#define TMCL_GAP 6
#define TMCL_STAP 7
enter code here#define TMCL_RSAP 8
enter code here#define TMCL_SGP 9
#define TMCL_GGP 10
#define TMCL_STGP 11
#define TMCL_RSGP 12
#define TMCL_RFS 13
#define TMCL_SIO 14
#define TMCL_GIO 15
#define TMCL_SCO 30
#define TMCL_GCO 31
#define TMCL_CCO 32
//Opcodes of TMCL control functions (to be used to run or abort a TMCL program in the module)
#define TMCL_APPL_STOP 128
#define TMCL_APPL_RUN 129
#define TMCL_APPL_RESET 131
//Options for MVP commandds
#define MVP_ABS 0
#define MVP_REL 1
#define MVP_COORD 2
//Options for RFS command
#define RFS_START 0
#define RFS_STOP 1
#define RFS_STATUS 2
#define FALSE 0
#define TRUE 1
//Result codes for GetResult
#define TMCL_RESULT_OK 0
#define TMCL_RESULT_NOT_READY 1
#define TMCL_RESULT_CHECKSUM_ERROR 2
//Open serial interface
//Usage: ComHandle=OpenRS232("COM1", CBR_9600)
HANDLE OpenRS232(const char* ComName, DWORD BaudRate)
{
HANDLE ComHandle;
DCB CommDCB;
COMMTIMEOUTS CommTimeouts;
ComHandle=CreateFile(ComName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(GetLastError()!=ERROR_SUCCESS) return INVALID_HANDLE_VALUE;
else
{
GetCommState(ComHandle, &CommDCB);
CommDCB.BaudRate=BaudRate;
CommDCB.Parity=NOPARITY;
CommDCB.StopBits=ONESTOPBIT;
CommDCB.ByteSize=8;
CommDCB.fBinary=1; //Binary Mode only
CommDCB.fParity=0;
CommDCB.fOutxCtsFlow=0;
CommDCB.fOutxDsrFlow=0;
CommDCB.fDtrControl=0;
CommDCB.fDsrSensitivity=0;
CommDCB.fTXContinueOnXoff=0;
CommDCB.fOutX=0;
CommDCB.fInX=0;
CommDCB.fErrorChar=0;
CommDCB.fNull=0;
CommDCB.fRtsControl=RTS_CONTROL_TOGGLE;
CommDCB.fAbortOnError=0;
SetCommState(ComHandle, &CommDCB);
//Set buffer size
SetupComm(ComHandle, 100, 100);
//Set up timeout values (very important, as otherwise the program will be very slow)
GetCommTimeouts(ComHandle, &CommTimeouts);
CommTimeouts.ReadIntervalTimeout=MAXDWORD;
CommTimeouts.ReadTotalTimeoutMultiplier=0;
CommTimeouts.ReadTotalTimeoutConstant=0;
SetCommTimeouts(ComHandle, &CommTimeouts);
return ComHandle;
}
}
//Close the serial port
//Usage: CloseRS232(ComHandle);
void CloseRS232(HANDLE Handle)
{
CloseHandle(Handle);
}
//Send a binary TMCL command
//e.g. SendCmd(ComHandle, 1, TMCL_MVP, MVP_ABS, 1, 50000); will be MVP ABS, 1, 50000 for module with address 1
//Parameters: Handle: Handle of the serial port (returned by OpenRS232).
// Address: address of the module (factory default is 1).
// Command: the TMCL command (see the constants at the begiining of this file)
// Type: the "Type" parameter of the TMCL command (set to 0 if unused)
// Motor: the motor number (set to 0 if unused)
// Value: the "Value" parameter (depending on the command, set to 0 if unused)
void SendCmd(HANDLE Handle, UCHAR Address, UCHAR Command, UCHAR Type, UCHAR Motor, INT Value)
{
UCHAR TxBuffer[9];
DWORD BytesWritten;
int i;
TxBuffer[0]=Address;
TxBuffer[1]=Command;
TxBuffer[2]=Type;
TxBuffer[3]=Motor;
TxBuffer[4]=Value >> 24;
TxBuffer[5]=Value >> 16;
TxBuffer[6]=Value >> 8;
TxBuffer[7]=Value & 0xff;
TxBuffer[8]=0;
for(i=0; i<8; i++)
TxBuffer[8]+=TxBuffer[i];
//Send the datagram
WriteFile(Handle, TxBuffer, 9, &BytesWritten, NULL);
}
//Read the result that is returned by the module
//Parameters: Handle: handle of the serial port, as returned by OpenRS232
// Address: pointer to variable to hold the reply address returned by the module
// Status: pointer to variable to hold the status returned by the module (100 means okay)
// Value: pointer to variable to hold the value returned by the module
//Return value: TMCL_RESULT_OK: result has been read without errors
// TMCL_RESULT_NOT_READY: not enough bytes read so far (try again)
// TMCL_RESULT_CHECKSUM_ERROR: checksum of reply packet wrong
UCHAR GetResult(HANDLE Handle, UCHAR *Address, UCHAR *Status, int *Value)
{
UCHAR RxBuffer[9], Checksum;
DWORD Errors, BytesRead;
COMSTAT ComStat;
int i;
//Check if enough bytes can be read
ClearCommError(Handle, &Errors, &ComStat);
if(ComStat.cbInQue>8)
{
//Receive
ReadFile(Handle, RxBuffer, 9, &BytesRead, NULL);
Checksum=0;
for(i=0; i<8; i++)
Checksum+=RxBuffer[i];
if(Checksum!=RxBuffer[8]) return TMCL_RESULT_CHECKSUM_ERROR;
*Address=RxBuffer[0];
*Status=RxBuffer[2];
*Value=(RxBuffer[4] << 24) | (RxBuffer[5] << 16) | (RxBuffer[6] << 8) | RxBuffer[7];
} else return TMCL_RESULT_NOT_READY;
return TMCL_RESULT_OK;
}
int main(int argc, char* argv[])
{
int i;
int Type, Motor, Velocity, Position,ref1;
UCHAR Address, Status;
int Value, Timeout;
HANDLE RS232Handle;
RS232Handle=OpenRS232("COM3", 9600);
// set parameters
SendCmd(RS232Handle, 1, TMCL_SAP, 140, 0, 5); //SAP 140, 0, 5 // set microsteps to 32 (32 additional steps per step of 1.8 degr.)
//SAP 4, 0, 500 //set max vel.
//SAP 5, 0, 100 //set max acc.
//SAP 6, 0, 255 //set abs. max current to 2.8 ampere
//SAP 7, 0, 50 //set standby current ((50/250)*2.8A)
printf("VPI Test Setup\n \n" );
do
{
printf("1 - Rotate clockwise (10 rotations)\n");
printf("2 - Rotate counter-clockwise (10 rotations)\n");
printf("3 - Stop motor\n");
printf("4 - Start test (First 100 rotations clockwise, \n then 100 rotations counter clockwise)\n");
printf("\n99 - End\n");
scanf("%d", &i);
switch(i)
{
case 1:
SendCmd(RS232Handle, 1, TMCL_MVP, 0, 0, 32000); //ABS(4th parameter) = 0
break;
case 2:
SendCmd(RS232Handle, 1, TMCL_MVP, 0, 0, -32000); //ABS(4th parameter) = 0
break;
case 3:
SendCmd(RS232Handle, 1, TMCL_MST, 0, 0, 0);
break;
case 4:
//SendCmd(RS232Handle, 1, TMCL_RFS,0,0,0);
printf("Test started \n" );
//UCHAR done;
UCHAR* adr;
UCHAR* stat;
int* val;
//SendCmd(RS232Handle, 1, TMCL_SAP, 193, 1, 2); //SAP 193,1,2
SendCmd(RS232Handle, 1, TMCL_MVP, 0, 0, -3200); //ABS(4th parameter) = 0
SendCmd(RS232Handle,1, TMCL_GAP, 8, 0, 0);
GetResult(RS232Handle,adr,stat,val);
printf("results from USB device: adr=%d, stat=%d, val=%d\n", adr, stat, val);
//CHAR GetResult(HANDLE Handle, UCHAR *Address, UCHAR *Status, int *Value)
// if(done != 2)
// {
// printf("rotation backwards started \n");
// SendCmd(RS232Handle, 1, TMCL_MVP, 0, 0, 3200);
// }
// }
break;
}
SendCmd(RS232Handle, 1, TMCL_ROL, 0, Motor, Velocity);
SendCmd(RS232Handle, 1, TMCL_ROL, 0, Motor, Velocity);
if(i==1 || i==2 || i==3 || i==4)
{
Address=0;
Status=0;
Value=0;
Timeout=GetTickCount();
while(GetResult(RS232Handle, &Address, &Status, &Value) ==TMCL_RESULT_NOT_READY && abs(GetTickCount()-Timeout)<1000);
printf("Result: Address=%d, Status=%d, Value=%d\n", Address, Status, Value);
}
}
while(i!=99);
CloseRS232(RS232Handle);
return 0;
}
Address, Status and Value should point to valid variables. So, your code should look something like:
UCHAR adr;
UCHAR stat;
int val;
GetResult(RS232Handle,&adr,&stat,&val);
What is happening now is that your variables (adr, stat and val) are not initialized, so, they point to random locations in memory. When you pass these variables to GetResult, it tries to write to those random locations.