ESP32 pin output not working with Arduino IDE - arduino-ide

I was trying to setup my first ESP32 board with Arduino IDE. It works fine with built-in LED but does not work with pins. Here is my code:
int LED_BUILTIN = 2; // works fine
int LED_OUT = 25; // not working, even other pins
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(LED_OUT, OUTPUT);
Serial.begin(115200);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
// turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW);
// turn the LED off by making the voltage LOW
delay(1000); // wait for a second
digitalWrite(LED_OUT, HIGH);
// turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_OUT, LOW);
// turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
The on-board built-in LED is blinking according to my code but GPIO 25 is not outputting anything. I tried other pins and found none of them works. I happened to try GPIO 4 and found it blinking together with the built-in LED. It seems like GPIO 4 is connected to the built-in LED.
So did I miss anything setting up the pin mode or whatever? How can I select a pin and make it work as output to blink my LED on breadboard?
Thanks in advance.

Make sure Positive(+ive) terminal is connected to Pin 25 .
Make sure, Pin number matched with pin name printed on board, there are different variants. If you select ESP32-DEV module and use pin layout in following link, most probably it will work. esp32-arduino-pin-layout
static const uint8_t A18 = 25;

Make sure the pinout diagram you are following matches with the board hardware you are using. You can do that by counting the number of pins in the diagram you're following and counting pins of your hardware. This is a simple check. Sometimes, you are using different version of the ESP32 board and following pinout of different version due to which it does not work.
Pin 2 works fine because normally GPIO_2 is connected to build in led but others wouldn't work.

Related

Qt c++ how to free memory after loading a new HTML page

I'am doing a Qt app in c++ with frontend in Html / Css.
Each time i load a new html page (or if i reload one), the app get +5mo ram, and dont get free after quit. (So after 10 pages i got +50mo ram)
I've allready try to préload my pages into a vector, but the loading still add 5mo each time.
I've also think to load pages in threads, so they'll be destroyed after using.
Is it a possible solution to keep a descent ram weight??
As i'am a newbie i'am probably doing something stupid : here's my code for loading a new view :
Q_INVOKABLE bool myBridge::newView(QString page)
{
QString path = ("file:///" + QDir::currentPath() + "/");
if (!(page.compare("page3.html")))
_mediaPlayer->setTimer(10000);
else
_mediaPlayer->setTimer(60000);
_view->close();
_view = new WebView;
_view->load(QUrl(path + page));
_view->page()->mainFrame()->addToJavaScriptWindowObject("bridge", this);
_view->showFullScreen();
_mediaPlayer->_srnsaver->timerRestart();
return (true);
}
Can you see something wrong in this code?
Every time this method is called you create a new WebView and you most likely never delete the previous one. Naturally this will cause a memory leak since nothing is freed. Calling close() does not delete the object.

Taking photo in C++/CX with Windows Phone 8.1

