I have implemented recording and playing back audio from a microphone in C++. The next step is to process the audio data for speech recognition. For this I want to write them to large buffers so that there are no word breaks. To do this, I implemented copying to large buffers using the memcpy function. Unfortunately, it doesn't work because only part of words can be recognized. What is my mistake and can this buffer manipulation be done in a more convenient way?
My code:
#include <stdio.h>
#include <Windows.h>
#include <mmsystem.h>
#include <iostream>
#include <fstream>
using namespace std;
#pragma comment(lib, "winmm.lib")
#define Samples 16000
#define NUM_FRAMES Samples*2
#define Channels 1
const int NUM_BUF = 4;
int main()
{
HWAVEIN inStream;
HWAVEOUT outStream;
WAVEFORMATEX waveFormat;
WAVEHDR buffer[NUM_BUF];
waveFormat.cbSize = 0;
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nChannels = Channels;
waveFormat.nSamplesPerSec = Samples;
waveFormat.wBitsPerSample = 16;
waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
waveFormat.nAvgBytesPerSec = waveFormat.nBlockAlign * waveFormat.nSamplesPerSec;
HANDLE event = CreateEventA(NULL, TRUE, FALSE, "waveout event");
MMRESULT res = MMSYSERR_NOERROR;
res = waveInOpen(&inStream, WAVE_MAPPER, &waveFormat, (unsigned long)event, 0, CALLBACK_EVENT);
if (res != MMSYSERR_NOERROR) {
printf("error in waveInOpen\n");
return -1;
}
res = waveOutOpen(&outStream, WAVE_MAPPER, &waveFormat, (unsigned long)event, 0, CALLBACK_EVENT);
if (res != MMSYSERR_NOERROR) {
printf("error in waveOutOpen\n");
return -2;
}
short int *_pBuf;
size_t bpbuff = 16000*2;
_pBuf = new short int [bpbuff * NUM_BUF];
for ( int i = 0; i < NUM_BUF; i++ )
{
buffer[i].lpData = (LPSTR)&_pBuf [i * bpbuff];
buffer[i].dwBufferLength = bpbuff*sizeof(*_pBuf);
buffer[i].dwFlags = 0L;
buffer[i].dwLoops = 0L;
waveInPrepareHeader(inStream, & buffer[i], sizeof(WAVEHDR));
}
ResetEvent(event);
for (int index = 0; index < NUM_BUF; index++) // queue all buffers for input
waveInAddBuffer(inStream, &buffer[index], sizeof(WAVEHDR));
waveInStart(inStream);
int len_buff = buffer[0].dwBufferLength*6 + 1;
int limit_buff = buffer[0].dwBufferLength*5 + 1;
int size = buffer[0].dwBufferLength;
int rl = 0;
int flagg = 0;
char * buff1 = new char[len_buff];
char * buff2 = new char[len_buff];
int flag_buf = 0;
int flag1 = 0, flag2 = 0;
int i = 0;
int inIndex = 0, outIndex = 0; // the next input and output to watch
while (true) {
if (buffer[inIndex].dwFlags & WHDR_DONE & flagg!=1)
{
flagg = 1;
waveInAddBuffer(inStream, &buffer[inIndex], sizeof(WAVEHDR));
inIndex = (inIndex + 1) % NUM_BUF;
}
if (buffer[outIndex].dwFlags & WHDR_DONE & flagg!=0) {
flagg = 0;
if (flag_buf == 0)
{
if (rl<limit_buff)
{
cout << rl << endl;
if (flag1 == 0)
{
//strcpy(buff1, buffer[outIndex].lpData);
memcpy(buff1, buffer[outIndex].lpData, size);
flag1 = 1;
rl = size + 1;
}
else
{
//strcat(buff1, buffer[outIndex].lpData);
memcpy(buff1 + rl, buffer[outIndex].lpData, size);
rl = rl + size;
}
}
else
{
//recognize buff1
flag_buf = 1;
flag1 = 0;
rl = 0;
}
}
else
{
if (rl<limit_buff)
{
if (flag2 == 0)
{
memcpy(buff2, buffer[outIndex].lpData, size);
flag2 = 1;
rl = size + 1;
}
else
{
memcpy(buff2 + rl, buffer[outIndex].lpData, size);
rl = rl + size;
}
}
else
{
//recognize buff2
flag_buf = 0;
flag2 = 0;
rl = 0;
}
}
waveOutWrite(outStream, &buffer[outIndex], sizeof(WAVEHDR));
outIndex = (outIndex + 1) % NUM_BUF;
printf("N_buff_%i %i\n",outIndex , i);
i++;
}
}
for (int index = 0; index < 4; index++)
waveInUnprepareHeader(inStream, &buffer[inIndex], sizeof(WAVEHDR));
free(buffer);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So I used to use Code::Blocks IDE, and like it a lot. Recently I switched to Visual Studio. I downloaded VS Express, it was 600mb and I can only use 1gb data per day, I don't have Wi-Fi, so I that was my only option.I inserted the same code that compiled properly in Code::Blocks in it , it took a few tweaks to make it work in VS, but when I finally check it, the output was totally different, Instead of a command line Tetris, it glitched and filled the command prompt with strange characters.
This is the code I tweaked a bit to make it work in VS:
#include <iostream>
#include <time.h>
#include <string>
#include <windows.h>
using namespace std;
int nScreenHeight = 30;
int nScreenWidth = 80;
int nFieldWidth = 10;
int nFieldHeight = 25;
unsigned char *pField = NULL;
wstring tetromine[7];
int currentPiece = 0;
int currentRotation = 0;
int currentX = (nFieldWidth/2);
int currentY = 0;
unsigned int score = 0;
int pieceCounter = 0;
int speed = 20;
int speedCounter = 0;
bool forcePieceDown =false;
bool key[4];
bool shiftGridDown = false;
int rotate(int px,int py,int r)
{
switch(r/90)
{
case 0:
return py*4+px;//0 degs
case 1:
return 12+py - (px*4);//90 degs
case 2:
return 15 - (py*4) - px;//180 degs
case 3:
return 3 - py + (px*4);//270 degs
}
return 0;
}
int doesPieceFit(int id,int rot, int x, int y)
{
for(int px = 0;px<4;px++){
for(int py = 0;py<4;py++){
int pi = rotate(px,py,rot);
int fi = (y+py) * nFieldWidth + (x+px);
if(x + px>= 0 && x+px < nFieldWidth){
if(tetromine[id][pi] == L'X' && pField[fi]!=0){
return false;
}
}
}
}
return true;
}
void lineCheck(){
bool line = true;
int lines = 0;
for(int y = 0; y<= nFieldHeight-1;y++){
for(int x = 1; x< nFieldWidth-1;x++){
if(pField[(y)*nFieldWidth+x]!=0){
line &= true;
} else line &= false;
}
if(line) lines++;
if(line){
for(int x = 1; x< nFieldWidth-1;x++){
pField[(y)*nFieldWidth+x] = 8;
}
}
}
}
int main()
{
//assets
tetromine[0].append(L"..X.");
tetromine[0].append(L"..X.");
tetromine[0].append(L"..X.");
tetromine[0].append(L"..X.");
tetromine[1].append(L"..X.");
tetromine[1].append(L".XX.");
tetromine[1].append(L".X..");
tetromine[1].append(L"....");
tetromine[2].append(L".X..");
tetromine[2].append(L".XX.");
tetromine[2].append(L"..X.");
tetromine[2].append(L"....");
tetromine[3].append(L"....");
tetromine[3].append(L".XX.");
tetromine[3].append(L".XX.");
tetromine[3].append(L"....");
tetromine[4].append(L"..X.");
tetromine[4].append(L".XX.");
tetromine[4].append(L"..X.");
tetromine[4].append(L"....");
tetromine[5].append(L"....");
tetromine[5].append(L".XX.");
tetromine[5].append(L"..X.");
tetromine[5].append(L"..X.");
tetromine[6].append(L"....");
tetromine[6].append(L".XX.");
tetromine[6].append(L".X..");
tetromine[6].append(L".X..");
pField = new unsigned char[nFieldWidth*nFieldHeight];
for(int x = 0; x<nFieldWidth; x++)
{
for(int y = 0; y<nFieldHeight; y++)
{
pField[y*nFieldWidth + x] = (x==0||x==nFieldWidth -1 || y == nFieldHeight - 1) ? 9 : 0;
}
}
char *screen = new char [nScreenWidth * nScreenHeight];
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole);
DWORD dwBytesWritten = 0;
//Display frame
COORD here;
here.X = 0;
here.Y = 0;
WriteConsoleOutputCharacter(hConsole, (LPCWSTR)screen, nScreenWidth * nScreenHeight,here, &dwBytesWritten);
bool gameOver = false;
while(!gameOver)
{
Sleep(100);
speedCounter++;
if(speedCounter>=speed){
forcePieceDown = true;
speedCounter = 0;
} else {
forcePieceDown = false;
}
if(shiftGridDown){
score++;
for(int y = nFieldHeight-2;y > 0;y--){
for(int x = 1;x<nFieldWidth -1;x++){
if((pField[(y)*nFieldWidth+x]) != 0){
pField[(y+1)*nFieldWidth+x] = pField[(y)*nFieldWidth+x];
pField[(y)*nFieldWidth+x] = 0;
}
}
}
shiftGridDown = false;
lineCheck();
}
for(int x = 1; x< nFieldWidth-1;x++){
if(pField[(nFieldHeight-2)*nFieldWidth+x]==8){
pField[(nFieldHeight-2)*nFieldWidth+x]=0;
if(x==nFieldWidth-2){
shiftGridDown = true;
score+=100;
}
}
}
for(int k = 0;k<4;k++){ // R L D Z
key[k] = (0x8000 & GetAsyncKeyState((unsigned char)("DASZ"[k]))) != 0;
}
if(key[1]){
if(doesPieceFit(currentPiece,currentRotation,currentX-1,currentY)){
currentX = currentX-1;
}
}else if(key[0]){
if(doesPieceFit(currentPiece,currentRotation,currentX+1,currentY)){
currentX = currentX+1;
}
}if(key[2]){
speedCounter = speed;
}
if(key[3]&&doesPieceFit(currentPiece,currentRotation+90,currentX,currentY)){
(currentRotation+90<=270)?currentRotation+=90:currentRotation=0;
}
if(forcePieceDown){
if(doesPieceFit(currentPiece,currentRotation,currentX,currentY+1))
currentY++;
else {
//lock piece
pieceCounter++;
if(pieceCounter%5==0){
speed-=1;
}
for(int px = 0;px<4;px++){
for(int py = 0;py<4;py++){
if(tetromine[currentPiece][rotate(px,py,currentRotation)]==L'X'){
pField[(currentY+py)*nFieldWidth+(currentX+px)] = currentPiece+1;
}
}
}
score+=20;
//check lines
lineCheck();
//get next piece
currentX = nFieldWidth/2;
currentY = 0;
currentRotation = 0;
srand(time(0));
currentPiece = rand() % 7;
//check game over
gameOver = !doesPieceFit(currentPiece,currentRotation,currentX,currentY);
}
}
//draw field
for(int x = 0; x < nFieldWidth; x++)
{
for(int y = 0; y < nFieldHeight; y++)
{
screen[(y+2)*nScreenWidth + (x+ 2)] = L" xxxxxxx=#"[pField[y*nFieldWidth + x]];
}
}
//draw piece
for(int px = 0;px<4;px++){
for(int py = 0;py<4;py++){
if(tetromine[currentPiece][rotate(px,py,currentRotation)] == L'X'){
screen[(currentY+py+2)*nScreenWidth+(currentX+px+2)] = '+';
}
}
}
string s("Score -> ");
string num;
int tmp = score;
while(tmp!=0){
int rem = tmp%10;
tmp /= 10;
num = ((char)(48+rem)) + num;
}
s+=num;
for(int i = 0; i<s.size();i++){
screen[i] = s[i];
}
//display frame
WriteConsoleOutputCharacter(hConsole, (LPCWSTR)screen, nScreenWidth * nScreenHeight,here, &dwBytesWritten);
}
return 0;
}
This is the origional code :
#include <iostream>
#include <time.h>
#include <string>
#include <windows.h>
using namespace std;
int nScreenHeight = 30;
int nScreenWidth = 80;
int nFieldWidth = 10;
int nFieldHeight = 25;
unsigned char *pField = NULL;
wstring tetromine[7];
int currentPiece = 0;
int currentRotation = 0;
int currentX = (nFieldWidth/2);
int currentY = 0;
unsigned int score = 0;
int pieceCounter = 0;
int speed = 20;
int speedCounter = 0;
bool forcePieceDown =false;
bool key[4];
bool shiftGridDown = false;
int rotate(int px,int py,int r)
{
switch(r/90)
{
case 0:
return py*4+px;//0 degs
case 1:
return 12+py - (px*4);//90 degs
case 2:
return 15 - (py*4) - px;//180 degs
case 3:
return 3 - py + (px*4);//270 degs
}
return 0;
}
int doesPieceFit(int id,int rot, int x, int y)
{
for(int px = 0;px<4;px++){
for(int py = 0;py<4;py++){
int pi = rotate(px,py,rot);
int fi = (y+py) * nFieldWidth + (x+px);
if(x + px>= 0 && x+px < nFieldWidth){
if(tetromine[id][pi] == L'X' && pField[fi]!=0){
return false;
}
}
}
}
return true;
}
void lineCheck(){
bool line = true;
int lines = 0;
for(int y = 0; y<= nFieldHeight-1;y++){
for(int x = 1; x< nFieldWidth-1;x++){
if(pField[(y)*nFieldWidth+x]!=0){
line &= true;
} else line &= false;
}
if(line) lines++;
if(line){
for(int x = 1; x< nFieldWidth-1;x++){
pField[(y)*nFieldWidth+x] = 8;
}
}
}
}
int main()
{
//assets
tetromine[0].append(L"..X.");
tetromine[0].append(L"..X.");
tetromine[0].append(L"..X.");
tetromine[0].append(L"..X.");
tetromine[1].append(L"..X.");
tetromine[1].append(L".XX.");
tetromine[1].append(L".X..");
tetromine[1].append(L"....");
tetromine[2].append(L".X..");
tetromine[2].append(L".XX.");
tetromine[2].append(L"..X.");
tetromine[2].append(L"....");
tetromine[3].append(L"....");
tetromine[3].append(L".XX.");
tetromine[3].append(L".XX.");
tetromine[3].append(L"....");
tetromine[4].append(L"..X.");
tetromine[4].append(L".XX.");
tetromine[4].append(L"..X.");
tetromine[4].append(L"....");
tetromine[5].append(L"....");
tetromine[5].append(L".XX.");
tetromine[5].append(L"..X.");
tetromine[5].append(L"..X.");
tetromine[6].append(L"....");
tetromine[6].append(L".XX.");
tetromine[6].append(L".X..");
tetromine[6].append(L".X..");
pField = new unsigned char[nFieldWidth*nFieldHeight];
for(int x = 0; x<nFieldWidth; x++)
{
for(int y = 0; y<nFieldHeight; y++)
{
pField[y*nFieldWidth + x] = (x==0||x==nFieldWidth -1 || y == nFieldHeight - 1) ? 9 : 0;
}
}
char *screen = new char [nScreenWidth * nScreenHeight];
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole);
DWORD dwBytesWritten = 0;
//Display frame
WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeight, {0,0}, &dwBytesWritten);
bool gameOver = false;
while(!gameOver)
{
Sleep(100);
speedCounter++;
if(speedCounter>=speed){
forcePieceDown = true;
speedCounter = 0;
} else {
forcePieceDown = false;
}
if(shiftGridDown){
score++;
for(int y = nFieldHeight-2;y > 0;y--){
for(int x = 1;x<nFieldWidth -1;x++){
if((pField[(y)*nFieldWidth+x]) != 0){
pField[(y+1)*nFieldWidth+x] = pField[(y)*nFieldWidth+x];
pField[(y)*nFieldWidth+x] = 0;
}
}
}
shiftGridDown = false;
lineCheck();
}
for(int x = 1; x< nFieldWidth-1;x++){
if(pField[(nFieldHeight-2)*nFieldWidth+x]==8){
pField[(nFieldHeight-2)*nFieldWidth+x]=0;
if(x==nFieldWidth-2){
shiftGridDown = true;
score+=100;
}
}
}
for(int k = 0;k<4;k++){ // R L D Z
key[k] = (0x8000 & GetAsyncKeyState((unsigned char)("DASZ"[k]))) != 0;
}
if(key[1]){
if(doesPieceFit(currentPiece,currentRotation,currentX-1,currentY)){
currentX = currentX-1;
}
}else if(key[0]){
if(doesPieceFit(currentPiece,currentRotation,currentX+1,currentY)){
currentX = currentX+1;
}
}if(key[2]){
speedCounter = speed;
}
if(key[3]&&doesPieceFit(currentPiece,currentRotation+90,currentX,currentY)){
(currentRotation+90<=270)?currentRotation+=90:currentRotation=0;
}
if(forcePieceDown){
if(doesPieceFit(currentPiece,currentRotation,currentX,currentY+1))
currentY++;
else {
//lock piece
pieceCounter++;
if(pieceCounter%5==0){
speed-=1;
}
for(int px = 0;px<4;px++){
for(int py = 0;py<4;py++){
if(tetromine[currentPiece][rotate(px,py,currentRotation)]==L'X'){
pField[(currentY+py)*nFieldWidth+(currentX+px)] = currentPiece+1;
}
}
}
score+=20;
//check lines
lineCheck();
//get next piece
currentX = nFieldWidth/2;
currentY = 0;
currentRotation = 0;
srand(time(0));
currentPiece = rand() % 7;
//check game over
gameOver = !doesPieceFit(currentPiece,currentRotation,currentX,currentY);
}
}
//draw field
for(int x = 0; x < nFieldWidth; x++)
{
for(int y = 0; y < nFieldHeight; y++)
{
screen[(y+2)*nScreenWidth + (x+ 2)] = L" xxxxxxx=#"[pField[y*nFieldWidth + x]];
}
}
//draw piece
for(int px = 0;px<4;px++){
for(int py = 0;py<4;py++){
if(tetromine[currentPiece][rotate(px,py,currentRotation)] == L'X'){
screen[(currentY+py+2)*nScreenWidth+(currentX+px+2)] = '+';
}
}
}
string s("Score -> ");
string num;
int tmp = score;
while(tmp!=0){
int rem = tmp%10;
tmp /= 10;
num = ((char)(48+rem)) + num;
}
s+=num;
for(int i = 0; i<s.size();i++){
screen[i] = s[i];
}
//display frame
WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeight, { 0, 0}, &dwBytesWritten);
}
return 0;
}
You have a mix of narrow and wide characters. The cast (LPCWSTR)screen in your call to WriteConsoleOutputCharacter is an indication something isn't right.
In this case, screen is a char but you want it to be wchar_t instead. You're already using wstring for tetromine, and L prefixed character strings. You just need to ensure the rest of the code is also using wide characters.
I am writing a program that takes a bitmap file to read into memory. But as I am reading it into memory I am making some changes. First I am inverting the colors of the pixels. I managed to get this working. Now I am trying to flip the image on the Y-Axis. I have tried using two for loops but would end up get segmentation faults and also I didn't like how messy it looked. On my second attempt I found a different approach that's cleaner due to it only using one loop and one condition vs 2 loops and 2 conditions. My code now produces no errors but doesn't perform the intended operation. Is there another algorithm I could possibly try?
Below is some code for part of my program. I am trying to reverse the pixel when I am reading them row by row.
fseek(fin, bfh.offset, SEEK_SET);
Pixel *p = new Pixel[bih.height * bih.width];
for (uint32_t i = 0; i < bih.height; i++) {
for (uint32_t j = 0; j < bih.width; j++) {
uint32_t index = i * bih.width + j;
fread(&p[index], 1, sizeof(p[0]), fin);
p[index].blue = 255 - p[index].blue;
p[index].green = 255 - p[index].green;
p[index].red = 255 - p[index].red;
}
uint32_t k = (bih.width * i) - 1;
uint32_t c = 0 + (i * bih.width);
if ( i == 0) {
k = bih.width - 1;
}
while( c < k)
{
temp = p[c];
p[c] = p[k];
p[k] = temp;
c++;
k--;
}
fseek(fin, padding_bytes, SEEK_CUR);
}
fclose(fin);
Below is my whole program if needed.
#include <cstdint>
#include <cstdio>
#pragma pack(push, 2)
struct BitmapFileHeader {
uint16_t type;
uint32_t size;
uint16_t reserved_1;
uint16_t reserved_2;
uint32_t offset;
};
struct BitmapInfoHeader {
uint32_t size;
uint32_t width;
uint32_t height;
uint16_t planes;
uint16_t bitcount;
uint32_t compression;
uint32_t imagesize;
uint32_t x_pixels_per_meter;
uint32_t y_pixels_per_meter;
uint32_t color_used;
uint32_t color_important;
};
#pragma pack(pop)
struct Pixel {
uint8_t blue;
uint8_t green;
uint8_t red;
};
int main(int argc, char* argv[])
{
if(argc != 3) {
printf("Usage : %s input_file output_file\n", argv[0]);
return 1;
}
FILE *fin;
FILE *fout;
BitmapFileHeader bfh;
BitmapInfoHeader bih;
Pixel temp;
fin = fopen(argv[1], "rb");
if (nullptr == fin) {
perror(argv[1]);
return -1;
}
if (sizeof(BitmapFileHeader) != fread(
&bfh,
1,
sizeof(bfh),
fin
)) {
printf("Unable to read bitmap file header. \n");
return -2;
}
if (sizeof(BitmapInfoHeader) != fread(
&bih,
1,
sizeof(bih),
fin
)) {
printf("Unable to read bitmap info header. \n");
return -3;
}
printf("Size of File Header = %lu\n", sizeof(BitmapFileHeader));
int8_t first = (bfh.type >> 8) & 0xff;
int8_t second = bfh.type & 0xff;
if ( (first != 'M') && (second != 'B') ){
printf("Input file is not a Bitmap file. \n");
return -4;
}
printf("File type = %c%c\n", first, second);
printf("File size = %u\n", bfh.size);
printf("File offset = %u\n", bfh.offset);
printf("File width = %u\n", bih.width);
printf("Info size = %u\n", bih.size);
uint32_t padding_bytes = 0;
uint32_t row_bytes_final = bih.width * sizeof(Pixel);
uint32_t row_bytes_initial = row_bytes_final;
do{
uint32_t rem = row_bytes_final % 4;
if (rem != 0) {
row_bytes_final += 1;
}
padding_bytes = row_bytes_final - row_bytes_initial;
} while( (row_bytes_final % 4) != 0);
fseek(fin, bfh.offset, SEEK_SET);
Pixel *p = new Pixel[bih.height * bih.width];
for (uint32_t i = 0; i < bih.height; i++) {
for (uint32_t j = 0; j < bih.width; j++) {
uint32_t index = i * bih.width + j;
fread(&p[index], 1, sizeof(p[0]), fin);
p[index].blue = 255 - p[index].blue;
p[index].green = 255 - p[index].green;
p[index].red = 255 - p[index].red;
}
uint32_t k = (bih.width * i) - 1;
uint32_t c = 0 + (i * bih.width);
if ( i == 0) {
k = bih.width - 1;
}
while( (c * bih.width) < (k * bih.width))
{
temp = p[c];
p[c] = p[k];
p[k] = temp;
c++;
k--;
}
fseek(fin, padding_bytes, SEEK_CUR);
}
fclose(fin);
fout = fopen(argv[2], "wb");
if(nullptr == fout) {
perror(argv[2]);
return -5;
}
if( sizeof(BitmapFileHeader) != fwrite(
&bfh,
1,
sizeof(bfh),
fout
)) {
printf("Unable to write bitmap file header.\n");
return -6;
}
if( sizeof(BitmapInfoHeader) != fwrite(
&bih,
1,
sizeof(bih),
fout
)) {
printf("Unable to write bitmap info header.\n");
return -7;
}
fseek(fout, bfh.offset, SEEK_SET);
for (uint32_t i = 0; i < bih.height; i++) {
for (uint32_t j = 0; j < bih.width; j++) {
uint32_t index = i * bih.width + j;
fwrite(&p[index], 1, sizeof(p[0]), fout);
}
fseek(fout, padding_bytes, SEEK_CUR);
}
if (padding_bytes > 0) {
fseek(fout, -1, SEEK_CUR);
fputc('\0', fout);
}
fclose(fout);
delete[] p;
return 0;
}
You got the bounds wrong, it should be c = i * bih.width; k = (i + 1) * bih.width - 1;.
You can also use std::reverse to do this:
std::reverse(p + i * bih.width, p + (i + 1) * bih.width); // Exclusive end, so no -1
I have a code that works on Maple Mini but I have to change hardware to Nucleo F030r8 because it has more ADC's and it totally sucks.
In the modbus_update() function there is a check of the size of inputBuffer and the following code should run only if the value of this variable is bigger than 0.
if (inputBuffer > 0 && micros() - microsFlag >= T3_5) {
...
}
But it runs even if value of inputBuffer is exactly 0. The strange thing is that this code (with different serial ports opening method) runs perfectly on Maple Mini. Does anyone have any idea what can be be the problem?
Here is the whole code:
#define BAUDRATE 19200
#define RE_PIN PC12
#define TE_PIN PF4
#define LED_PIN LED_BUILTIN
#define SLAVE_ID 1
#define BUFFER_SIZE 256 // max frame size
#define READ_INTERNAL_REGISTERS 4 // function code
#define MIN_REGISTER_ADDRESS 30001
#define MAX_REGISTER_ADDRESS 30020
#define MAX_SENSORS_PER_ROW 10
#define SENSORS_PER_ROW 7
#define MAX_ROWS 2
#define ROWS 1
#define DEBUG true
#define INVALID_VALUE 0x7FFF
const byte INPUTS[] = {PA0, PA1, PA4, PB0, PC1, PC0};
unsigned char frame[BUFFER_SIZE];
unsigned char functionCode;
unsigned int T1;
unsigned int T1_5; // inter character time out
unsigned int T3_5; // frame delay
unsigned long millisFlag = 0;
unsigned long microsFlag = 0;
unsigned char inputBuffer = 0;
int dlyCounter = 0;
int16_t sensorVals[MAX_SENSORS_PER_ROW * MAX_ROWS];
/*
HardwareSerial *modbus = &Serial;
HardwareSerial Serial1(PA10, PA9);
HardwareSerial *debug = &Serial1;
*/
HardwareSerial debug(PA10, PA9);
void setup() {
pinMode(LED_PIN, OUTPUT);
for (int i = 0; i < SENSORS_PER_ROW; i++) {
pinMode(INPUTS[i], INPUT_PULLUP);
}
debug.begin(BAUDRATE, SERIAL_8E1);
modbus_configure(BAUDRATE, 0); // baud rate, low latency
microsFlag = micros();
}
void loop() {
readSensorVals(100);
modbus_update();
}
unsigned int modbus_update() {
unsigned char overflow = 0;
while (Serial.available()) {
if (overflow) {
Serial.read(); // empty the input buffer
} else {
if (inputBuffer == BUFFER_SIZE) {
overflow = 1;
} else {
frame[inputBuffer] = Serial.read();
inputBuffer++;
}
}
microsFlag = micros();
}
// If an overflow occurred return to the main sketch
// without responding to the request i.e. force a timeout
if (overflow) {
debug.println("Error: input buffer overflow");
return 0;
}
// if inter frame delay occurred, check the incoming package
if (inputBuffer > 0 && micros() - microsFlag >= T3_5) {
debug.println("\nIncoming frame:");
for (int i = 0; i < inputBuffer; i++) {
debug.print(frame[i], HEX);
debug.print(" ");
}
debug.println();
// check CRC
unsigned int crc = ((frame[inputBuffer - 2] << 8) | frame[inputBuffer - 1]); // combine the crc Low & High bytes
if (calculateCRC(frame, inputBuffer - 2) != crc) {
debug.println("Error: checksum failed");
inputBuffer = 0;
return 0;
}
debug.println("CRC OK");
// check ID
unsigned char id = frame[0];
if (id > 242) {
debug.println("Error: Invalid ID");
inputBuffer = 0;
return 0;
}
// check if it's a broadcast message
if (id == 0) {
debug.println("Broadcast message");
inputBuffer = 0;
return 0;
}
if (id != SLAVE_ID) {
debug.println("Not my ID");
inputBuffer = 0;
return 0;
}
debug.println("ID OK");
// check function code
functionCode = frame[1];
if (functionCode != READ_INTERNAL_REGISTERS) {
debug.println("Exception: illegal function");
exceptionResponse(1);
inputBuffer = 0;
return 0;
}
debug.println("Function code OK");
// check frame size (function 4 frame MUST be 8 bytes long)
if (inputBuffer != 8) {
// some workaround here:
//if (inputBuffer != 8 || !(inputBuffer == 9 && frame[inputBuffer] == 0)) {
debug.println("Error: inaccurate frame length");
inputBuffer = 0;
return 0;
}
debug.println("Frame size OK");
// check data address range
unsigned int noOfRegisters = ((frame[4] << 8) | frame[5]); // combine the number of register bytes
if (noOfRegisters > 125) {
debug.println("Exception: illegal data address");
exceptionResponse(2);
inputBuffer = 0;
return 0;
}
unsigned int firstRegAddress = ((frame[2] << 8) | frame[3]); // combine the starting address bytes
debug.print("First address: ");
debug.println(firstRegAddress);
unsigned int lastRegAddress = firstRegAddress + noOfRegisters - 1;
debug.print("Last address: ");
debug.println(lastRegAddress);
unsigned char noOfBytes = noOfRegisters * 2;
unsigned char responseFrameSize = 5 + noOfBytes; // ID, functionCode, noOfBytes, (dataLo + dataHi) * number of registers, crcLo, crcHi
unsigned char responseFrame[responseFrameSize];
responseFrame[0] = SLAVE_ID;
responseFrame[1] = 0x04;
responseFrame[2] = noOfBytes;
unsigned char address = 3; // PDU starts at the 4th byte
for (int index = (int)(firstRegAddress - MIN_REGISTER_ADDRESS); index <= (int)(lastRegAddress - MIN_REGISTER_ADDRESS); index++) {
int16_t temp = (index >= 0 && index < MAX_ROWS * MAX_SENSORS_PER_ROW) ? sensorVals[index] : INVALID_VALUE;
responseFrame[address] = temp >> 8; // split the register into 2 bytes
address++;
responseFrame[address] = temp & 0xFF;
address++;
}
unsigned int crc16 = calculateCRC(responseFrame, responseFrameSize - 2);
responseFrame[responseFrameSize - 2] = crc16 >> 8; // split crc into 2 bytes
responseFrame[responseFrameSize - 1] = crc16 & 0xFF;
debug.println("Frame to send:");
for (int i = 0; i < responseFrameSize; i++) {
debug.print(responseFrame[i], HEX);
debug.print(" ");
}
debug.println();
sendPacket(responseFrame, responseFrameSize);
inputBuffer = 0;
while (Serial.available()) { // empty input buffer
Serial.read();
}
}
}
void modbus_configure(long baud, unsigned char _lowLatency) {
Serial.begin(baud, SERIAL_8E1);
pinMode(TE_PIN, OUTPUT);
pinMode(RE_PIN, OUTPUT);
rxEnable(); // pin 0 & pin 1 are reserved for RX/TX. To disable set TE and RE pin < 2
if (baud == 1000000 && _lowLatency) {
T1 = 1;
T1_5 = 1;
T3_5 = 10;
} else if (baud >= 115200 && _lowLatency) {
T1 = 50;
T1_5 = 75;
T3_5 = 175;
} else if (baud > 19200) {
T1 = 500;
T1_5 = 750;
T3_5 = 1750;
} else {
T1 = 10000000 / baud;
T1_5 = 15000000 / baud; // 1T * 1.5 = T1.5
T3_5 = 35000000 / baud; // 1T * 3.5 = T3.5
}
}
void exceptionResponse(unsigned char exception) {
unsigned char responseFrameSize = 5;
unsigned char responseFrame[responseFrameSize];
responseFrame[0] = SLAVE_ID;
responseFrame[1] = (functionCode | 0x80); // set the MSB bit high, informs the master of an exception
responseFrame[2] = exception;
unsigned int crc16 = calculateCRC(responseFrame, 3); // ID, functionCode + 0x80, exception code == 3 bytes
responseFrame[3] = crc16 >> 8;
responseFrame[4] = crc16 & 0xFF;
sendPacket(responseFrame, responseFrameSize); // exception response is always 5 bytes (ID, functionCode + 0x80, exception code, 2 bytes crc)
}
unsigned int calculateCRC(unsigned char f[], byte bufferSize) {
unsigned int temp, temp2, flag;
temp = 0xFFFF;
for (unsigned char i = 0; i < bufferSize; i++) {
temp = temp ^ f[i];
for (unsigned char j = 1; j <= 8; j++) {
flag = temp & 0x0001;
temp >>= 1;
if (flag)
temp ^= 0xA001;
}
}
// Reverse byte order.
temp2 = temp >> 8;
temp = (temp << 8) | temp2;
temp &= 0xFFFF;
return temp; // the returned value is already swapped - crcLo byte is first & crcHi byte is last
}
void rxEnable() {
if (TE_PIN > 1 && RE_PIN > 1) {
digitalWrite(TE_PIN, LOW);
digitalWrite(RE_PIN, LOW);
digitalWrite(LED_PIN, LOW);
}
}
void txEnable() {
if (TE_PIN > 1 && RE_PIN > 1) {
digitalWrite(TE_PIN, HIGH);
digitalWrite(RE_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
}
}
void sendPacket(unsigned char f[], unsigned char bufferSize) {
txEnable();
delayMicroseconds(T3_5);
for (unsigned char i = 0; i < bufferSize; i++) {
Serial.write(f[i]);
}
Serial.flush();
delayMicroseconds(T3_5); // allow frame delay to indicate end of transmission
rxEnable();
}
// #param dly delay between sensor readings in milliseconds
void readSensorVals(int dly) {
if (millis() != millisFlag) {
dlyCounter++;
millisFlag = millis();
}
if (dlyCounter >= dly) { // read sensor values
for (int i = 0; i < MAX_ROWS; i++) {
for (int j = 0; j < MAX_SENSORS_PER_ROW; j++) {
int actualIndex = i * MAX_SENSORS_PER_ROW + j;
if (i < ROWS && j < SENSORS_PER_ROW) {
sensorVals[actualIndex] = random(20, 30);
//sensorVals[actualIndex] = (4096 - analogRead(INPUTS[j])) / 20 - 133;
} else {
sensorVals[actualIndex] = INVALID_VALUE;
}
}
}
dlyCounter = 0;
}
}
I am trying to store a sparse vector using a bit mask. I allocate a char* to represent the bit mask. However, when I delete [] the mask, I get a memory corruption error. Upon investigation, I'm seeing that it's because I'm freeing memory that I'm not supposed to. This is confusing, since I don't see how this could be the case.
When I run this on my case, it prints out "ALLOCATED" and "DEALLOCATING" but nothing further.
void set_i_bit(char* mask, int i) {
int field_num = floor(i/8);
int bit_num = i %8;
mask[field_num] = (1 << bit_num) | mask[field_num];
}
int write_sparse_with_bitmask(vector<float> arr, ofstream* fout) {
int mx_sz = arr.size() - 1;
float tol = 0.5;
char* mask = 0;
for(int i = arr.size() -1; i>=0; i-=1) {
if (fabs(arr[i]) > tol) break;
mx_sz = i;
}
int sprse_cnt = 0;
for(int i = 0; i<=mx_sz; i+=1) {
if (fabs(arr[i]) < tol) sprse_cnt++;
}
int bitmask_sz = ceil(mx_sz/8);
if (sprse_cnt*sizeof(int16_t) + sizeof(int16_t) > bitmask_sz) {
cout<<"ALLOCATED"<<endl;
mask = new char[bitmask_sz];
for (int i =0; i<bitmask_sz; i++) mask[i] = 0;
for(int i = 0; i<=mx_sz; i+=1) {
if (fabs(arr[i]) > coef_tol) {
set_i_bit(mask, i);
}
}
}
else {
bitmask_sz = 0;
}
uint16_t sz = mx_sz + 1;
uint16_t bt_msk = bitmask_sz + 1;
char flag = 0;
if (bitmask_sz > 0) {
flag = flag | 1;
}
fout->write((char*)&sz, sizeof(uint16_t));
fout->write((char*)&flag, sizeof(char));
int w_size = sizeof(uint16_t) + sizeof(char);
if (flag & 1) {
fout->write((char*)&bt_msk, sizeof(uint16_t));
fout->write(mask, sizeof(char)*bt_msk);
cout<<"DEALLOCATING"<<endl;
delete [] mask;
cout<<"THIS DOESN'T PRINT"<<endl;
w_size += sizeof(uint16_t) + sizeof(char)*bt_msk;
}
for(int i = 0; i<=mx_sz; i+=1) {
if (fabs(arr[i]) > tol || !(flag & 1)) {
int16_t vl = arr[i];
fout->write((char*) &vl, sizeof(int16_t));
w_size += sizeof(int16_t);
}
}
return w_size;
}
I am receiving data in TCP in C++ using Qt library. I store the received packet in a QByteArray, but after reading the whole data, I face this error in debug. At the end, I try to clear the buffer, but I face this problem while trying to clear it too.
Here is my code :
void AvaNPortTester::scoket_readyRead()
{
ui.lineEdit_Sending_Status_->setText("Sent");
ui.lineEdit_Sending_Status_->setStyleSheet("QLineEdit { background: rgb(50, 255, 50); }");
tcpSocket_data_buffer_.append(tcpSocket_->readAll());
//qDebug() << serialport_data_buffer_.size();
//auto ddd = QString::number(tcpSocket_data_buffer_.size());// +" : " + tcpSocket_data_buffer_.toHex();
//ui.lableSocketRead->setText(ddd);
bool read_aain = false;
QByteArray dummy(int(1446), Qt::Initialization::Uninitialized);
int reminded_data = 0;
int dummy_size = 0;
int frame_size = 0;
int l_size = 0;
int total_size_rcvd = tcpSocket_data_buffer_.size();
//int total_size_rcvd_b = total_size_rcvd_b;
int temp = 0;
while (total_size_rcvd != 0)
{
if(total_size_rcvd != 0){
auto packet = tcpSocket_data_buffer_.mid(0, 1446);
auto rem = tcpSocket_data_buffer_.mid(1446);//****1146
tcpSocket_data_buffer_ = rem;
QDataStream streamdata(packet);
uint8_t Sync_Header[3];
auto ss = streamdata.readRawData((char*)&Sync_Header, 3);
uint8_t Total_size[2];
ss = streamdata.readRawData((char*)&Total_size, 2);
int t_size = Total_size[0] * 256 + Total_size[1];
uint8_t Reserved[2];
ss = streamdata.readRawData((char*)&Reserved, 2);
frame_size = t_size - 2;
reminded_data = t_size - 2;
while (frame_size != 0)
{
uint8_t portid;
ss = streamdata.readRawData((char*)&portid, 1);
//ui.lineEdit_FileSize->setText(QString::number(fileSend_2Ser->size()));
uint8_t ProtocolID;
ss = streamdata.readRawData((char*)&ProtocolID, 1);
uint8_t MoreFragmentFlag;
ss = streamdata.readRawData((char*)&MoreFragmentFlag, 1);
uint8_t Seq;
ss = streamdata.readRawData((char*)&Seq, 1);
uint8_t size[2];
ss = streamdata.readRawData((char*)&size, 2);
l_size = size[0] * 256 + size[1];
if (packet_flags.Ser2Eth.packet_started[portid] == false) {
uint8_t DDCMP_Header[14];
ss = streamdata.readRawData((char*)&DDCMP_Header, 14);
packet_flags.Ser2Eth.protocol_payload_size[portid] = DDCMP_Header[7] + 256 * DDCMP_Header[8];
temp = packet_flags.Ser2Eth.protocol_payload_size[portid];
packet_flags.Ser2Eth.packet_started[portid] = true;
}
QByteArray ddcmp_datap(int(l_size), Qt::Initialization::Uninitialized);
streamdata.readRawData(ddcmp_datap.data(), l_size - 14);
if ((pre_more_frag == 0) && (MoreFragmentFlag == 0)) {
packet_flags.Ser2Eth.packet_ended[portid] = true;
packet_flags.Ser2Eth.protocol_payload_size[portid] = l_size;
temp = packet_flags.Ser2Eth.protocol_payload_size[portid];
}
else if ((pre_more_frag == 0) && (MoreFragmentFlag == 1)) {
packet_flags.Ser2Eth.packet_ended[portid] = false;
packet_flags.Ser2Eth.protocol_payload_size[portid] = l_size + 16;
temp = packet_flags.Ser2Eth.protocol_payload_size[portid];
}
else if ((pre_more_frag == 1) && (MoreFragmentFlag == 1)) {
packet_flags.Ser2Eth.packet_ended[portid] = false;
packet_flags.Ser2Eth.protocol_payload_size[portid] = packet_flags.Ser2Eth.protocol_payload_size[portid] + l_size;
temp = packet_flags.Ser2Eth.protocol_payload_size[portid];
}
else if ((pre_more_frag == 1) && (MoreFragmentFlag == 0)) {
packet_flags.Ser2Eth.packet_ended[portid] = true;
packet_flags.Ser2Eth.protocol_payload_size[portid] = packet_flags.Ser2Eth.protocol_payload_size[portid] + l_size;
temp = packet_flags.Ser2Eth.protocol_payload_size[portid];
}
if (MoreFragmentFlag == 1) {
pre_more_frag = 1;
}
else {
pre_more_frag = 0;
}
int ff = 0;
if (packet_flags.Ser2Eth.packet_ended[portid] == true) {
packet_flags.Ser2Eth.packet_started[portid] = false;
packet_flags.Ser2Eth.packet_started[portid] = false;
set_port_id_flag(portid, packet_flags.Ser2Eth.protocol_payload_size[portid], ProtocolID);
pre_more_frag = 0;
}
reminded_data = reminded_data - 6 - l_size;
//ui.lableSocketRead->setText(ddcmp_datap.toHex());
frame_size = frame_size - l_size - 6;
}//end of while (frame_size != 0)
uint8_t sync_footer[3];
streamdata.readRawData((char *)&sync_footer, 3);
dummy_size = 1446 - t_size - 8;
uint8_t dummy_data[1000];
streamdata.readRawData((char *)&dummy_data, dummy_size);
total_size_rcvd = total_size_rcvd - 1446;
if (total_size_rcvd == 0) {
tcpSocket_data_buffer_.clear();
}
} //end of if
}//end of while()
}