How to use boolean function inside class in Arduino? - function

I am making a library for the MPR121 sensor and in that I want to use a bool function inside a class in Arduino IDE but it is not working.
Here's my code.
#include <Wire.h>
#include "Adafruit_MPR121.h"
#ifndef _BV
#define _BV(bit) (1 << (bit))
#endif
Adafruit_MPR121 cap = Adafruit_MPR121();
uint16_t lasttouched = 0;
uint16_t currtouched = 0;
class PaperTron {
private:
uint8_t i;
uint8_t a;
public:
PaperTron(){
}
void touchBegin(){
Serial.begin(9600);
Serial.println("Hi! I'm PaperTron.");
if (!cap.begin(0x5A)) {
Serial.println("Error! TOUCH pins not found. Please check wiring.");
while (1);
}
Serial.println("Hurray! Now you can use my TOUCH pins.");
}
**//This is the boolean function which is not working**
bool isHigh(uint8_t touchpin) {
currtouched = cap.touched();
for (i=0; i<12; i++) {
if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) {
if(i==touchpin) return true;
}
if (!(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) {
if(i==touchpin) return false;
}
}
lasttouched = currtouched;
}
};
PaperTron papertron;
void setup() {
papertron.Begin();
papertron.touchBegin();
}
void loop() {
if(papertron.isHigh(2)){Serial.println("Hello");}
}
The serial monitor is showing "Hello" continuously whereas it should print "Hello" only when I press the touch pin on MPR121.

Related

Passing class function using function pointer to external library

I have a class that uses a preexisting library. There is a function call that needs a function pointer, and I am trying to pass in the function that is in my class. It doesn't compile though. What can I do to fix this? (Also, I'm sure this was asked before in a much clearer way. I'm out of my element with this, so my apologies).
Note: This is for an arduino.
In my main program I have the following code...
#include "CM.h"
CM cm;
void setup() {
cm.setup();
}
CM.h
class CM {
private:
LibClass *lib;
void onInit();
public:
void setup();
};
CM.cpp
#include "CM.h"
void CM::setup() {
lib->attach(onInit); // <-- this isn't working.
}
void CM::onInit() {
Serial.println("HERE I AM");
}
To pass a member function, you need to make it "static" and then pass it with a full scope qualifier:
#include <iostream>
void attach( void (*func)(void) );
class CM {
private:
static void onInit();
public:
void setup();
};
void CM::setup()
{
attach(CM::onInit);
}
void CM::onInit(void)
{
std::cout << "HERE I AM";
}
// a global function pointer for this example
void (*p_func)(void);
// a "library" attach function
void attach( void (*func)(void) )
{
p_func = func;
}
int main(int argc, const char * argv[]) {
CM my;
my.setup();
p_func(); // like the library call
return 0;
}

DirectX DrawText doesn't work