I am working in C++/CX (in Visual Studio 2013) on an app for Windows phone 8.1 systems. I test my app on a Nokia Lumia 930. My app must take photos to do some image processing on them. Therefore I would like to have a byte* or char* or unsigned char* to to whatever I want. So I tried to use ::Windows::Media::Capture::MediaCapture::CapturePhotoToStreamAsync to get the content of the photo into a stream and then with a ::Windows::Storage::Streams::DataReader get the actual bytes of the photo. But I have been unsuccessful. More precisely the problem is here in the code that follows.
IRandomAccessStream ^ras = ref new InMemoryRandomAccessStream();
IAsyncAction ^ac = cap->CapturePhotoToStreamAsync(ImageEncodingProperties::CreateBmp(),ras);
ac->Completed = ref new AsyncActionCompletedHandler(
[=] (IAsyncAction ^async_op,AsyncStatus status) mutable
{
debug->Text = L"finished";
});
where cap is a managed pointer to a MediaCapture which seems to be correctly initialized.
But the debug TextBlock never shows finished. And when I get the status of ac it seems to be blocked on Started forever, it never gets to Error or Completed. I do not understand why. So for now I implemented a dirty workaround that uses ::Windows::Media::Capture::MediaCapture::CapturePhotoToStorageFileAsync. But storing the photo in a bitmap on a file then reading it back to get the image back in memory is not satisfactory at all.
I have found a lot on taking photos with Windows Phone 8.1, but they are all in C# and copy-pasting those solutions by replacing the '.' by '::' does not work. I mean it is (at least for me) not easy at all to adapt C# code to C++ code.
So my questions are :
Is there a quick and/or clean way of getting a good old C pointer to the pixels of the image?
Why do CapturePhotoToStreamAsync block with status Started?
Thank you for your answers and your time.
Take a look at the basic camera sample app on the Microsoft Github page: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/CameraStarterKit
There's a lot you need to do before you can take a picture (initialize, configure, start preview, etc.) and the sample will walk you through it.
Here's a shortened snippet from the sample I linked above:
/// <summary>
/// Takes a photo to a StorageFile and adds rotation metadata to it
/// </summary>
/// <returns></returns>
task<void> MainPage::TakePhotoAsync()
{
auto inputStream = ref new Streams::InMemoryRandomAccessStream();
// Take the picture
WriteLine("Taking photo...");
return create_task(_mediaCapture->CapturePhotoToStreamAsync(Windows::Media::MediaProperties::ImageEncodingProperties::CreateJpeg(), inputStream))
.then([this, inputStream]()
{
WriteLine("Photo taken!");
auto photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
return ReencodeAndSavePhotoAsync(inputStream, photoOrientation);
}).then([this](task<void> previousTask)
{
try
{
previousTask.get();
}
catch (Exception^ ex)
{
WriteException(ex);
}
});
}

Detect if user Idle on windows universal app

I'm developing a class library for windows 10 universal apps (mobile and desktop device families only). I need to invoke an event if the user has been idle(no touch, mouse move, key press etc) for x number of seconds. This method can be used to solves this problem on android. But I couldn't find a solution on windows UWP.
Is there an API available in UWP to achieve this?
You can detect global input with various events on the app's CoreWindow:
Touch and mouse input with CoreWindow.PointerPressed, PointerMoved, and PointerReleased.
Keyboard input: KeyUp and KeyDown (the soft keys) and CharacterReceived (for characters generated via chords & text suggestions)
Use these to detect the user is active and idle out if it goes too long without any of these events.
I know this is really old question, but I think you can now get to same result with RegisterBackgroundTask
Just set:
new TimeTrigger(15, false) //For time trigger
Link
new SystemCondition(SystemConditionType.UserNotPresent)) //And so you want to know so user is not present
Link
Example usage in App.xaml.cs:
var builder = new BackgroundTaskBuilder();
builder.Name = "Is user Idle";
builder.SetTrigger(new TimeTrigger(2, false)); //two mins
builder.AddCondition(new SystemCondition(SystemConditionType.UserNotPresent));
// Do not set builder.TaskEntryPoint for in-process background tasks
// Here we register the task and work will start based on the time trigger.
BackgroundTaskRegistration task = builder.Register();
task.Completed += (sender, args) =>
{
//Handle user not present (Idle) here.
};

wakeLock does not wait for network connectivity

