STM32F407 Stucks on UART Interrupt - stm32f4discovery

I got a problem with my STM32F407 and the UART.
I want to receive data with USART3 in interrupt mode.
my primary code is that:
UART_HandleTypeDef huart3;
uint8_t buffer[16];
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart == &huart3)
{
if(HAL_UART_Receive_IT(&huart3, uartData, sizeof(uartData)) != HAL_OK)
{
uint32_t error = HAL_UART_GetError(&huart3);
}
}
}
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
uint32_t error = huart->ErrorCode;
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init()
MX_USART3_UART_Init();
MX_NVIC_Init();
HAL_UART_Receive_IT(&huart3, uartData, sizeof(uartData));
while (1)
{
osDelay(1);
}
}
i send over my serial console the text 'test' until the buffer is full and interrupt is fired.
my interrupt is fired one time and then no more, HAL_UART_Receive_IT gives me HAL_OK back, but the
ErrorCallback is fired after the with HAL_UART_RxCpltCallback with error 0x8, this says that are a UART Overrun Error...
Okay.. i see no blocking function that can be overrun the UART, or is my function wrong?
it gives many examples with this code to use the UART, who is the problem?
Thank you!
Daniel

Related

How to use hook to hijack cudaSetDevice and modify device id?

I want to hijack cudaSetDevice with hook(LD_PRELOAD) and modify the device id. After the hijacking is successful, the gpu task submission will be wrong.
I tried to hijack the cuCtxCreate function in the driver api, but I couldn't hijack it. The same method hijacks the cuDevicePrimaryCtxRetain function, which can be hijacked and an error will occur when modifying the device id.
// cuda 9.0 cuda runtime api
typedef int(*cuda_set_device_fp)(int);
// define dynamic library same name function
int cudaSetDevice(int device)
{
static void *handle = NULL;
static cuda_set_device_fp orig_cuda_set_device = NULL;
if( !handle )
{
handle = dlopen("libcuda.so", RTLD_LAZY);
orig_cuda_set_device = (cuda_set_device_fp)dlsym(handle, "cudaSetDevice");
}
device = 1;
printf("oops!!! hack function invoked. device = %d\n", device);
return cudaSetDevice(device);
}
The hijacking succeeds, mapping the user to the gpu task on device 0 and re-mapping to device 1.
In the provided source code at the end of your function you recursively call your function again, instead of calling orig_cuda_set_device with the modified device id. This causes infinite recursion.

BluetoothLeScanner could not find callback wrapper

Because of I had problems with Bluetooth on Android Lollipop, I have tried to change the scanner method.
So I have tried to use the new package.
In the previous version, I called startScan(mLeScanCallback) and everything works but now, when I call startScan(mScanCallback) I have the error: "D/BluetoothLeScanner: could not find callback wrapper".
No devices are found and the ListAdapter, I use to show the devices, is empty.
The comment lines are the previous code (and it worked!).
This my code:
public class Selection extends ListActivity implements ServiceConnection {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
// Initializes a Bluetooth adapter through BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
getApplicationContext().bindService(new Intent(this, MetaWearBleService.class), this, Context.BIND_AUTO_CREATE);
}
private void scanLeDevice(final boolean enable) {
final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (enable) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
//mBluetoothAdapter.stopLeScan(mLeScanCallback);
bluetoothLeScanner.stopScan(mScanCallback);
setListAdapter(listAdapter);
}
}, SCAN_PERIOD);
//mBluetoothAdapter.startLeScan(mLeScanCallback);
bluetoothLeScanner.startScan(mScanCallback);
} else {
//mBluetoothAdapter.stopLeScan(mLeScanCallback);
bluetoothLeScanner.stopScan(mScanCallback);
setListAdapter(listAdapter);
}
}
private ScanCallback mScanCallback =
new ScanCallback() {
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
listAdapter.addDevice(device);
}
});
}
};
Instead the ListAdapter extends BaseAdapter and use a ViewHolder. If it necessary, I post it.
So what does it mean "D/BluetoothLeScanner: could not find callback wrapper"? What is it wrong?
Otherwise how I can't resolve the problem of scanning with the Android Lollipop?
In Lollipop I have often errors about BluetoothGatt. I don't know to minized it (or solve it).
Thanks
The log message D/BluetoothLeScanner: could not find callback wrapper appears whenever Android's bluetooth scanning APIs are told top stop scanning for an app when they think scanning has not started. You can see this by looking at the source code of Android's BluetoothLeScanner here.
This is usually safe to ignore as there are lot of reasons that scanning my not have actually started (it was already stopped, bluetooth is off, permissions have not been granted, etc.) Client software that does scanning often stops scanning on a timer regardless of whether it has been successfully started, or whether it was manually stopped before the timer goes off. Android's example code (and the code shown above) does exactly this, often causing these log messages to show up.
If you really want to minimize these messages, you need to keep track of whether scanning actually started and only stop scanning if it actually did. Unfortunately, you don't get a return code if scanning starts successfully, and you only get an asynchronous callback to onScanFailed(errorCode) if you cannot start successfully. So one approach would be to set scanStartCount++; when you call start scan, and set scanStartCount--; when you get a callback to onScanFailed(errorCode). Then when your timer goes off to stop the scan, only actually stop it if the scanStartCount > 0.
Keep in mind that you can only minimize these messages coming from your application. Other applications on the phone doing bluetooth scanning may be causing these messages to be emitted as well.
for the same problem
I had just add permissions :
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.
Manifest.permission.
Manifest.permission.BLUETOOTH_PRIVILEGED,
in your activity call this methods :
checkPermissions(MainActivity.this, this);
public static void checkPermissions(Activity activity, Context context){
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH_PRIVILEGED,
};
if(!hasPermissions(context, PERMISSIONS)){
ActivityCompat.requestPermissions( activity, PERMISSIONS, PERMISSION_ALL);
}
}
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
hope it's help
I had the same problem with android m.It was due to lack of permissions.Make sure you go to settings and grant location permission to your app
for location permission, only ACCESS_FINE_LOCATION worked. ACCESS_COARSE_LOCATION had the same problem.

