ESP8266Audio with multiple .wav file encoded in hex - c

I'm working on a script that will play multiple.wav encoded files in the ESP8266 using the ESP8266Audio library. I need to play multiple audio streams with different time stamps; that's why I am asking for it. Please do note that the hardware is ESP32-8266 and TIP 120 transistor.
#include <Arduino.h>
#include "AudioFileSourcePROGMEM.h"
#include "AudioGeneratorWAV.h"
#include "AudioOutputI2SNoDAC.h"
#include <ESP8266WiFi.h>
#include <SPI.h>
#include <SD.h>
// VIOLA sample taken from https://ccrma.stanford.edu/~jos/pasp/Sound_Examples.html
#include "viola.h"
#include "viola02.h"
AudioGeneratorWAV *wav;
AudioFileSourcePROGMEM *file;
AudioOutputI2SNoDAC *out;
void setup()
{
Serial.begin(115200);
delay(1000);
Serial.printf("WAV start\n");
audioLogger = &Serial;
out = new AudioOutputI2SNoDAC();
// out02 = new AudioOutputI2SNoDAC();
// out -> SetGain(0.08);
}
void Play(const void *data, uint32_t len) {
file = new AudioFileSourcePROGMEM( data, len );
wav = new AudioGeneratorWAV();
wav->begin(file, out);
delay(3000);
while (true) {
if (wav->isRunning()) {
if (!wav->loop()) wav->stop();
} else {
Serial.printf("WAV done\n");
delay(1000);
break;
}
}
}
void loop()
{
Play(viola,sizeof(viola));
Play(viola02,sizeof(viola02));
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/yIKml.png

Related

Array Data Reading Failed

I am reading the data from a "Torque Wrench" using "USB Host Shield2.0" and Arduino UNO. I am receiving correct data from my "Torque Wrench" Data is receiving in a array.
But when I started reading data after "for" loop inside Void loop() I am receiving incorrect data. I attached Both output pictures correct and incorrect data.
Basically I am read data from Torque Wrench and send to receiver using Nrf24l01. I am receiving incorrect data.
My question is :- Why I am reading Incorrect data outside "for" loop.
Correct Data inside "for" loop :- enter image description here
Incorrect Data outside "for" loop :- enter image description here
#include <SPI.h> // for SPI communication
#include <nRF24L01.h>
#include <RF24.h>
#include <cdcacm.h>
#include <usbhub.h>
//#include "pgmstrings.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = {'R','x','A','A','A','B'}; // the address the the module
class ACMAsyncOper : public CDCAsyncOper
{
public:
uint8_t OnInit(ACM *pacm);
};
uint8_t ACMAsyncOper::OnInit(ACM *pacm)
{
uint8_t rcode;
// Set DTR = 1 RTS=1
rcode = pacm->SetControlLineState(3);
if (rcode)
{
ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
return rcode;
}
LINE_CODING lc;
lc.dwDTERate = 9600;
lc.bCharFormat = 0;
lc.bParityType = 0;
lc.bDataBits = 8;
rcode = pacm->SetLineCoding(&lc);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
return rcode;
}
USB Usb;
//USBHub Hub(&Usb);
ACMAsyncOper AsyncOper;
ACM Acm(&Usb, &AsyncOper);
void setup() {
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MAX);
radio.stopListening();
#if !defined(__MIPSEL__)
while (!Serial);
#endif
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("USB Not Connected");
delay( 200 );
}
void loop() {
Usb.Task();
if( Acm.isReady()) {
uint8_t rcode;
/* reading the keyboard */
if(Serial.available()) {
uint8_t data= Serial.read();
/* sending to the phone */
rcode = Acm.SndData(1, &data);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
}
delay(10);
uint8_t buf[64];
uint16_t rcvd = 64;
char text[64];
rcode = Acm.RcvData(&rcvd, buf);
if (rcode && rcode != hrNAK)
ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
if ( rcvd ) {
for(uint16_t i=0; i < rcvd; i++ )
{
// Serial.print((char)buf[i]); // correct Data read from torque wrench
text[i] = (char)buf[i];
}
Serial.println(text); // reading wrong data here
//radio.write(&text, sizeof(text));
//Serial.println(text);
}
delay(10);
}
}
Character arrays must be null-terminated to count as C strings.
After the for loop, add text[rcvd] = '\0';
Also, your rcvd is fixed at 64. It needs to be one less than the array size for the null terminator to fit.

