Pcl Visualizer In Visual Studio 2010 Using Cmake - visual-studio-2010

I am using pcl-visualizer on visual studio 2010.I build the files using cmake but when it is running,it is displaying only some options (as in printusage func) in the command prompt, and not further displaying or manipulating the point cloud(it is making an exit from command prompt as any key is pressed).I used PCL 1.6.0 and cmake 3.9.0.
Here is the code
#include <iostream>
#include <boost/thread/thread.hpp>
#include <pcl/common/common_headers.h>
#include <pcl/common/common_headers.h>
#include <pcl/features/normal_3d.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/console/parse.h>
void printUsage (const char* progName)
{
std::cout << "\n\nUsage: "<<progName<<" [options]\n\n"
<< "Options:\n"
<< "-------------------------------------------\n"
<< "-h this help\n"
<< "-s Simple visualisation example\n"
<< "-r RGB colour visualisation example\n"
<< "-c Custom colour visualisation example\n"
<< "-n Normals visualisation example\n"
<< "-a Shapes visualisation example\n"
<< "-v Viewports example\n"
<< "-i Interaction Customization example\n"
<< "\n\n";
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
viewer->addPointCloud<pcl::PointXYZ> (cloud, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> rgbVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> customColourVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(cloud, 0, 255, 0);
viewer->addPointCloud<pcl::PointXYZ> (cloud, single_color, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> normalsVis (
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals)
{
// --------------------------------------------------------
// -----Open 3D viewer and add point cloud and normals-----
// --------------------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals, 10, 0.05, "normals");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> shapesVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
//------------------------------------
//-----Add shapes at cloud points-----
//------------------------------------
viewer->addLine<pcl::PointXYZRGB> (cloud->points[0],
cloud->points[cloud->size() - 1], "line");
viewer->addSphere (cloud->points[0], 0.2, 0.5, 0.5, 0.0, "sphere");
//---------------------------------------
//-----Add shapes at other locations-----
//---------------------------------------
pcl::ModelCoefficients coeffs;
coeffs.values.push_back (0.0);
coeffs.values.push_back (0.0);
coeffs.values.push_back (1.0);
coeffs.values.push_back (0.0);
viewer->addPlane (coeffs, "plane");
coeffs.values.clear ();
coeffs.values.push_back (0.3);
coeffs.values.push_back (0.3);
coeffs.values.push_back (0.0);
coeffs.values.push_back (0.0);
coeffs.values.push_back (1.0);
coeffs.values.push_back (0.0);
coeffs.values.push_back (5.0);
viewer->addCone (coeffs, "cone");
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewportsVis (
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals1, pcl::PointCloud<pcl::Normal>::ConstPtr normals2)
{
// --------------------------------------------------------
// -----Open 3D viewer and add point cloud and normals-----
// --------------------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->initCameraParameters ();
int v1(0);
viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1);
viewer->setBackgroundColor (0, 0, 0, v1);
viewer->addText("Radius: 0.01", 10, 10, "v1 text", v1);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud1", v1);
int v2(0);
viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2);
viewer->setBackgroundColor (0.3, 0.3, 0.3, v2);
viewer->addText("Radius: 0.1", 10, 10, "v2 text", v2);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> single_color(cloud, 0, 255, 0);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, single_color, "sample cloud2", v2);
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud1");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud2");
viewer->addCoordinateSystem (1.0);
viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals1, 10, 0.05, "normals1", v1);
viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals2, 10, 0.05, "normals2", v2);
return (viewer);
}
unsigned int text_id = 0;
void keyboardEventOccurred (const pcl::visualization::KeyboardEvent &event,
void* viewer_void)
{
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = *static_cast<boost::shared_ptr<pcl::visualization::PCLVisualizer> *> (viewer_void);
if (event.getKeySym () == "r" && event.keyDown ())
{
std::cout << "r was pressed => removing all text" << std::endl;
char str[512];
for (unsigned int i = 0; i < text_id; ++i)
{
sprintf (str, "text#%03d", i);
viewer->removeShape (str);
}
text_id = 0;
}
}
void mouseEventOccurred (const pcl::visualization::MouseEvent &event,
void* viewer_void)
{
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = *static_cast<boost::shared_ptr<pcl::visualization::PCLVisualizer> *> (viewer_void);
if (event.getButton () == pcl::visualization::MouseEvent::LeftButton &&
event.getType () == pcl::visualization::MouseEvent::MouseButtonRelease)
{
std::cout << "Left mouse button released at position (" << event.getX () << ", " << event.getY () << ")" << std::endl;
char str[512];
sprintf (str, "text#%03d", text_id ++);
viewer->addText ("clicked here", event.getX (), event.getY (), str);
}
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> interactionCustomizationVis ()
{
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
viewer->addCoordinateSystem (1.0);
viewer->registerKeyboardCallback (keyboardEventOccurred, (void*)&viewer);
viewer->registerMouseCallback (mouseEventOccurred, (void*)&viewer);
return (viewer);
}
// --------------
// -----Main-----
// --------------
int
main (int argc, char** argv)
{
// --------------------------------------
// -----Parse Command Line Arguments-----
// --------------------------------------
if (pcl::console::find_argument (argc, argv, "-h") >= 0)
{
printUsage (argv[0]);
return 0;
}
bool simple(false), rgb(false), custom_c(false), normals(false),
shapes(false), viewports(false), interaction_customization(false);
if (pcl::console::find_argument (argc, argv, "-s") >= 0)
{
simple = true;
std::cout << "Simple visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-c") >= 0)
{
custom_c = true;
std::cout << "Custom colour visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-r") >= 0)
{
rgb = true;
std::cout << "RGB colour visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-n") >= 0)
{
normals = true;
std::cout << "Normals visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-a") >= 0)
{
shapes = true;
std::cout << "Shapes visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-v") >= 0)
{
viewports = true;
std::cout << "Viewports example\n";
}
else if (pcl::console::find_argument (argc, argv, "-i") >= 0)
{
interaction_customization = true;
std::cout << "Interaction Customization example\n";
}
else
{
printUsage (argv[0]);
return 0;
}
// ------------------------------------
// -----Create example point cloud-----
// ------------------------------------
pcl::PointCloud<pcl::PointXYZ>::Ptr basic_cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr point_cloud_ptr (new pcl::PointCloud<pcl::PointXYZRGB>);
std::cout << "Genarating example point clouds.\n\n";
// We're going to make an ellipse extruded along the z-axis. The colour for
// the XYZRGB cloud will gradually go from red to green to blue.
uint8_t r(255), g(15), b(15);
for (float z(-1.0); z <= 1.0; z += 0.05)
{
for (float angle(0.0); angle <= 360.0; angle += 5.0)
{
pcl::PointXYZ basic_point;
basic_point.x = 0.5 * cosf (pcl::deg2rad(angle));
basic_point.y = sinf (pcl::deg2rad(angle));
basic_point.z = z;
basic_cloud_ptr->points.push_back(basic_point);
pcl::PointXYZRGB point;
point.x = basic_point.x;
point.y = basic_point.y;
point.z = basic_point.z;
uint32_t rgb = (static_cast<uint32_t>(r) << 16 |
static_cast<uint32_t>(g) << 8 | static_cast<uint32_t>(b));
point.rgb = *reinterpret_cast<float*>(&rgb);
point_cloud_ptr->points.push_back (point);
}
if (z < 0.0)
{
r -= 12;
g += 12;
}
else
{
g -= 12;
b += 12;
}
}
basic_cloud_ptr->width = (int) basic_cloud_ptr->points.size ();
basic_cloud_ptr->height = 1;
point_cloud_ptr->width = (int) point_cloud_ptr->points.size ();
point_cloud_ptr->height = 1;
// ----------------------------------------------------------------
// -----Calculate surface normals with a search radius of 0.05-----
// ----------------------------------------------------------------
pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne;
ne.setInputCloud (point_cloud_ptr);
pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB> ());
ne.setSearchMethod (tree);
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals1 (new pcl::PointCloud<pcl::Normal>);
ne.setRadiusSearch (0.05);
ne.compute (*cloud_normals1);
// ---------------------------------------------------------------
// -----Calculate surface normals with a search radius of 0.1-----
// ---------------------------------------------------------------
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2 (new pcl::PointCloud<pcl::Normal>);
ne.setRadiusSearch (0.1);
ne.compute (*cloud_normals2);
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
if (simple)
{
viewer = simpleVis(basic_cloud_ptr);
}
else if (rgb)
{
viewer = rgbVis(point_cloud_ptr);
}
else if (custom_c)
{
viewer = customColourVis(basic_cloud_ptr);
}
else if (normals)
{
viewer = normalsVis(point_cloud_ptr, cloud_normals2);
}
else if (shapes)
{
viewer = shapesVis(point_cloud_ptr);
}
else if (viewports)
{
viewer = viewportsVis(point_cloud_ptr, cloud_normals1, cloud_normals2);
}
else if (interaction_customization)
{
viewer = interactionCustomizationVis();
}
//--------------------
// -----Main loop-----
//--------------------
while (!viewer->wasStopped ())
{
viewer->spinOnce (100);
boost::this_thread::sleep (boost::posix_time::microseconds (100000));
}
}