I have been learning DirectX and Windows programming for a short time now. However, I have a problem with the DirectX function DrawText. Somehow it doesn't display text in the window, and cannot figure out why. Here is my code:
main.cpp
//Include's
#include"winwindow.hpp"
#include<time.h>
#include<iostream>
//main
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow){
c_winwindow window(hInstance,nCmdShow);
bool b_init=false;
b_init=window.init();
while(b_init){
window.clear(D3DCOLOR_XRGB(0xEF,0xEF,0xEF));
window.drawtext(0,0,L"Halo",D3DCOLOR_COLORVALUE(0xFF,0,0,0xFF));
window.display();
b_init=window.update();
}
return 0;
}
winwindow.hpp
//Include's
#include"windows.h"
#include"d3d9.h"
#include"d3dx9.h"
//c_winwindow
class c_winwindow{
private:
HWND hwnd;
MSG msg;
HINSTANCE hInstance;
int nCmdShow;
bool b_init;
static LRESULT CALLBACK Messagehandler(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
LPDIRECT3D9 lpd3d;
LPDIRECT3DDEVICE9 lpd3ddevice;
ID3DXFont *p_d3dfont;
bool initwin();
bool initdx();
public:
c_winwindow(const HINSTANCE &hInstance,int nCmdShow);
~c_winwindow();
bool init();
bool update();
void clear(D3DCOLOR clr);
void display();
void drawtext(unsigned short int,unsigned short int,LPCWSTR,D3DCOLOR);
};
winwindow.cpp
//Include's
#include"winwindow.hpp"
#include<iostream>
//c_winwindow memberfunction's
//konstruktor
c_winwindow::c_winwindow(const HINSTANCE &temphInstance,int tempnCmdShow){
hInstance=temphInstance;
nCmdShow=tempnCmdShow;
hwnd=NULL;
lpd3d=NULL;
lpd3ddevice=NULL;
b_init=false;
}
//destruktor
c_winwindow::~c_winwindow(){
PostQuitMessage(0);
hwnd=NULL;
if(lpd3d!=NULL){
lpd3d->Release();
lpd3d=NULL;
}
if(lpd3ddevice!=NULL){
lpd3ddevice->Release();
lpd3ddevice=NULL;
}
if(p_d3dfont!=NULL){
p_d3dfont->Release();
p_d3dfont=NULL;
}
}
//initwin
bool c_winwindow::initwin(){
if(!b_init){
WNDCLASS wc;
ZeroMemory(&wc,sizeof(wc));
wc.lpfnWndProc=Messagehandler;
wc.hInstance=hInstance;
wc.lpszClassName=L"wndc";
RegisterClass(&wc);
hwnd=CreateWindow(L"wndc",L"TestWindow",WS_SYSMENU,10,10,1200,800,NULL,NULL,hInstance,NULL);
if(hwnd==NULL){
std::cout << "failed to create Window!" << std::endl;
return false;
}else{
b_init=true;
ShowWindow(hwnd,nCmdShow);
return true;
}
}else{
return true;
}
}
//initdx
bool c_winwindow::initdx(){
lpd3d=Direct3DCreate9(D3D_SDK_VERSION);
if(lpd3d==NULL){
std::cout << "couldn't create direct3d Object" << std::endl;
return false;
}
D3DPRESENT_PARAMETERS params;
ZeroMemory(&params,sizeof(params));
params.SwapEffect=D3DSWAPEFFECT_FLIP;
params.hDeviceWindow=hwnd;
params.Windowed=true;
params.BackBufferWidth=1200;
params.BackBufferHeight=800;
params.BackBufferFormat= D3DFMT_A8R8G8B8;
if(FAILED(lpd3d->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&params,&lpd3ddevice))){
std::cout << "couldn't create direct3d device" << std::endl;
return false;
}
if(D3D_OK!=D3DXCreateFont(lpd3ddevice,22,0,FW_NORMAL,1,false,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,ANTIALIASED_QUALITY,DEFAULT_PITCH|FF_DONTCARE,L"Arial",&p_d3dfont)){
std::cout << "couldn't create font" << std::endl;
return false;
}
return true;
}
//init
bool c_winwindow::init(){
return initwin()&&initdx();
}
//update
bool c_winwindow::update(){
if(b_init){
if(GetMessage(&msg,NULL,0,0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
return true;
}else{
if(lpd3d!=NULL){
lpd3d->Release();
lpd3d=NULL;
}
if(lpd3ddevice!=NULL){
lpd3ddevice->Release();
lpd3ddevice=NULL;
}
hwnd=NULL;
b_init=false;
return false;
}
}else{
return false;
}
}
//clear
void c_winwindow::clear(D3DCOLOR clr){
lpd3ddevice->Clear(0,0,D3DCLEAR_TARGET,clr,0,0);
lpd3ddevice->BeginScene();
}
//display
void c_winwindow::display(){
lpd3ddevice->EndScene();
lpd3ddevice->Present(0,0,0,0);
}
void c_winwindow::drawtext(unsigned short int us_x,unsigned short int us_y,LPCWSTR text,D3DCOLOR textcolor){
RECT r;
SetRect(&r,us_x,us_y,0,0);
p_d3dfont->DrawText(NULL,text,-1,&r,DT_LEFT,textcolor);
}
//WndProc
LRESULT CALLBACK c_winwindow::Messagehandler(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam){
switch(msg){
case(WM_DESTROY):
PostQuitMessage(0);
return 0;
break;
case(WM_PAINT):
return 0;
break;
}
return DefWindowProc(hwnd,msg,wParam,lParam);
}
The window appears grey, with no text in it. Can anyone explain why there is no text?

private C++ template function in a regular class - OpenCL

I am trying to create a customized class around the OpenCL C++ wrapper to get some specific information from the available devices. For example get the number of available GPUs, CPUs, etc. in a platform. To reduce code I decided to implement a private template function as shown below:
//Devices.hpp
class Devices
{
public:
Devices(const cl::Platform& inputPlatform)
{
inputPlatform.getDevices(CL_DEVICE_TYPE_ALL, &availableDevices);
}
cl_int getTotalNumberOfDevices()
{
return availableDevices.size();
}
cl_int getTotalNumberOfGPUs()
{
return countDevicesWithSpecificProperty(CL_DEVICE_TYPE, CL_DEVICE_TYPE_GPU);
}
private:
std::vector<cl::Device> availableDevices;
template <typename T>
cl_int countDevicesWithSpecificProperty(
const cl_device_info& deviceInfo,
const T& searchPropertyValue)
{
cl_int totalNumberOfDevices = getTotalNumberOfDevices();
T response;
cl_int count = 0;
for (cl_int i = 0; i < totalNumberOfDevices; ++i)
{
try
{
availableDevices.at(i).getInfo(deviceInfo, &response);
}
catch (cl::Error e)
{
return e.err();
}
if (response == searchPropertyValue) ++count;
}
return count;
}
};
While the code compiles correctly, getInfo throws a CL_INVALID_VALUE error. When I implemented the same code using regular function (instead of a template) the code works fine:
//Devices.hpp
class Devices
{
public:
Devices(const cl::Platform& inputPlatform)
{
inputPlatform.getDevices(CL_DEVICE_TYPE_ALL, &availableDevices);
}
cl_int getTotalNumberOfDevices()
{
return availableDevices.size();
}
cl_int getTotalNumberOfGPUs()
{
return countDevicesWithSpecificProperty(CL_DEVICE_TYPE, CL_DEVICE_TYPE_GPU);
}
private:
std::vector<cl::Device> availableDevices;
cl_int countDevicesWithSpecificProperty
(const cl_device_info& deviceInfo,
const cl_device_type& searchPropertyValue)
{
cl_int totalNumberOfDevices = getTotalNumberOfDevices();
cl_device_type response;
cl_int count = 0;
for (cl_int i = 0; i < totalNumberOfDevices; ++i)
{
try
{
availableDevices.at(i).getInfo(deviceInfo, &response);
}
catch (cl::Error e)
{
return e.err();
}
if (response == searchPropertyValue) ++count;
}
return count;
}
};
Any thoughts?
PS: The method is invoked as follows:
//main.cpp
#define __CL_ENABLE_EXCEPTIONS
#include <iostream>
#include <vector>
#include <CL/cl.hpp>
#include "Devices.hpp"
int main()
{
try
{
std::vector<cl::Platform> availablePlatforms;
cl::Platform::get(&availablePlatforms);
Devices d(availablePlatforms[0]);
std::cout << d.getTotalNumberOfGPUs() << std::endl;
}
catch (cl::Error e)
{
std::cout << e.what() << std::endl << e.err() << std::endl;
}
return 0;
}
The issue is that your response variable doesn't have the correct type in your templated version. This is because you are passing CL_DEVICE_TYPE_GPU to the templated parameter, which is a preprocessor macro, and so won't necessarily have the correct type needed for the device info query.
One solution is to explicitly cast the templated parameter to ensure it has the correct type:
return countDevicesWithSpecificProperty(CL_DEVICE_TYPE, (cl_device_type)CL_DEVICE_TYPE_GPU);
Check assembler listing for both cases. There should be some difference in what compiler generates.

How is WaitForSingleObjectEx supposed to be implemented when using source voice callbacks with XAudio2 for Windows Runtime Components?

I am receiving a system error code x05 error_access_denied when I try to use the WaitForSingleObjectEx function to signal that an Xaudio2 source voice has finished processing all of the data in its buffer.
I want to use this as an event handler to know when to submit another buffer of audio data to the source voice, so it can continue playing until my stop() function/method is called.
How should the WaitForSingleObjectEx function be propely implemented so that I do not receive the error_access_denied system error code?
This is for a Windows Phone 8 C++/CX Windows Runtime Component...
TestTone.h file:
#pragma once
#include <client.h> /* ComPtr */
#include <winnt.h> /* HRESULT */
#include <xaudio2.h> /* IXAudio2 */
#include <ppltasks.h> /* task .then */
#include "XAudio2VoiceBufferCallback.h"
namespace PhoneDirect3DXamlAppComponent
{
public ref class TestTone sealed
{
public:
void Initialize();
void Play();
void Stop();
private:
Microsoft::WRL::ComPtr<IXAudio2> pXAudio2;
IXAudio2MasteringVoice *pMasteringVoice;
IXAudio2SourceVoice * pSourceVoice;
byte soundData[2*44100];
XAUDIO2_BUFFER buffer;
WAVEFORMATEX waveformat;
VoiceCallback *vcb;
void CreateSourceVoice();
void FillSoundArrayWithData();
void getSourceVoiceCallbacks(VoiceCallback *vcb,IXAudio2SourceVoice *pSourceVoice,XAUDIO2_BUFFER *buffer);
};
}
TestTone.cpp file:
// TestTone.cpp
#include "pch.h"
#include "TestTone.h"
#include "XAudio2VoiceBufferCallback.h"
#include <client.h> /* ComPtr */
#include <winnt.h> /* HRESULT */
#include <XAudio2.h> /* IXAudio2 */
#include <ppltasks.h> /* task .then */
#include <math.h> /* sine */
#define PI 3.14159265
using namespace PhoneDirect3DXamlAppComponent;
using namespace concurrency; // tasks
void TestTone::Initialize()
{
XAudio2Create(&pXAudio2,0,XAUDIO2_DEFAULT_PROCESSOR);
pXAudio2->CreateMasteringVoice(&pMasteringVoice);
vcb = new VoiceCallback();
CreateSourceVoice();
buffer.AudioBytes = 2 * 44100;
buffer.pAudioData = soundData;
buffer.PlayBegin = 0;
buffer.PlayLength = 44100;
}
void TestTone::Play()
{
pSourceVoice->Start();
FillSoundArrayWithData();
buffer.pAudioData = soundData;
pSourceVoice->SubmitSourceBuffer(&buffer);
getSourceVoiceCallbacks(vcb, pSourceVoice, &buffer);
}
void TestTone::Stop()
{
pSourceVoice->Stop();
CreateSourceVoice();
}
void TestTone::CreateSourceVoice()
{
waveformat.wFormatTag = WAVE_FORMAT_PCM;
waveformat.nChannels = 1;
waveformat.nSamplesPerSec = 44100;
waveformat.nAvgBytesPerSec = waveformat.nSamplesPerSec * waveformat.nChannels;
waveformat.nBlockAlign = waveformat.nChannels;
waveformat.wBitsPerSample = 8;
waveformat.cbSize = 0;
hrXAudio2Create = pXAudio2->CreateSourceVoice(&pSourceVoice,&waveformat,0,XAUDIO2_DEFAULT_FREQ_RATIO,vcb,NULL,NULL);
}
void TestTone::FillSoundArrayWithData()
{
for (int index = 0, second = 0; second < 1; second++)
{
for (int sample = 0; sample < waveformat.nSamplesPerSec; sample++)
{
soundData[index++] = 128+(127*sin((500*sample*PI)/(waveformat.nSamplesPerSec)));
}
}
}
void TestTone::getSourceVoiceCallbacks(VoiceCallback *vcb,IXAudio2SourceVoice *pSourceVoice,XAUDIO2_BUFFER *buffer)
{
DWORD dw = NULL;
dw = WaitForSingleObjectEx( vcb->hBufferEndEvent,0,//INFINITE,TRUE );
DWORD err = NULL;
err = GetLastError();
while (WAIT_OBJECT_0 == (WaitForSingleObjectEx(vcb->hBufferEndEvent,INFINITE,TRUE)))
{
pSourceVoice->SubmitSourceBuffer(buffer);
}
return;
}
XAudio2VoiceBufferCallback.h file:
#pragma once
#include <client.h> /* ComPtr */
#include <winnt.h> /* HRESULT */
#include <xaudio2.h> /* IXAudio2 */
namespace PhoneDirect3DXamlAppComponent
{
class VoiceCallback : public IXAudio2VoiceCallback
{
public:
HANDLE hBufferEndEvent;
VoiceCallback();//: hBufferEndEvent( CreateEventEx( NULL, FALSE, FALSE, NULL ) ){};
~VoiceCallback();//{ CloseHandle( hBufferEndEvent ); }
//Called when the voice has just finished playing a contiguous audio stream.
virtual void __stdcall OnStreamEnd(); //{ SetEvent( hBufferEndEvent ); }
//Unused methods are stubs
void __stdcall OnVoiceProcessingPassEnd();
void __stdcall OnVoiceProcessingPassStart(UINT32 SamplesRequired);
void __stdcall OnBufferEnd(void * pBufferContext);
void __stdcall OnBufferStart(void * pBufferContext);
void __stdcall OnLoopEnd(void * pBufferContext);
void __stdcall OnVoiceError(void * pBufferContext, HRESULT Error);
};
}
XAudio2VoiceBufferCallback.cpp file:
// XAudio2VoiceBufferCallback.cpp
#include "pch.h"
#include "XAudio2VoiceBufferCallback.h"
#include <client.h> /* ComPtr */
#include <winnt.h> /* HRESULT */
#include <XAudio2.h> /* IXAudio2 */
using namespace PhoneDirect3DXamlAppComponent;
VoiceCallback::VoiceCallback()//:hBufferEndEvent( CreateEventEx( NULL, FALSE, FALSE, NULL ) )
{
hBufferEndEvent = (CreateEventEx(NULL,FALSE,FALSE,NULL));
}
VoiceCallback::~VoiceCallback()
{
CloseHandle( hBufferEndEvent );
}
void VoiceCallback::OnStreamEnd()
{
SetEvent( hBufferEndEvent );
}
void VoiceCallback::OnVoiceProcessingPassEnd() { }
void VoiceCallback::OnVoiceProcessingPassStart(UINT32 SamplesRequired) { }
void VoiceCallback::OnBufferEnd(void * pBufferContext) { }
void VoiceCallback::OnBufferStart(void * pBufferContext) { }
void VoiceCallback::OnLoopEnd(void * pBufferContext) { }
void VoiceCallback::OnVoiceError(void * pBufferContext, HRESULT Error) { }

Calling a Base Class Construtor in a function of Derived Class

I am trying to call a constructor of a Base Class in a function of Derived Class. Here is the code:
Classes:
#pragma once
#include "CAR_TYRE_DOOR.h"
#include <string>
using namespace std;
//#ifndef 1_A_H_B
//#define 1_A_H_B
class Honda_Civic: public Car
{
private:
string CNG_y_n;
public:
Honda_Civic();
Honda_Civic(string CNG);
Honda_Civic(Honda_Civic& H1);
void set_CNG_y_n(string S);
string get_CNG_y_n();
void print();
};
class BMW: public Car
{
private:
string conv_y_n;
public:
BMW();
BMW(string S);
BMW(BMW& BMW1);
void set_conv_y_n(string S);
string get_conv_y_n();
void print();
};
class Mercedes: public Car
{
private:
int no_WS;
string SGR_y_n;
public:
Mercedes();
Mercedes(int no_WS, string SGR_y_n);
Mercedes(Mercedes& Merc);
//::Car( Merc1);
void set_no_WS(int n);
void set_SGR(string SGR);
int get_no_WS();
string get_SGR();
void print();
};
//#endif
The BaseClass functions:
//#include "BMW+MERC.h"
#include "CAR_TYRE_DOOR.h"
#include "Honda.h"
#include "S_R.h"
#include <iostream>
#include <string>
using namespace std;
void Car::set_color(string S)
{
S = this->color;
}
void Car::set_model(string S)
{
S = this->model;
}
void Car::set_cost(float x)
{
x = this->cost;
}
string Car::get_color()
{
return this->color;
}
string Car::get_model()
{
return this->model;
}
float Car::get_cost()
{
return this->cost;
}
Car::Car()
{
}
Car::Car(string color, string model, float cost)
{
this->color = "white";
this->model = "2011";
this->cost = 1000000;
}
Car::Car(Car& C1)
{
this->color = C1.color;
this->model = C1.model;
this->cost = C1.cost;
for(int i=0; i<4; i++)
{
DX[i] = C1.DX[i];
}
for(int i=0; i<4; i++)
{
TX[i] = C1.TX[i];
}
}
void Car::print_car()
{
cout <<"Car color: "<<get_color()<<endl;
cout <<"Car model: "<<get_model()<<endl;
cout <<"Car door color: "<<DX[0].get_color()<<endl;
cout <<"Car door vendor: "<<DX[0].get_vendor()<<endl;
cout <<"Tyre vendor: "<<TX[0].get_vendor()<<endl;
for(int i=0; i<4; i++)
{
cout <<"Tyre"<< i+1 <<"type: "<<TX[i].get_rubber_type()<<endl;
}
}
The Derived Class:
#include "Honda.h"
#include <iostream>
#include <string>
using namespace std;
Mercedes::Mercedes()
{
}
Mercedes::Mercedes(int no_WS, string SGR_y_n)
{
this->no_WS = 4;
this->SGR_y_n = "Yes";
}
Mercedes::Mercedes(Mercedes& Merc)
{
Mercedes::Car( Merc);
this->no_WS = Merc.no_WS;
this->SGR_y_n = Merc.SGR_y_n;
}
void Mercedes::set_no_WS(int n)
{
this->no_WS = n;
}
void Mercedes::set_SGR(string SGR)
{
this->SGR_y_n = SGR;
}
int Mercedes::get_no_WS()
{
return this->no_WS;
}
string Mercedes::get_SGR()
{
return this->SGR_y_n;
}
void Mercedes::print()
{
Mercedes.print_car();
cout <<"Number of Woofer Speakers: "<<get_no_WS()<<endl;
cout <<"Sunglass Roof: "<<get_SGR()<<endl;
}
Now in the copy constructor of the derivedclass, i am trying to call the copy constructor of the base class using:
Mercedes::Mercedes(Mercedes& Merc)
{
Mercedes::Car( Merc);
this->no_WS = Merc.no_WS;
this->SGR_y_n = Merc.SGR_y_n;
}
See this: Mercedes::Car( Merc);
to implement this, please tell me the syntax.
The proper way to call constructor hierarchies is like this:
class Car
{
public:
Car () { }
Car (cosnt Car &) {}
};
class Mercedes : public Car
{
public:
Mercedes () { }
Mercedes (const Mercedes &) {}
};
Mercedes :: Mercedes () : Car() { }
Mercedes :: Mercedes (const Mercedes &car) : Car(car) { }
A copy constructor looks like this (notice the const):
Class :: Class (const Class &)