How to storage sensors value in JSON string

i'm doing with JSON string, i want to storage my sensor data to JSON string then i will send it to Node red or firebase (which i heard is it need JSON format, not sure about that). My actually project is receive lots of sensors value like
["ID": 01, "temp": value_temp_1, "humid": value_humid_1] , ["ID": 02, "temp": value_temp_2, "humid": value_humid_2],...
#include <DHT.h>
#include <DHT_U.h>
#include <ArduinoJson.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
int humidity, temperature;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Begin");
dht.begin();
}
void loop()
{
delay(2000);
humidity = dht.readHumidity();
temperature = dht.readTemperature();
StaticJsonDocument<50> doc;
JsonObject object = doc.to<JsonObject>();
object["ID"] = "Node01";
object["humidity"] = humidity;
object["temperature"] = temperature;
serializeJson(doc, Serial);
Serial.println("");
}
my question is do i have to use those code in loop()? everytime it will create a Json<50> so it will be full later or it only create 1 time? i have little confuse about that or could anyone give me some advices to optimize my code.
thank you
You don't need to create your object each time. Just define it as a global variable and change its values on your loop. Something like this:
#include <DHT.h>
#include <DHT_U.h>
#include <ArduinoJson.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
int humidity, temperature;
StaticJsonDocument<50> doc;
JsonObject object;
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Begin");
dht.begin();
object = doc.to<JsonObject>();
}
void loop()
{
humidity = dht.readHumidity();
temperature = dht.readTemperature();
object["ID"] = "Node01";
object["humidity"] = humidity;
object["temperature"] = temperature;
serializeJson(doc, Serial);
Serial.println("");
delay(2000);
}

I need a proper while condition for my loop

Here i have a while loop which is ment to have a condition to be satisfied, when i receive the whole message from My Arduino. The problem is that: i dont know how i could change this condition
do
{
read_result = arduino.readSerialPort(incomingData, MAX_DATA_LENGTH);
//prints out data
if (read_result > 0)
cout << incomingData;
//puts(incomingData);
} while (true);
i have inspired all my project from Here
but i have changed the main function and my arduino file. here is my main function:
//This code snippet will help you to read and write data from arduino
//#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "SerialClass.h"
#include <fstream>
//using namespace std;
using std::cin;
using std::cout;
using std::endl;
//String for getting the Output from Arduino
char outputData[MAX_DATA_LENGTH];
//String for incoming data
char incomingData[MAX_DATA_LENGTH];
//Portname must contain these backslashes
char *port_name = "\\\\.\\COM5";
const unsigned int bufSize =255;
int main()
{
SerialPort arduino(port_name);
if (arduino.isConnected())
std::cout << "Connection Established! \n" << std::endl;
else
std::cout << "ERROR, check port!";
while (arduino.isConnected()) {
std::string input_string ;
//cout << "Write something: \n";
getline(cin, input_string);
//Creating a c string
char *c_string = new char[input_string.size() + 1];
//copying the std::string to c string
std::copy(input_string.begin(), input_string.end(), c_string);
//Adding the delimeter
c_string[input_string.size()] = '\n';
//Writing string to arduino
arduino.writeSerialPort(c_string, MAX_DATA_LENGTH);
//Getting reply from arduino
arduino.readSerialPort(outputData, MAX_DATA_LENGTH);
//printing the output
//puts(outputData);
//freeing c_string memory
delete[] c_string;
//Check if data has been read or not
int read_result;
do
{
read_result = arduino.readSerialPort(incomingData, MAX_DATA_LENGTH);
//prints out data
if (read_result > 0)
cout << incomingData;
//puts(incomingData);
} while (true);
//wait a bit
//Sleep(100000);
}
}
and here is my arduino file:
int PButton=2;
int Led=13;
unsigned long start,finished,elapsed;
void setup() {
Serial.begin(9600); //begins the Serial Connection.
pinMode(PButton, INPUT_PULLUP);
pinMode(Led,OUTPUT);
digitalWrite(Led,LOW);
Serial.println("Is the video already started? ""yes/no""...\n");
start=millis();
String ans;
while(Serial.available()<=0)
{
}
ans=Serial.readStringUntil('\n');
if(ans.equals("yes")){
digitalWrite(13,HIGH);
Serial.println("The video is started!\n\nplease Press the Pushbutton when the task is fullfilled!\n");
}
else if(ans.equals("no")){
digitalWrite(13,LOW);
Serial.println("The Video is still not started! \n");
}
}
void loop() {
int buttonState=digitalRead(PButton); //read the input pin
if(buttonState==LOW)
{
Serial.print("The pushbutton is pressed after ");
finished=millis();
elapsed=finished-start;
Serial.println(elapsed);
delay(3000);
}
}

