Serial communication (for Arduino) using Visual Studio 2010 and C - visual-studio-2010

I'm facing a slight issue at the moment. I am currently doing some video (image) detection and tracking using Microsoft Visual Studio 2010 Professional and OpenCV, and the result (of the vision system) is to control additional hardware via the Arduino platform.
My code for the vision system works 100% and code on Arduino also works 100%, but I'm having an issue communicating via C / C++ from the PC to the Arduino board. (Can not use Visual Basic, etc.)
Specifications at the moment: Windows 7 platform, Visual Studio 2010, OpenCV 2.2.0, Arduino 0022, Arduino Mega board, 2 x USB to serial converters for simulations.
My code does not seem to even be functioning. I am, however, following the example below by #opc0de. But to illustrate my point the code below doesn't seem to work (never states COM open (yes, I change to the write ports)). (Connect two serial cables to each other plugged into two different COM ports hyperterminal, realterm, etc. work 100%. My code and the code below don't seem to work at all). (My code is +- 800 lines long and I don't feel like posting as the COMs section is very similar to below). I just want serial commynication to be working.
All I want from the COMs is the ability to send a text string, "x=### y=###" so even a simple piece of code will do (like below) (I want to read at a later stage, but I am not worried it at the moment)
Link to code: Stack Overflow - opc0de
#include <Windows.h>
#include <stdio.h>
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
char test[] = "Hello";
HANDLE hDevice = CreateFile(L"COM2",GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,0);
if (hDevice !=INVALID_HANDLE_VALUE)
{
printf("Port opened! \n");
DCB lpTest;
GetCommState(hDevice,&lpTest);
lpTest.BaudRate = CBR_9600;
lpTest.ByteSize = 8;
lpTest.Parity = NOPARITY;
lpTest.StopBits = ONESTOPBIT;
SetCommState(hDevice,&lpTest);
DWORD btsIO;
WriteFile(hDevice,test,strlen(test),&btsIO,NULL);
CloseHandle(hDevice);
}
_getch();
return 0;
}

Check your code to make sure it works separately:
First, use a COM logger. The old and good Terminal from MS is the worst, but I cannot remember another one right now. See if your C++ code sends something there. If no, make it work :) If yes, debug commnication problems with an Arduino. Make a simple logger on Arduino to see what you receive on the other part and how you handle it.

Related

IOKit inclusion in c++ project in xcode

I am trying to write a program that uses IOAudioControl.h file in the IOKit, so that I learn dealing with IOKit directly without using Apple's APIs. Whenever I run a simple file like below I got tons of errors in IOAudioControl.h
#include <IOKit/audio/I0AudioControl.h>
#include <iostream>
int main(int argc, const char * argv]) (
{
// insert code here.
std: :cout << "Hello, world! \n"
return 0:
}
Here is a screenshot for my build settings
enter image description here
and here is a screenshot for the errors
enter image description here
IOAudioControl is a class that exists in the macOS Kernel (and its API is available to kexts), and it is also accessible from DriverKit extensions (dext) via the IOUserAudioControl API in AudioDriverKit.
From your code sample it looks like you're trying to include the kernel header file in a regular user space program. This will not work, kernel objects are not accessible from user space in this way.
You do not specify what you are ultimately trying to achieve, but:
If you are trying to implement an audio device driver, use either the Core Audio Server Plugin API or build your driver as a DriverKit extension. (Most kinds of audio kernel extensions are deprecated.)
If you want to access and modify the controls of an existing audio device in the system, use the Core Audio API.
If you wish to enumerate the kernel's IOAudioControl objects from user space, use the IOKit framework's service iteration APIs from your program.

Visual Studio 2013 Express MFC program could not work after Windows 10 update to 1903

These days I upgrade to Windows 10 to 1903, however, after that, my MFC program soon disappears after running up. The solution is composed of an MFC project and a DLL project, they are static linked.
Thank you all for paying attention to my question. So far the issue disappear, and below is the story.
1) I modified my code to dynamic link.
2) I got the message of System AccessViolationException when calling the second API of DLL.
3) I found think link. Programs randomly getting System.AccessViolationException
4) In the post, someone mentioned that change platform setting may solve it
5) So I change my platform setting to x64
6) It works
7) I continue to finish my work base on x64 and everything looks OK
8) However I was required to provide x32 version Orz
9) So I have to dig this question as very first priority
10) However, base on the modified source code, now x32 is able to run
Sorry there is not so many useful information.....
There is more information.
I tried to install VS2013 Express at another Win7 64bit PC, which is able to re-produce the phenomenon. It does not matter x86 or Win32 this time.
When Running "Local Windows Debugger," (or use hostkey of: F10, F11, F5)
the debug interface soon finish, with below log:
The program '[2576] test.exe: Native' has exited with code 1 (0x1).
However, in my code did not write any pattern like "return 1"
Below is the main function built-in
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew Form_main());
return 0;
}