Related

Inverting a bitmap in Embarcadero C++Builder

The same problem happens in Borland C++Builder 6 and Embarcadero C++Builder 2010.
When I try to invert an image, the form freezes for about 5 seconds and nothing happens. When I click again, the image is inverted within a blink of an eye, and again, again...
To reproduce, create a form with a TImage and two TButton's using this code:
//---------------------------------------------------------------------------
#include <vcl.h>
#include <jpeg.hpp>
#pragma hdrstop
#pragma package(smart_init)
#pragma resource "*.dfm"
#include "Unit1.h"
TForm1 *Form1;
Graphics::TBitmap *CurrentBitmap;
bool bLoaded = false;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
CurrentBitmap = new Graphics::TBitmap;
}
//---------------------------------------------------------------------------
bool __fastcall Invert( TImage *img ) {
if( bLoaded ) {
double Scale, ScaleW, ScaleH;
Graphics::TBitmap *bmp = new Graphics::TBitmap;
bmp->Assign( CurrentBitmap );
DWORD **pixel = new DWORD*[bmp->Height];
for( long y=0; y<bmp->Height; y++ ) {
pixel[y] = (DWORD*)(bmp->ScanLine[y]);
for( long x=0; x<bmp->Width; x++ ) {
if( pixel[y][x] == clBlack ) {
pixel[y][x] = clWhite;
} else if( pixel[y][x] == clWhite ) {
pixel[y][x] = clBlack;
}
}
}
delete[] pixel;
ScaleW = (double)bmp->Width / img->ClientWidth;
ScaleH = (double)bmp->Height / img->ClientHeight;
if( ScaleW > ScaleH ) {
Scale = ScaleW;
} else {
Scale = ScaleH;
}
CurrentBitmap->Assign( bmp );
img->Picture->Bitmap->Canvas->StretchDraw(Rect(0, 0, bmp->Width/Scale, bmp->Height/Scale), bmp );
delete bmp;
return true;
} else {
return false;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) {
TJPEGImage *jpg = new TJPEGImage();
jpg->LoadFromFile( "V:\\CBuilder\\BCB10\\GerberTest\\Testdata\\GerberTest.dpi2400.mskcmp.jpg" );
CurrentBitmap->Width = jpg->Width;
CurrentBitmap->Height = jpg->Height;
CurrentBitmap->Canvas->StretchDraw(Rect(0, 0, jpg->Width, jpg->Height), jpg );
bLoaded = true;
double Scale, ScaleW, ScaleH;
ScaleW = (double)jpg->Width / Image1->ClientWidth;
ScaleH = (double)jpg->Height / Image1->ClientHeight;
if( ScaleW > ScaleH ) {
Scale = ScaleW;
} else {
Scale = ScaleH;
}
Image1->Canvas->StretchDraw(Rect(0, 0, jpg->Width/Scale, jpg->Height/Scale), jpg );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender) {
Invert( Image1 );
}
I cannot explain why the application freezes, or what the code is doing during the 5 second delay.
Like Remy Lebeau mentioned you should set the PixelFormat. I tried your solution which did not seems to invert images properly. Below you find a solution which should work properly.
#include <JPEG.hpp>
Byte __fastcall IntToByte(int AValue)
{
if (AValue > 255)
return 255;
else if (AValue < 0)
return 0;
else
return AValue;
}
// ---------------------------------------------------------------------------
void __fastcall InvertBitmap(Graphics::TBitmap *ABitmap)
{
Byte *p0;
int red, green, blue;
for (int y = 0; y < ABitmap->Height; y++) {
p0 = (Byte*) ABitmap->ScanLine[y];
for (int x = 0; x < ABitmap->Width; x++) {
red = p0[x * 3];
green = p0[x * 3 + 1];
blue = p0[x * 3 + 2];
// invert
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
p0[x * 3] = IntToByte(red);
p0[x * 3 + 1] = IntToByte(green);
p0[x * 3 + 2] = IntToByte(blue);
}
}
}
// ---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Screen->Cursor = crHourGlass;
TJPEGImage *jpeg = new TJPEGImage();
Graphics::TBitmap *bitmap = new Graphics::TBitmap();
try {
jpeg->LoadFromFile("**YOUR-JPEG-FILE**");
bitmap->SetSize(jpeg->Width, jpeg->Height);
bitmap->Canvas->Draw(0, 0, jpeg);
bitmap->PixelFormat = pf24bit;
InvertBitmap(bitmap);
Image1->Picture->Bitmap->Assign(bitmap);
}
__finally {
jpeg->Free();
bitmap->Free();
}
Screen->Cursor = crDefault;
}
// ---------------------------------------------------------------------------