Overriding WP8 Navigation - crash in PhoneApplicationPage

I'm trying to do something that's arguably a bad idea, but I think it's still possible. I'm trying to override how WP8 handles the Back Button and implement it myself. I theorize that if I:
The Plan
Only ever create one "Frame" and "Page" in the entire application
Always handle PhoneApplicationPage.BackKeyPress myself unless they were about to back out of the application.
The Repro
Here's a sample project that has the crash
The code
..then it should work. However, my attempts are being thwarted by Windows Phone. Here's the code:
// This basically happens on PhoneApplicationService.OnLaunched
_viewModelChanged.StartWith(ViewModel).Where(x => x != null).Subscribe(vm => {
var page = default(IViewFor);
var frame = RootVisual as PhoneApplicationFrame;
// Find the initial PhoneApplicationPage for the app
page = RxApp.GetService<IViewFor>("InitialPage");
// Depending on how we're being signalled (i.e. if this is cold start
// vs. resume), we need to create the PhoneApplicationFrame ourselves
if (frame == null) {
frame = new PhoneApplicationFrame() {
Content = page,
};
}
page.ViewModel = vm;
var pg = page as PhoneApplicationPage;
if (pg != null) {
pg.BackKeyPress += (o, e) => {
if (ViewModel.Router.NavigationStack.Count <= 1 ||
ViewModel.Router.NavigateBack.CanExecute(null)) {
return;
}
e.Cancel = true;
ViewModel.Router.NavigateBack.Execute(null);
};
}
// Finally, set Application.RootVisual
RootVisual = frame;
});
Sadness
This works great, until right after this code executes, where a DispatcherItem queued by the framework crashes the app:
System.NullReferenceException occurred
Message: A first chance exception of type 'System.NullReferenceException' occurred in Microsoft.Phone.ni.dll
Microsoft.Phone.ni.dll!Microsoft.Phone.Controls.PhoneApplicationPage.InternalOnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) Unknown
Microsoft.Phone.ni.dll!Microsoft.Phone.Controls.PhoneApplicationPage.Microsoft.Phone.Controls.IPhoneApplicationPage.InternalOnNavigatedFromX(System.Windows.Navigation.NavigationEventArgs e) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.NavigationService.RaiseNavigated(object content, System.Uri uri, System.Windows.Navigation.NavigationMode mode, bool isNavigationInitiator, Microsoft.Phone.Controls.IPhoneApplicationPage existingContentPage, Microsoft.Phone.Controls.IPhoneApplicationPage newContentPage) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.NavigationService.CompleteNavigation(System.Windows.DependencyObject content, System.Windows.Navigation.NavigationMode mode) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.NavigationService.ContentLoader_BeginLoad_Callback(System.IAsyncResult result) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(System.AsyncCallback userCallback, System.Windows.Navigation.PageResourceContentLoader.PageResourceContentLoaderAsyncResult result) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.PageResourceContentLoader.BeginLoad.AnonymousMethod__0(object args) Unknown
[Native to Managed Transition]
mscorlib.ni.dll!System.Delegate.DynamicInvokeImpl(object[] args) Unknown
System.Windows.ni.dll!System.Windows.Threading.DispatcherOperation.Invoke() Unknown
System.Windows.ni.dll!System.Windows.Threading.Dispatcher.Dispatch(System.Windows.Threading.DispatcherPriority priority) Unknown
System.Windows.ni.dll!System.Windows.Threading.Dispatcher.OnInvoke(object context) Unknown
System.Windows.ni.dll!System.Windows.Hosting.CallbackCookie.Invoke(object[] args) Unknown
System.Windows.RuntimeHost.ni.dll!System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(System.IntPtr pHandle, int nParamCount, System.Windows.Hosting.NativeMethods.ScriptParam* pParams, System.Windows.Hosting.NativeMethods.ScriptParam* pResult) Unknown
So, I've solved this - my code was problematic because I didn't grok how WP8 works :) Here's what I understand now, which may also be wrong but I'll write it anyways
How your WP8 app is initialized:
The OS creates your App class via rehydrating App.xaml.cs
This means, your constructor gets run, and as part of that, you create a PhoneApplicationFrame
Creating a PhoneApplicationFrame seems to also set a global static variable (same thing happens with creating PhoneApplicationService in the App.xaml, it sets PhoneApplicationService.Current).
NavigationService then attempts to recreate a XAML View via a resource string (i.e. '/MainPage.xaml'). Either it will recreate the one that was previously tombstoned, or if not, it defaults to the one in your WMAppManifest (this is the part I didn't understand).
PhoneApplicationFrame.Navigated gets called by NavigationService - this is where you can actually start doing stuff, including most importantly, setting Application.RootVisual, which will send the Loading... screen away
PhoneApplicationService.Launched or PhoneApplicationService.Activated finally fires, once basically everything is set up, depending how your app was woken up.
Found the issue. Well, the tip of the iceberg.
The code of the InternalOnNavigatedFrom method is:
internal override void InternalOnNavigatedFrom(NavigationEventArgs e)
{
PhoneApplicationPage content = e.Content as PhoneApplicationPage;
string str = ((content == null) || (content.Title == null)) ? string.Empty : content.Title;
PerfUtil.BeginLogMarker(MarkerEvents.TH_ONNAVIGATEDFROM_PAGE, string.Format("{0},{1},{2}", (base.Title == null) ? "" : base.Title, e.NavigationMode, str));
this.OnNavigatedFrom(e);
PerfUtil.EndLogMarker(MarkerEvents.TH_ONNAVIGATEDFROM_PAGE, string.Format("{0},{1},{2}", (base.Title == null) ? "" : base.Title, e.NavigationMode, str));
DeviceStatus.KeyboardDeployedChanged -= new EventHandler(this.OnKeyboardDeployedChanged);
Task rootTask = ApplicationHost.Current.RootTask;
rootTask.OnVisibleRegionChange = (ITask.VisibleRegionChanged) Delegate.Remove(rootTask.OnVisibleRegionChange, new ITask.VisibleRegionChanged(this.OnVisibleRegionChange));
Task task2 = ApplicationHost.Current.RootTask;
task2.OnSipVisibilityChange = (ITask.SipVisibilityChange) Delegate.Remove(task2.OnSipVisibilityChange, new ITask.SipVisibilityChange(this.OnSipVisibilityChange));
this._lastSipHeight = 0.0;
this._dictionary = null;
}
After a bit of debugging, I concluded that neither e or Application.Current.RootTask were null. After scratching my head, I looked at the code of the KeyboardDeployedChanged event handler:
public static event EventHandler KeyboardDeployedChanged
{
[SecuritySafeCritical] add
{
if (KeyboardDeployedSubscription == null)
{
KeyboardDeployedSubscription = new SubscriptionHandler(DeviceTypes.KeyBoard);
}
KeyboardDeployedSubscription.Changed += value;
}
[SecuritySafeCritical] remove
{
KeyboardDeployedSubscription.Changed -= value;
}
}
This code is poorly written. If the remove part of the handler is called before the add, KeyboardDeployedSubscription will be null and an exception will be raised. To test my theory, I subscribed to the event in App's constructor:
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
DeviceStatus.KeyboardDeployedChanged += (sender, e) => { };
And sure enough, the exception was gone. Now, to understand why your code is triggering this issue, I backtraced to which part of the framework is supposed to subscribe to the event. The only candidate is the InternalOnNavigatedTo method.
Therefore, your issue is that OnNavigatedFrom is called even though OnNavigatedTo was never called.
Since you are strungling with the built-in auto navigation of Windows Phone to the page defined in WMAppManifest.xml, I tried to remove the auto navigation and it basically worked (no exception).
I just replaced
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
with
<DefaultTask Name="_default" />
Not sure if this solves your problem but it at least doesn't crash anymore.

Proper use of cudaDeviceReset()

Since I'm having suspicions the "black box" (GPU) is not shutting down cleanly in some larger code (others perhaps too), I would include a cudaDeviceReset() at the end of main(). But wait! This would Segmentation fault all instances of classes statically created in main() with non-trivial CUDA code in destructors, right? E.g.
class A {
public:
cudaEvent_t tt;
cudaEvent_t uu;
A() {
cudaEventCreate(&tt);
cudaEventCreate(&uu);
}
~A(){
cudaEventDestroy(tt);
cudaEventDestroy(uu);
}
};
instantiated statically:
int main() {
A t;
cudaDeviceReset();
return 0;
}
segfaults on exit. Question: is perhaps cudaDeviceReset() invoked automatically on exit from main()?
Otherwise whole useful code of main() should be shifted to some run(), and cudaDeviceReset() should be the as last command in main(), right?
As indicated by Talonmies, the destructor of class A is called after the cudaDeviceReset() function is already called, namely when the main(..) function finishes.
I think, you may take cudaDeviceReset() to an atexit(..) function.
void myexit() {
cudaDeviceReset();
}
int main(...) {
atexit(myexit);
A t;
return 0;
}

code for optimized watch

i want to implement a code to keep a watch on suppose some event ...at the meantime i don have any inbuilt eventwatcher so i hv to implement one of mine..which consumes least cpu & memory.
can u suggest me one..
for example a pseudocode is given:
while(true)
{
if(process.isrunning)
process.kill();
}
If you don't have any event to hook into, then your code has to be "active" to run the checks. And that costs CPU cycles.
What you can to do ease waste is to add a call to sleep (Thread.Sleep in .NET, sleep in some implementations of C++).
while (true) {
if(process.isrunning)
process.kill();
sleep(100); // Wait 100 millisecond before trying again
}
But that will make you code a little less responsive.
you can try using timer queue : http://msdn.microsoft.com/en-us/library/ms687003%28VS.85%29.aspx its basically using kernel scheduler to call your function callback at specified interval, the caller is from different thread so it won't interrupt the main thread and make your application responsive, the thread is managed by Windows so you don't have to manage your own pooling thread, and its relative accurate.
implementation example:
`
//a singleton class that hold timer queue
class TimerQueue {
protected:
HANDLE timerQueue;
TimerQueue() {
this->timerQueue = ::CreateTimerQueue();
}
~TimerQueue() {
if(this->timerQueue) {
::DeleteTimerQueueEx(this->timerQueue,NULL);
this->timerQueue = NULL;
}
}
public:
static HANDLE getHandle() {
static TimerQueue timerQueueSingleton;
return timerQueueSingleton.timerQueue;
}
}
//timer base class
class Timer
{
protected:
HANDLE timer;
virtual void timerProc() = 0;
static void CALLBACK timerCallback(PVOID param,BOOLEAN timerOrWait) {
Timer* self = (Timer*)param;
self->timerProc();
}
public:
Timer(DWORD startTimeMs,DWORD periodTimeMs) {
if(!::CreateTimerQueueTimer( &this->timer, TimerQueue::getHandle(),
(WAITORTIMERCALLBACK)&this->timerCallback,
this, startTimeMs, periodTimeMs,
WT_EXECUTEDEFAULT) ) {
this->timer = NULL;
}
}
virtual ~Timer() {
if(this->timer) {
::DeleteTimerQueueTimer(TimerQueue::getHandle(),&this->timer,NULL);
this->timer = NULL;
}
}
}
//derive and implement timerProc
class MyTimer : public Timer
{
protected:
virtual void timerProc() {
if(process.isRunning()) {
process.kill();
}
}
public:
MyTimer(DWORD startTimeMs,DWORD periodTimeMs)
: Timer(startTimeMs,periodTimeMs) {}
}
//usage:
int main(int argc,char* argv[]) {
MyTimer timer(0,100); //start immediately, at 10 Hz interval
}
`
disclaimer : i don't test or compile those codes, you should recheck it
Although you've tagged this as language-agnostic, any good implementation is going to vary widely not just from one language to another, but across operating systems. There are plenty of circumstances where programs or operating system functions need to do just this sort of thing, and mechanisms will have been implemented to do this in as sensible, non-intrusive a way as possible.
If you have a particular language and/or operating system in mind, please tell us, and give us a better idea of what you're trying to achieve. That way we can point you towards the most appropriate of the many possible solutions to this problem.