Granting access with RFID card

I've got a problem with my arduino program. I'm using a RFID reader to scan cards (this part works flawlessly). I want the program to grant access to using some buttons (doesn't matter to be honest). The user who uses a verified card can use the functionalities until he scans a card again. I've deleted some unnecessary parts of the code.
#include <SPI.h>
#include <MFRC522.h>
String read_rfid;
String ok_rfid_1="a3f90f7"; //ID of the verified CARD
const int buzzer=8; //Buzzer
const int redLed=7;
const int greenLed=6;
const int yellowLed=5;
byte access=false; //
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
}
/*
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
read_rfid="";
for (byte i = 0; i < bufferSize; i++) {
read_rfid=read_rfid + String(buffer[i], HEX);
}
}
void granted() { } //it lights up the green led
void denied() { } //it lights up the red led
void login() {
if (read_rfid==ok_rfid_1) {
granted();
access=true;
} else {
denied();
}
delay(1000);
}
void logout() {
if (read_rfid==ok_rfid_1 && access==1) {
access=false;
Serial.println("Logout ");
}
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println(read_rfid);
login();
while(access==true)
{logout();};
}
The logging in part works well, but it logs out automatically. As I observed the problem might be that if(read_rfid==ok_rfid_1 && access==1) is always true, because the read_rfid does not change. Do you have any ideas to solve my dillema?

C++ program crashed when loading array of objects

Hello i'm trying to fill an array of objects from a text file in c++ , but i have a crash every time i run the program. I'm i at the right direction here? Is there any more eficient way to do it?
main.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include "Item.h"
using namespace std;
void readItems(FILE *products, Item pList[]);
FILE *products;
int main()
{
Item pList[5];
readItems(products,pList);
return 0;
}
void readItems(FILE *products, Item pList[]){
products = fopen("data.txt", "r");
int i = 0;
fread(&pList[i], sizeof(pList), 1, products);
while (!feof(products))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}
fclose(products);
}
Item.cpp
#include "Item.h"
#include <stdio.h>
#include <string>
#include <conio.h>
#include <iostream>
using namespace std;
Item::Item()
{
code = 0;
description = "";
price = 0;
}
Item::Item(int code1,string description1,float price1)
{
code = code1;
description = description1;
price = price1;
}
void Item::printData(){
cout<<endl<<"Code:"<<code<<"\tName:"<<description<<"\tPrice:"<<price;
}
void Item::setData(int code1,string description1,float price1){
code = code1;
description = description1;
price = price1;
}
int Item::getCode(){
return code;
}
float Item::getPrice(){
return price;
}
Item::~Item()
{
//dtor
}
The new code is like that , but it prints a set of some chars of the txt file with some weird symbols .
void readItems(FILE *fin, Item list[]){
int i=0;
products = fopen("items.txt","r");
fread(&list[i],sizeof(list[i]),1,products);
list[i].printData();
while(!feof(products) && i<5){
fread(&list[i],sizeof(list[i]),1,products);
list[i].printData();
i++;
}
fclose(products);
}
Try replacing
while (!feof(products))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}
with
while (!feof(products) && (i < 5))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}

Resources