direct x 11 invalid argument when creating vertex shader

Here is the Shader Code File Name:Shader.shader
struct VOut
{
float4 position : SV_POSITION;
float4 color : COLOR;
};
VOut VMain(float4 position : POSITION, float4 color : COLOR)
{
VOut output;
output.position = position;
output.color = color;
return output;
}
float4 PMain(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
return color;
}
Here is how I compile my shaders
RasterShader::RasterShader(ID3D11Device* device,LPCWSTR vFile,LPCSTR vEntry,LPCSTR vVersion,LPCWSTR pFile,LPCSTR pEntry,LPCSTR pVersion)
{
ID3DBlob* compiledCode=nullptr;
vShader = nullptr;
pShader = nullptr;
errors = 0;
if (FAILED(Compile(vFile,vEntry,vVersion,&compiledCode)))
{
errors = 1;
return;
}
if (FAILED(device->CreateVertexShader(compiledCode->GetBufferPointer(), compiledCode->GetBufferSize(),nullptr, &vShader)))
{
compiledCode->Release();
MessageBox(NULL, L"Failed To Create Vertex Shader", L"Failed Vertex Shader", MB_OK);
errors = 1;
return;
}
D3D11_INPUT_ELEMENT_DESC desc[] =
{
{"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0}
,{"COLOR",0,DXGI_FORMAT_R32G32B32_FLOAT,0,12,D3D11_INPUT_PER_VERTEX_DATA,0}
};
if (FAILED(device->CreateInputLayout(desc, 2,compiledCode->GetBufferPointer(),compiledCode->GetBufferSize(),&inputLayout)))
{
compiledCode->Release();
MessageBox(NULL, L"Failed To Create Input Layout", L"Failed Input Layout", MB_OK);
errors = 1;
return;
}
compiledCode->Release();
if (FAILED(Compile(pFile,pEntry,pVersion,&compiledCode)))
{
errors = 1;
return;
}
if (FAILED(device->CreatePixelShader(compiledCode->GetBufferPointer(), compiledCode->GetBufferSize(), nullptr, &pShader)))
{
compiledCode->Release();
MessageBox(NULL, L"Failed To Create Pixel Shader", L"Failed Pixel Shader", MB_OK);
errors = 1;
return;
}
compiledCode->Release();
}
HRESULT RasterShader::Compile(LPCWSTR fileName,LPCSTR entry,LPCSTR version,ID3DBlob** code)
{
ID3DBlob* errors=nullptr;
HRESULT hr = D3DCompileFromFile(fileName,nullptr,nullptr
,entry,version
,0,0,code,&errors);
if (FAILED(hr))
{
if (errors!=nullptr)
{
CString data((char*)errors->GetBufferPointer());
MessageBox(NULL, data.GetBuffer(), L"Shader Compile Errors", MB_OK);
data.ReleaseBuffer();
errors->Release();
}
if (code) { (*code)->Release(); }
}
return hr;
}
RasterShader * RasterShader::Create(ID3D11Device* device,LPCWSTR vFile,LPCSTR vMain,LPCSTR vVersion,LPCWSTR pFile,LPCSTR pMain,LPCSTR pVersion)
{
RasterShader* shader = new RasterShader(device,vFile,vMain,vVersion,pFile,pMain,pVersion);
if (shader->errors == 1)
{
delete shader;
shader = nullptr;
}
return shader;
}
Here is how I create my shader
shader = RasterShader::Create(directx->getDevice(), L"Shader.shader","VMain","vs_4_0",L"Shader.shader","PMain","ps_4_0");
if (shader == nullptr)
{
errors = 1;
return;
}
Here is how I create my device
D3D_FEATURE_LEVEL levels[] = {
D3D_FEATURE_LEVEL_9_1,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_11_1
};
//CREATE DEVICE AND CONTEXT
HRESULT hr = D3D11CreateDevice(nullptr,D3D_DRIVER_TYPE_HARDWARE,0,D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D10_CREATE_DEVICE_DEBUG
,levels,ARRAYSIZE(levels),D3D11_SDK_VERSION
,&device,&level,&context);
The Returned/Supported feature level is 9_1
The program breaks at the point I create my VertexShader with the Message "FAILED TO CREATE VERTEX SHADER"
When I analyze the HRESULT returned by device->CreateVertexShader() I get the Error Code
E_INVALIDARG
When debug layer was enabled I got this error
CreateVertexShader: Encoded Vertex Shader size doesn't match specified size. [ STATE_CREATION ERROR #166: CREATEVERTEXSHADER_INVALIDSHADERBYTECODE]
I tired enquiring the size of my buffer. Not sure if helpful or if I did it right.
wchar_t buffer[256];
wsprintf(buffer, L"%d",sizeof((*code)->GetBufferPointer()));
MessageBox(NULL, buffer, L"A", MB_OK);
It prints 4
wchar_t buffer[256];
wsprintf(buffer, L"%d",sizeof((*code)->GetBufferSize()));
MessageBox(NULL, buffer, L"A", MB_OK);
It prints 164
Any help would be greatly appreciated. Thank U
Eurika I got it !!
Turns out my profile should be combined with my feature level as follows
Vertex Shader : vs_4_0_level_9_1
Pixel Shader : ps_4_0_level_9_1
Thank's Everyone :)

HLSL Stream Out Entries don't work correctly

I want implement Particle system based on stream out structure to my bigger project. I saw few articles about that method and I build one particle. It works almost correctly but in geometry shader with stream out i cant get value of InitVel.z and age because it always is 0. If i change order of age(for example age is before Position) it works fine for age but 6th float of order is still 0. It looks like he push only 5 first positions. I had no idea what i do wrong because i try change almost all(create input layout for vertex, the same like entry SO Declaration, change number of strides for static 28, change it to 32 but in this case he draw chaotic so size of strides is probably good). I think it is problem with limits of NumEntry in declaration Entry but on site msdn i saw the limit for directx is D3D11_SO_STREAM_COUNT(4)*D3D11_SO_OUTPUT_COMPONENT_COUNT(128) not 5. Pls can you look in this code and give me the way or hope of implement it correctly?? Thanks a lot for help.
Structure of particle
struct Particle{
Particle() {}
Particle(float x, float y, float z,float vx, float vy, float vz,float
l /*UINT typ*/)
:InitPos(x, y, z), InitVel(vx, vy, vz), Age(l) /*, Type(typ)*/{}
XMFLOAT3 InitPos;
XMFLOAT3 InitVel;
float Age;
//UINT Type;
};
SO Entry
D3D11_SO_DECLARATION_ENTRY PartlayoutSO[] =
{
{ 0,"POSITION", 0, 0 , 3, 0 }, // output all components of position
{ 0,"VELOCITY", 0, 0, 3, 0 },
{ 0,"AGE", 0, 0, 1, 0 }
//{ 0,"TYPE", 0, 0, 1, 0 }
};
Global Variables
//streamout shaders
ID3D11VertexShader* Part_VSSO;
ID3D11GeometryShader* Part_GSSO;
ID3DBlob *Part_GSSO_Buffer;
ID3DBlob *Part_VSSO_Buffer;
//normal shaders
ID3D11VertexShader* Part_VS;
ID3D11GeometryShader* Part_GS;
ID3DBlob *Part_GS_Buffer;
ID3D11PixelShader* Part_PS;
ID3DBlob *Part_VS_Buffer;
ID3DBlob *Part_PS_Buffer;
ID3D11Buffer* PartVertBufferInit;
//ID3D11Buffer* Popy;
ID3D11Buffer* mDrawVB;
ID3D11Buffer* mStreamOutVB;
ID3D11InputLayout* PartVertLayout;// I try to set input layout too
void ParticleSystem::InitParticles()
{
mFirstRun = true;
srand(time(NULL));
hr = D3DCompileFromFile(L"ParticleVertexShaderSO4.hlsl", NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "vs_5_0", NULL, NULL,
&Part_VSSO_Buffer, NULL);
hr = D3DCompileFromFile(L"ParticleGeometryShaderSO4.hlsl", NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "gs_5_0", NULL, NULL,
&Part_GSSO_Buffer, NULL);
UINT StrideArray[1] = { sizeof(Particle) };//I try to set static 28 bits-7*4
per float
hr = device->CreateVertexShader(Part_VSSO_Buffer->GetBufferPointer(),
Part_VSSO_Buffer->GetBufferSize(), NULL, &Part_VSSO);
hr = device->CreateGeometryShaderWithStreamOutput(Part_GSSO_Buffer-
>GetBufferPointer(), Part_GSSO_Buffer->GetBufferSize(), PartlayoutSO ,3/*
sizeof(PartlayoutSO)*/ , StrideArray, 1,D3D11_SO_NO_RASTERIZED_STREAM,
NULL,&Part_GSSO);
//Draw Shaders
hr = D3DCompileFromFile(L"ParticleVertexShaderDRAW4.hlsl", NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "vs_5_0", NULL, NULL,
&Part_VS_Buffer, NULL);
hr = D3DCompileFromFile(L"ParticleGeometryShaderDRAW4.hlsl", NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "gs_5_0", NULL, NULL,
&Part_GS_Buffer, NULL);
hr = D3DCompileFromFile(L"ParticlePixelShaderDRAW4.hlsl", NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "ps_5_0", NULL, NULL,
&Part_PS_Buffer, NULL);
hr = device->CreateVertexShader(Part_VS_Buffer->GetBufferPointer(),
Part_VS_Buffer->GetBufferSize(), NULL, &Part_VS);
hr = device->CreateGeometryShader(Part_GS_Buffer->GetBufferPointer(),
Part_GS_Buffer->GetBufferSize(), NULL, &Part_GS);
hr = device->CreatePixelShader(Part_PS_Buffer->GetBufferPointer(),
Part_PS_Buffer->GetBufferSize(), NULL, &Part_PS);
BuildVertBuffer();
}
void ParticleSystem::BuildVertBuffer()
{
D3D11_BUFFER_DESC vertexBufferDesc1;
ZeroMemory(&vertexBufferDesc1, sizeof(vertexBufferDesc1));
vertexBufferDesc1.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc1.ByteWidth = sizeof(Particle)*1; //*numParticles;
vertexBufferDesc1.BindFlags = D3D11_BIND_VERTEX_BUFFER;// |
D3D11_BIND_STREAM_OUTPUT;
vertexBufferDesc1.CPUAccessFlags = 0;
vertexBufferDesc1.MiscFlags = 0;
vertexBufferDesc1.StructureByteStride = 0;// I tried to comment this too
Particle p;
ZeroMemory(&p, sizeof(Particle));
p.InitPos = XMFLOAT3(0.0f, 0.0f, 0.0f);
p.InitVel = XMFLOAT3(0.0f, 0.0f, 0.0f);
p.Age = 0.0f;
//p.Type = 100.0f;
D3D11_SUBRESOURCE_DATA vertexBufferData1;
ZeroMemory(&vertexBufferData1, sizeof(vertexBufferData1));
vertexBufferData1.pSysMem = &p;//było &p
vertexBufferData1.SysMemPitch = 0;
vertexBufferData1.SysMemSlicePitch = 0;
hr = device->CreateBuffer(&vertexBufferDesc1, &vertexBufferData1,
&PartVertBufferInit);
ZeroMemory(&vertexBufferDesc1, sizeof(vertexBufferDesc1));
vertexBufferDesc1.ByteWidth = sizeof(Particle) * numParticles;
vertexBufferDesc1.BindFlags = D3D11_BIND_VERTEX_BUFFER |
D3D11_BIND_STREAM_OUTPUT;
hr = device->CreateBuffer(&vertexBufferDesc1, 0, &mDrawVB);
hr = device->CreateBuffer(&vertexBufferDesc1, 0, &mStreamOutVB);
}
void ParticleSystem::LoadDataParticles()
{
UINT stride = sizeof(Particle);
UINT offset = 0;
//Create the Input Layout
//device->CreateInputLayout(Partlayout, numElementsPart, Part_VSSO_Buffer-
//>GetBufferPointer(),
// Part_VSSO_Buffer->GetBufferSize(), &PartVertLayout);
//Set the Input Layout
//context->IASetInputLayout(PartVertLayout);
//Set Primitive Topology
context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
if (mFirstRun)
{
// context->CopyResource(Popy, PartVertBufferInit);
context->IASetVertexBuffers(0, 1, &PartVertBufferInit, &stride,
&offset);
}
else
{
context->IASetVertexBuffers(0, 1, &mDrawVB, &stride, &offset);
}
context->SOSetTargets(1, &mStreamOutVB, &offset);
context->VSSetShader(Part_VSSO, NULL, 0);
context->GSSetShader(Part_GSSO, NULL, 0);
context->PSSetShader(NULL, NULL, 0);
//context->PSSetShader(Part_PS, NULL, 0);
ID3D11DepthStencilState* depthState;//disable depth
D3D11_DEPTH_STENCIL_DESC depthStateDesc;
depthStateDesc.DepthEnable = false;
depthStateDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
device->CreateDepthStencilState(&depthStateDesc, &depthState);
context->OMSetDepthStencilState(depthState, 0);
if (mFirstRun)
{
//mFirstRun;
context->Draw(1, 0);
mFirstRun = false;
}
else
{
context->DrawAuto();
}
//}
// done streaming-out--unbind the vertex buffer
ID3D11Buffer* bufferArray[1] = { 0 };
context->SOSetTargets(1, bufferArray, &offset);
// ping-pong the vertex buffers
std::swap(mStreamOutVB, mDrawVB);
// Draw the updated particle system we just streamed-out.
//Create the Input Layout
//device->CreateInputLayout(Partlayout, numElementsPart, Part_VS_Buffer-
//>GetBufferPointer(),
// Part_VS_Buffer->GetBufferSize(), &PartVertLayout);
//Set the normal Input Layout
//context->IASetInputLayout(PartVertLayout);
context->IASetVertexBuffers(0, 1, &mDrawVB, &stride, &offset);
ZeroMemory(&depthStateDesc, sizeof(depthStateDesc));
depthStateDesc.DepthEnable = true;
depthStateDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
device->CreateDepthStencilState(&depthStateDesc, &depthState);
context->OMSetDepthStencilState(depthState, 0);
//I tried add normal layout here the same like Entry SO but no changes
//Set Primitive Topology
//context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
context->VSSetShader(Part_VS, NULL, 0);
context->GSSetShader(Part_GS, NULL, 0);
context->PSSetShader(Part_PS, NULL, 0);
context->DrawAuto();
//mFirstRun = true;
context->GSSetShader(NULL, NULL, 0);
}
void ParticleSystem::RenderParticles()
{
//mFirstRun = true;
LoadDataParticles();
}
And the code of shaders:
VertexShader to stream out
struct Particle
{
float3 InitPos : POSITION;
float3 InitVel : VELOCITY;
float Age : AGE;
//uint Type : TYPE;
};
Particle main(Particle vin)
{
return vin;// just push data into geomtrywithso
}
GeometrywithSo
struct Particle
{
float3 InitPos : POSITION;
float3 InitVel : VELOCITY;
float Age : AGE;
//uint Type : TYPE;
};
float RandomPosition(float offset)
{
float u = Time + offset;// (Time + offset);
float v = ObjTexture13.SampleLevel(ObjSamplerState, u, 0).r;
return (v);
}
[maxvertexcount(6)]
void main(
point Particle gin[1],
inout PointStream< Particle > Output
)
{
//gin[0].Age = Time;
if ( StartPart == 1.0f )
{
//if (gin[0].Age < 100.0f)
//{
for (int i = 0; i < 6; i++)
{
float3 VelRandom; //= 5.0f * RandomPosition((float)i / 5.0f);
VelRandom.y = 10.0f+i;
VelRandom.x = 35 * i* RandomPosition((float)i / 5.0f);//+ offse;
VelRandom.z = 10.0f;//35*i * RandomPosition((float)i / 5.0f);
Particle p;
p.InitPos = VelRandom;//float3(0.0f, 5.0f, 0.0f); //+ VelRandom;
p.InitVel = float3(10.0f, 10.0f, 10.0f);
p.Age = 0.0f;//VelRandom.y;
//p.Type = PT_FLARE;
Output.Append(p);
}
Output.Append(gin[0]);
}
else if (StartPart == 0.0f)
{
if (gin[0].Age >= 0)
{
Output.Append(gin[0]);
}
}
}
If I change Age in geometry with so: for example Age += Time from const buffer
In geometry shader its fine once but in draw shader it is 0 and next time if it is reading in geometry with so it is 0 too.
Vertex shader to draw
struct VertexOut
{
float3 Pos : POSITION;
float4 Colour : COLOR;
//uint Type : TYPE;
};
struct Particle
{
float3 InitPos : POSITION;
float3 InitVel : VELOCITY;
float Age : AGE;
// uint Type : TYPE;
};
VertexOut main(Particle vin)
{
VertexOut vout;
float3 gAccelW = float3(0.0f, -0.98f, 0.0f);
float t = vin.Age;
//float b = Time/10000;
// constant Acceleration equation
vout.Pos = vin.InitVel+ (0.7f * gAccelW)*Time/100;
//vout.Pos.x = t;
vout.Colour = float4(1.0f, 0.0f, 0.0f, 1.0f);
//vout.Age = vout.Pos.y;
//vout.Type = vin.Type;
return vout;
}
Geometry shader to change point into line
struct VertexOut
{
float3 Pos : POSITION;
float4 Colour : COLOR;
//uint Type : TYPE;
};
struct GSOutput
{
float4 Pos : SV_POSITION;
float4 Colour : COLOR;
//float2 Tex : TEXCOORD;
};
[maxvertexcount(2)]
void main(
point VertexOut gin[1],
inout LineStream< GSOutput > Output
)
{
float3 gAccelW = float3(0.0f, -0.98f, 0.0f);
//if (gin[0].Type != PT_EMITTER)
{
float4 v[2];
v[0] = float4(gin[0].Pos, 1.0f);
v[1] = float4((gin[0].Pos + gAccelW), 1.0f);
GSOutput gout;
[unroll]
for (int i = 0; i < 2; ++i)
{
gout.Pos = mul(v[i], WVP);// mul(v[i], gViewProj);
gout.Colour = gin[0].Colour;
Output.Append(gout);
}
}
}
And pixel Shader
struct GSOutput
{
float4 Pos : SV_POSITION;
float4 Colour : COLOR;
};
float4 main(GSOutput pin) : SV_TARGET
{
return pin.Colour;
}

Why I can't see the value in my trackbar?

my running environment as follow:
Mac OSX EI 10.11.5
opencv 2.4.13
Xcode Version 7.3.1
why there is not display my value on the trackbar as attached picture.
is this because of system problem?
main()
{
VideoCapture cap(0);
if ( !cap.isOpened() ) // if not success, exit program
{
cout << "Cannot open the cam" << endl;
return -1;
}
namedWindow("Thresholded Image", CV_WINDOW_AUTOSIZE); //create a window called "Control"
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
cvCreateTrackbar("LowH", "Thresholded Image", &iLowH, 179);
cvCreateTrackbar("HighH", "Thresholded Image", &iHighH, 179);
cvCreateTrackbar("LowS", "Thresholded Image", &iLowS, 255);
cvCreateTrackbar("HighS", "Thresholded Image", &iHighS, 255);
cvCreateTrackbar("LowV", "Thresholded Image", &iLowV, 255);
cvCreateTrackbar("HighV", "Thresholded Image", &iHighV, 255);
while (true)
{
Mat imgOriginal;
bool bSuccess = cap.read(imgOriginal); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
Mat imgHSV;
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
Mat imgThresholded;
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
namedWindow("Thresholded Image", 0);
namedWindow("Original", CV_WINDOW_NORMAL);
resize(imgThresholded,imgThresholded, Size(imgThresholded.cols/3, imgThresholded.rows/3));
namedWindow("Thresholded Image", CV_WINDOW_AUTOSIZE);
imshow("Thresholded Image", imgThresholded); //show the thresholded image
resize(imgOriginal,imgOriginal, Size(imgOriginal.cols/3, imgOriginal.rows/3));
namedWindow("Original", CV_WINDOW_AUTOSIZE);
imshow("Original", imgOriginal); //show the original image
if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
this is running display window

Arduino TimeAlarms are not working sometimes

i use an Arduino Mega compatible board (SainSmart Mega 2560 R3 ATmega2560-16AU) which has a rtc module attached (v1.1 ds1307rtc) and working on it with the attached code. I have used the TimeAlarms library (downloaded it from http://www.pjrc.com/teensy/td_libs_TimeAlarms.html) to have an alarm every hour. The alarms should occur at different minutes every hour, but for testing i have set them all to the 12th minute.
This code is waiting for a correct time, which i can set via usb, serial interface. The code is working fine most of the times. But sometimes the alarm is not activated and my leds are not flashing. I don't know why and when this happens, i didn't any changes between the working flashing and not working. Also i can't see any hours where it doesn't working correct, afaik it works correct, but fails sometimes. If it failes, it looks like all hours after the failing hour are also failing and no alarm is triggered.
I know about the restriction of 6 alarms in TimeAlarms.h and set the variable dtNBR_ALARMS in this file to 25.
As you can see i have implemented a printTime function which print out the rtc and the system time and always both are correct.
Has anyone an idea what i am doing wrong or why it fails sometimes?
#include <Time.h>
#include <TimeAlarms.h>
#include <Wire.h>
#include <DS1307RTC.h>
tmElements_t tm;
int pwm_2 = 2;
int pwm_3 = 3;
int pwm_4 = 4;
int pwm_5 = 5;
int pwm_6 = 6;
int pwm_7 = 7;
int pwm_8 = 8;
int pwm_9 = 9;
int pwm_10 = 10;
int pwm_11 = 11;
int pwm_12 = 12;
int pwm_13 = 13;
//delay in the for loops
int dly = 120;
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
while (!Serial) ; // wait for serial
setSyncProvider(RTC.get); // the function to get the time from the RTC
RTC.read(tm);
setTime(tm.Hour,tm.Minute,tm.Second,tm.Day,tm.Month,tm.Year);
printTime();
//wait for time input via serial, time must be set at every system boot
while(tmYearToCalendar(tm.Year) < 2014) {
Serial.println("wait in time loop, you have to set a time, current time is not correct:");
printTime();
if (Serial.available()) {
time_t t = processSyncMessage();
Serial.println("wait in time loop");
if (t != 0) {
RTC.set(t); // set the RTC and the system time to the received value
setTime(t);
Serial.println("time is succesfully set to");
printTime();
break;
}
}
delay(1000);
}
Serial.println("Time is already set to:");
printTime();
//set alarms for all hours in UTC, not in CET
Alarm.alarmRepeat(0, 12, 0, shotAlarm);
Alarm.alarmRepeat(1, 12, 0, shotAlarm);
Alarm.alarmRepeat(2, 12, 0, shotAlarm);
Alarm.alarmRepeat(3, 12, 0, shotAlarm);
Alarm.alarmRepeat(4, 12, 0, shotAlarm);
Alarm.alarmRepeat(5, 12, 0, shotAlarm);
Alarm.alarmRepeat(6, 12, 0, shotAlarm);
Alarm.alarmRepeat(7, 12, 0, shotAlarm);
Alarm.alarmRepeat(8, 12, 0, shotAlarm);
Alarm.alarmRepeat(9, 12, 0, shotAlarm);
Alarm.alarmRepeat(10, 12, 0, shotAlarm);
Alarm.alarmRepeat(11, 12, 0, shotAlarm);
Alarm.alarmRepeat(12, 12, 0, shotAlarm);
Alarm.alarmRepeat(13, 12, 0, shotAlarm);
Alarm.alarmRepeat(14, 12, 0, shotAlarm);
Alarm.alarmRepeat(15, 12, 0, shotAlarm);
Alarm.alarmRepeat(16, 12, 0, shotAlarm);
Alarm.alarmRepeat(17, 12, 0, shotAlarm);
Alarm.alarmRepeat(18, 12, 0, shotAlarm);
Alarm.alarmRepeat(19, 12, 0, shotAlarm);
Alarm.alarmRepeat(20, 12, 0, shotAlarm);
Alarm.alarmRepeat(21, 12, 0, shotAlarm);
Alarm.alarmRepeat(22, 12, 0, shotAlarm);
Alarm.alarmRepeat(23, 12, 0, shotAlarm);
// declare pin 2-13 to be an output:
pinMode(pwm_2, OUTPUT); //red
pinMode(pwm_3, OUTPUT); //blue
pinMode(pwm_4, OUTPUT); //green
pinMode(pwm_5, OUTPUT); //red
pinMode(pwm_6, OUTPUT); //blue
pinMode(pwm_7, OUTPUT); //green
pinMode(pwm_8, OUTPUT); //red
pinMode(pwm_9, OUTPUT); //blue
pinMode(pwm_10, OUTPUT); //green
pinMode(pwm_11, OUTPUT); //red
pinMode(pwm_12, OUTPUT); //blue
pinMode(pwm_13, OUTPUT); //green
}
void shotAlarm() {
Serial.println("SHOTALARM");
analogWrite(pwm_2, 255);
analogWrite(pwm_5, 255);
analogWrite(pwm_8, 255);
analogWrite(pwm_11, 255);
analogWrite(pwm_3, 255);
analogWrite(pwm_4, 255);
analogWrite(pwm_6, 255);
analogWrite(pwm_7, 255);
analogWrite(pwm_9, 255);
analogWrite(pwm_10, 255);
analogWrite(pwm_12, 255);
analogWrite(pwm_13, 255);
for(int a = 0; a < 60; a = a+1) {
for (int i = 0; i < 255; i = i + 1) {
analogWrite(pwm_2, i); //red
analogWrite(pwm_5, i); //red
analogWrite(pwm_8, i); //red
analogWrite(pwm_11, i); //red
delay (5);
}
for (int i = 255; i > 0; i = i - 1) {
analogWrite(pwm_2, i); //red
analogWrite(pwm_5, i); //red
analogWrite(pwm_8, i); //red
analogWrite(pwm_11, i); //red
delay (5);
}
}
}
void loop() {
Alarm.delay(0);
Serial.println("new loop");
printTime();
analogWrite(pwm_2, 0);
analogWrite(pwm_5, 0);
analogWrite(pwm_8, 0);
analogWrite(pwm_11, 0);
analogWrite(pwm_3, 255);
analogWrite(pwm_4, 255);
analogWrite(pwm_6, 255);
analogWrite(pwm_7, 255);
analogWrite(pwm_9, 255);
analogWrite(pwm_10, 255);
analogWrite(pwm_12, 255);
analogWrite(pwm_13, 255);
for (int i = 255; i > 0; i = i - 1) {
analogWrite(pwm_4, i); //green
analogWrite(pwm_7, i); //green
analogWrite(pwm_10, i); //green
analogWrite(pwm_13, i); //green
Alarm.delay (dly);
}
for (int i = 0; i < 255; i = i + 1) {
analogWrite(pwm_2, i); //red
analogWrite(pwm_5, i); //red
analogWrite(pwm_8, i); //red
analogWrite(pwm_11, i); //red
Alarm.delay (dly);
}
for (int i = 255; i > 0; i = i - 1) {
analogWrite(pwm_3, i); //blue
analogWrite(pwm_6, i); //blue
analogWrite(pwm_9, i); //blue
analogWrite(pwm_12, i); //blue
Alarm.delay (dly);
}
for (int i = 0; i < 255; i = i + 1) {
analogWrite(pwm_4, i); //green
analogWrite(pwm_7, i); //green
analogWrite(pwm_10, i); //green
analogWrite(pwm_13, i); //green
Alarm.delay (dly);
}
for (int i = 255; i > 0; i = i - 1) {
analogWrite(pwm_2, i); //red
analogWrite(pwm_5, i); //red
analogWrite(pwm_8, i); //red
analogWrite(pwm_11, i); //red
Alarm.delay (dly);
}
for (int i = 0; i < 255; i = i + 1) {
analogWrite(pwm_3, i); //blue
analogWrite(pwm_6, i); //blue
analogWrite(pwm_9, i); //blue
analogWrite(pwm_12, i); //blue
Alarm.delay (dly);
}
Alarm.delay(0);
}
void printTime() {
if (RTC.read(tm)) {
Serial.print("Ok, RTC Time = ");
print2digits(tm.Hour);
Serial.write(':');
print2digits(tm.Minute);
Serial.write(':');
print2digits(tm.Second);
Serial.print(", Date (D/M/Y) = ");
Serial.print(tm.Day);
Serial.write('/');
Serial.print(tm.Month);
Serial.write('/');
Serial.print(tmYearToCalendar(tm.Year));
Serial.println();
}
else {
if (RTC.chipPresent()) {
Serial.println("The DS1307 is stopped. Please run the SetTime");
Serial.println("example to initialize the time and begin running.");
Serial.println();
}
else {
Serial.println("DS1307 read error! Please check the circuitry.");
Serial.println();
}
}
Serial.print("Ok, System Time = ");
print2digits(hour());
Serial.write(':');
print2digits(minute());
Serial.write(':');
print2digits(second());
Serial.print(", Date (D/M/Y) = ");
Serial.print(day());
Serial.write('/');
Serial.print(month());
Serial.write('/');
Serial.print(year());
Serial.println();
}
void print2digits(int number) {
if (number >= 0 && number < 10) {
Serial.write('0');
}
Serial.print(number);
}
/* code to process time sync messages from the serial port */
#define TIME_HEADER "T" // Header tag for serial time sync message
unsigned long processSyncMessage() {
unsigned long pctime = 0L;
const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
if(Serial.find(TIME_HEADER)) {
pctime = Serial.parseInt();
return pctime;
if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
pctime = 0L; // return 0 to indicate that the time is not valid
}
}
return pctime;
}
For all who read this thread later:
I found the mistake in my code. The following line was wrong:
setTime(tm.Hour,tm.Minute,tm.Second,tm.Day,tm.Month,tm.Year);
The correct version is:
setTime(tm.Hour,tm.Minute,tm.Second,tm.Day,tm.Month,tmYearToCalendar(tm.Year));
Unfortunately i forgot to convert the year value to the expected format. The code from above is working very fine with this correction. I checked the alarms for more then a week and it is working very stable.
Thanks all for their help.
One thing to mention is that in the read me of the TimerAlarm library, it says you can only define up to 6 alarms only, but that can be changed inside the library by dtNBR_ALARMS field. The number ofcourse is restricted by ram but you can easily add that since the Arduino mega has a significantly large SRAM. So this might be worth looking at if you experience further problems with the alarms.

Resources