I am using a wakelock for a alarm to update the app state regularly. The wifi takes a while to connect on Samsung phones. Also the "keep awake" option on Wifi does not work on Samsung phones (nor are they interested in fixing the issue). So when the wakelock does happen, it should wait for wifi to connect. Do I need to create a listener for the wifi connectivity for this to work, or should wakelock, kinda block for that wifi to connect ?
mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "Taxeeta");
mWakeLock.acquire();
// do some network activity, in a asynctask
// in the doPost of asyscTask, release lock
Edit :
The question is, that in the AsyncTask if the network is not connected, OR takes time to get on (3g takes a while to get on), the webservice call in the Async doInBackground will fail. And I will have to release the lock anyways.
SO
Should I put in wifi/data connection listeners in ? Or is there a better way ?
I have a similar scenario - I am woken up by an alarm, the alarm's BroadcastReceiver launches a WakefulIntentService and the service starts a scan for networks. I use a stupid way of holding on to the lock1 - I intend to replace this with a latch. I suggest you replace the "AsyncTask" with a WakefulIntentService. Chances are the AsyncTask is not ever fired. In the WakefulIntentService you must acquire and hold on to a wifi lock - I would make this a static field of the YourWakefulIntentService - not entirely clear on this - it's a while back. If this does not work I would use a latch in the YourWakefulIntentService :
// register an alarm
Intent i = new Intent(context, YourReceiver.class);
PendingIntent alarmPendingIntent= PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
public class YourReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
WakefulIntentService.sendWakefulWork(context, YourWIS.class);
}
}
//pseudocode !
public class YourWIS extends WakefulIntentService { // you must add a cstor !
#Override
doWakefulWork() {
acquireWifiLock();
enableScanReceiver();
startScan();
serviceLatch.wait();
releaseWifiLock();
}
}
// in YourScanReceiver
onReceive() {
if(action.equals(SCAN_RESULTS) {
// do something that does not take time or start another/the same
// WakefulIntentService
serviceLatch.notify();
}
}
Try first the WakefulIntentService (I guess you launch the AsyncTask from the alarm receiver). The scan receiver is a receiver registered to receive the scan results (see WifiManager docs - prefer Receivers to listeners for sleep issues)
1 : this is a working class - I just use a second wakeful intent service to keep the wake locks - have still to refactor it to use latches but this approach at least works (I have the second service (the Gatekeeper) wait on a monitor and have the wake lock inside the Gatekeeper. The gatekeeper also holds its CPU lock so all is fine (and ugly)

WebAPI and HTML5 SSE

was trying to encapsulate a partial view to show feedback that i can push back to the client.
This Article shows a method of pushing back data using HTML5 Server-Sent events (SSE).
I noticed that if i opened up several browser tabs and then closed one i got exceptions as the logic didn't remove the respective stream from the ConcurrentQueue. I amended the code as below
private static void TimerCallback(object state)
{
StreamWriter data;
Random randNum = new Random();
// foreach (var data in _streammessage)
for (int x = 0; x < _streammessage.Count; x++)
{
_streammessage.TryDequeue(out data);
data.WriteLine("data:" + randNum.Next(30, 100) + "\n");
try
{
data.Flush();
_streammessage.Enqueue(data);
}
catch (Exception ex)
{
// dont re-add the stream as an error ocurred presumable the client has lost connection
}
}
//To set timer with random interval
_timer.Value.Change(TimeSpan.FromMilliseconds(randNum.Next(1, 3) * 500), TimeSpan.FromMilliseconds(-1));
}
I also had to amend the OnStreamAvailable member as the framework syntax had changed to the second parameter being a HttpContent rather than HttpContentHeaders
public static void OnStreamAvailable(Stream stream, HttpContent headers, TransportContext context)
The problem now is i am still getting inconsistant behaviour if i add or remove clients i.e it times out when trying to initialise a new client. Does anyone have any ideas or more examples of using SSE with WinAPI and the correct "framework of methods" to handle disconnected clients
Cheers
Tim
This article is actually an adaptation of my original article from May - http://www.strathweb.com/2012/05/native-html5-push-notifications-with-asp-net-web-api-and-knockout-js/ (notice even variable names and port numbers are the same :-).
It is a very valid point that you are raising, and detecting a broken connection is something that's not very easy with this setup. The main reason is that while ASP.NET (the host) allows you to check a broken connection, there is no notification mechanism between ASP.NET (host) and Web API informing about that.
That is why in order to detect a broken connection (disconnected client) you should really try writing to the stream, and catch any error - this would mean the client has been disconnected.
I asked the same question to Brad Wilson/Marcin Dobosz/Damien Edwards at aspconf, and Damien suggested using HttpContext.Current.Response.IsClientConnected - so basically bypassing Web API and obtaining the connectivity info from the underlying host directly (however there is still a race condition involved anyway). That is really .NET 4. He also pointed an interesting way in which this problem could be avoided in .NET 4.5 using an async cancellation token. Frankly, I have never got around to test it, but perhaps this is something you should explore.
You can see their response to this problem in this video - http://channel9.msdn.com/Events/aspConf/aspConf/Ask-The-Experts - fast forward to 48:00