Qt Creator: start programm with processor affinity

I need to debug an application for an embedded device. A problem with this application might be timing related so I try to decrease the speed of execution on my development machine.
I have a setup which is quite useful but needs a little tweaking for convenience, basically I followed the advice given here:
https://blogs.msdn.microsoft.com/vijaysk/2012/10/26/tools-to-simulate-cpu-memory-disk-load/
Linked in the article there is the tool "CPUSTRES.exe" which generates high CPU usage. To prevent the tool to eat up all my CPU I start it like so (the tool will only run on the 8th core):
START "Stress" /affinity 0x80 /HIGH CPUSTRES.EXE
Then I start the debugging session in the Qt Creator (version 4.1.0). Using the windows task manager I can set the same processor affinity for the application as the stress tool has. Doing so gives me an app that more or less sluggish like on the embedded device but the debugger and all other apps behave nicely.
I find it a little inconvenient to set the affinity in the task manager manually. I want this application always only on the same single core. This is only for debugging purposes, so would not like to change this in code. How can I achieve that?
While I managed to start the application under test with the desired processor affinity I would not recomment it. It does not make my life easier. Instead I would recommend to set the affinity in code as commented by #ni1ight.
The easy way (that was not asked for):
#include <windows.h>
int main(int argc, char* argv[]) {
#ifdef _DEBUG
DWORD_PTR processAffinityMask = 1 << 7;
HANDLE process = GetCurrentProcess();
SetProcessAffinityMask(process, processAffinityMask);
#endif
[...]
The other way to do it (that is not reasonable):
View your project's settings
add a new run configuration and choose 'custom executeable'
As the executeable choose a new 'cmd' file with the command as it is in the question (START "" /affinity 0x80 AppUnderTest.EXE). It should be possible to provide the application path as an argument to the cmd but I did not try this.
Then it is possible to start the application from the creator but debugging is not possible.
Attach the debugger to the running process to debug the application.

MongoDB on Windows slow *sometimes* using tailable cursors as message queue

We are completing a generic service-bus implementation on C, with clients for C#, Delphi, PL/SQL and PHP.
The library works great, we have awesome performance for our bus unless the MongoDB database is running on Windows (tested on 2008 R2, 2003 and 7) and there's no other "special" program running.
Out test do the following:
Program A sends a message on a capped collection
Program B tails on the message queue collection and "wakes up" when message appear using a cursor with awaitData param set to true
When Program B wakes up, prepares a messsage and sends a response to Program A inserting a document on a specific collection by Program A
Program A was already waiting on the second "response" collection and gets awaken when Program B (the producer) sent the response back
Loop ends there
Our testing program counts the loop and reports performance on a console application compiled with Visual Studio 2010.
We run this everything on one machine, or using a different machine for MongoDB and running consumer and producer on the same machine.
We run this on Windows 2008R2, Windows 2003 and Windows 7.
For 2008R2 we used the special mongo build for that OS, while for 2003 and 7 we used the "legacy" 64 bits build.
In a clean OS, with no programs running, our test performs about 32-50 roundtrips per second, which is a lousy performance compared to the "good" results we get when everything goes full speed.
Now, here comes the strange thing:
When starting certain application on the same machine where the mongo database runs, our tests speed up to about 450/sec (when running over loopback everything on the same machine) to about 300/sec when consumer and producer run on one machine, and mongodb in another machine going over the network.
The reason we never noticed this problem consistently before was because pretty much all the time we had in our development vms Visual Studio open, and Visual Studio is a program that acts as a "mongodb accelerator" (I know this sounds ridiculous, please don't bash me on this statement).
At first we noticed this issue "randomly" essentially when running our tests without VS open. So we tend to blame it on the underlying SAN where vmware runs, or the vm hosts, or cosmic rays or the NSA snooping on our program.
This was until we figured out finally the correlation between VS open at the same time while we were running tests, and narrowed down to the following:
MongoDB running on a Windows system (as console OR as service), virtual or physical versions 2008R2, 2003 or 7 will run slow a pattern of receiving data on a capped collection and waking up a tailing cursor then sending a response back to the consumer on another capped collection in the same way unless you simply start a program such as Visual Studio, Delphi XE4, Google Chrome browser, CrystalDiskMark disk I/O testing program (other program may speed up Mongo too). Then mongodb speeds up on full order of magnitude the pattern mentioned before.
We could not find exactly what these programs have in common that may cause the issue.
At this point we are stunned by the issue, I even reviewed the MongoDB code used for tailable cursor, but didn't find anything that smells as potentially causing a problem. The code pretty much spins for a max of 4 seconds waiting for data to appear, besides the suspicious "sleep" call on every loop, there was nothing else eye catching.
Is it possible that certain programs end up causing Sleep() Windows API call to behave differently? And that makes mongo do this operations on tailable cursor slower??
We think something is indeed "slowing down" because also the CPU utilization profiles goes down, like mongodb is literally "waiting" for something when it's running slow.
I know this pattern works fine on unix/linux based systems, I tried the same codebase on a Mac with no issues, so this horribly smells as a Windows issue.
Anyone else experienced a similar issue out there?
Found the source of the problem.
MongoDB calls straight Sleep() Windows API function, even for Sleep times lesser than 15ms.
Because of the default Windows minimum resolution, anything less than that (at least on Windows 2008 R2, Windows 2003 and Windows 7) will sleep for at least 15ms no matter what.
Simple solution in MongoDb is updating time_support.cpp from this:
void sleepmillis(long long s) {
fassert(16228, s <= 0xffffffff );
Sleep((DWORD) s);
}
to:
extern "C" unsigned int __stdcall timeBeginPeriod( unsigned int ms );
extern "C" unsigned int __stdcall timeEndPeriod( unsigned int ms );
// Notice bellow the arbitrary nature of 50ms set as the "minimum" timer resolution
// There seems to be no complete agreement on that *is* the default timer resolution in Windows.
// To be on the "safe side" let's use 50ms
#define BELLOW_WINDOWS_MIN_RESOLUTION(s)(s > 0 && s < 50)
void sleepmillis(long long s) {
fassert(16228, s <= 0xffffffff );
// When our waiting period falls bellow Windows min resolution, let's set resolution
// to 1 ms. Note that this change may effect all kernel scheduler thread operations.
// Apparently this changes the Windows kernel "quantum" length
// see http://msdn.microsoft.com/en-us/library/windows/desktop/dd757624(v=vs.85).aspx
// Applications such as Google Chrome seem to do this during the life of Chrome, that's why
// running apps which do this "accelerate" certain mongo operations that depending on proper
// Sleep() resolution on Windows
if(BELLOW_WINDOWS_MIN_RESOLUTION(s)) timeBeginPeriod(1);
Sleep((DWORD) s);
if(BELLOW_WINDOWS_MIN_RESOLUTION(s)) timeEndPeriod(1);
}

winUSB error (possible .inf issue)

I would really really appreciate some help with winUSB.
I followed all the steps that were listed in msdn website
http://msdn.microsoft.com/en-us/library/windows/hardware/hh450799(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/hardware/ff540174(v=vs.85).aspx
I tried to run it on Windows 7 with Visual Studio 2010. Even though it compiles with no errors, I cannot pass the function
SetupDiEnumDeviceInfo, and it errors out (I think error #259).
I don't know how to pass this error.
However I am not sure of the few steps in the process:
What does msdn talk about with "A signed catalog file for the package. This file is required to install WinUSB on x64 versions"? What is a signed catalog package? How do I set this?
It also talks about making some directory (For example, c:\UsbDevice) to put the .inf file in there ! But how does my VS project know that I am pointing to c:\UsbDevice, and how does it know what the name of the ".inf' file should be? what should I call the .inf file? And how to point the project to it?
Inside the .inf file there are two GUID numbers. I can get the Class GUID number by going to the Device Manager. But how do I set the Device Interface GUID?
Please help.
Is is possible that the error that I am getting is because I don't have one of the following items set up correctly?
Thanks,
--Rudy
I developed an application about 2 years ago that I needed to use WinUSB, it's not fresh in my mind but looking at my code now I can see that I did use this function: SetupDiEnumDeviceInfo, but as I remember it wasn't a problem for me.
As you probably know, the WinUSB is an API of Windows for you to communicate with an usb hardware. The hardware must have it's driver already, so, you have to know the GUID of your device
Answering your steps:
1. Signed catalog is the .cat file generated from an inf, you can genarate it using inf2cat.exe, it's somwhere in your machine. This is just a step for signing your winusb driver. To sign it you will need to submit your .inf and the .cat files for the WHQL (windows hardware quality labs) http://www.microsoft.com/whdc/whql/ , this is not important at this moment, I've never signed my WinUSB driver, and it works in the x64 machines with a inelegant warning saying that my WinUSB driver might be dangerous (despite it's not!)
2. The application you are developing doens't need to know where the .inf file is, the .inf file is meant to install the WinUSB driver, the application will communicate with the driver trough the GUID number of the device after the driver is properly installed. Here is part of the code that is necessary to connect to the device after the WinUSB driver is correctly installed.
LPGUID _lpGuid = (LPGUID) malloc (sizeof(GUID));
HRESULT result = CLSIDFromString (L"{A54E04AD-E06A-4A03-95BB-25AACC4E6CCA}", _lpGuid);
...
bResult = SetupDiEnumDeviceInterfaces(deviceInfo,
NULL,
_lpGuid,
0,
&interfaceData); //If the function succeeds
//the return value is nonzero.
// [1]
deviceInfo = SetupDiGetClassDevs(_lpGuid,
NULL, NULL,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfo == INVALID_HANDLE_VALUE)
{
//lblDispStatus->Caption = "Erro 1 - deviceInfo";
return false;
}
// [2]
interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
bResult = SetupDiEnumDeviceInterfaces(deviceInfo,
NULL,
_lpGuid,
0,
&interfaceData); //If the function succeeds
//the return value is nonzero.
InterfaceData is passed as reference, so you will have the ability to call the next function, that is SetupDiGetDeviceInterfaceDetail
3.Who developed the driver? He must know the GUIDs you need.
All I know from WinUSB I fount at the poor WinUSB documentation, you will need tons of patiante to read all their messy information. And for your unlucky, it's not fresh in my mind right know, I would have to take a deep look at this subject to help you more.
This page seems important at the point you are, take a look at this: http://msdn.microsoft.com/en-us/library/windows/hardware/ff540174%28v=vs.85%29.aspx

Resources