ESP32 attempt reconnect to when network drops without halting loop (Arduino) - c++

I have an ESP 32 collect data from a moisture sensor, which it then serves on our network. Our WiFi turns off between 1am and 6 am (because no one is using it). The ESP does not automatically try to reconnect, so it gathered data all night which I straight up can not access now.
For obvious reasons I do not want it to halt data collection when it looses connection to our network, so I can not have a loop try to reconnect. I tried this code:
void loop() {
sensor_value = analogRead(sensor_pin);
Serial.println(sensor_value);
push_value(float(sensor_value)/2047.0);
//============
//RELEVANT BIT
//============
if( WiFi.status() != WL_CONNECTED ){
//Try to recconect if connection is lost....
WiFi.disconnect();
WiFi.begin(ssid, pwd);
}
delay(second_delay*1000);
}
I've seen everyone run Wifi.disconnect() before attempting reconnecting. Is that necessary. Also does WiFi.begin() pause execution? I can't test my code right now unfortunately.
I am using the Arduino IDE and Wifi.h
And before you ask: Yes, 2047 is correct. I am running the sensor on the wrong voltage which results in about this max value.

Given that you've tagged esp8266 wifi, I'm assuming you're using that library. If so, then wifi.begin will not block execution. The library sets autoreconnect by default, so it'll automatically reconnect to the last access point when available. Any client functions will simply return an error code while disconnected. I do not know of any reason that wifi.disconnect should be called before begin.

Related

QSerialPort continuous reading accumulative delay

I am trying to do communication from QT Application to Arduino. The flow is like this: QT Application sends a '1' and Arduino is expected to respond with some data(the data String length is huge, around 300). QT Application is sending '1' at the rate of around 5Hz(every 200ms).
The problem I am facing is, there is an accumulative delay between the Arduino to QT communication. That is, the data I receive from Arduino is not recent data but the frequency of data coming of Arduino is 5Hz only(which is as expected), just the data coming is not recent. This delay keeps on increasing with time. I believe there is some problem with buffer or something.
What I tried:
QSerialPort serialPort; is my device port
serialPort.clear()
serialPort.flush()
Increasing and decreasing Baud Rate from both ends.
Reduce character length from Arduino, here delay reduces significantly but the accumulated delay is observed after a long time.
to clear serial communication buffer, but the issue still persists.
Here is my code snippet:
connect(timer_getdat, SIGNAL(timeout()), this, SLOT(Rec()));
timer_getdat->start(200);
where Rec() is the function where I do communication part.
In Rec():
serialPort.write("1", 2);
// serialPort.waitForBytesWritten(100);
long long bytes_available = serialPort.bytesAvailable();
if (bytes_available >= 1)
{
serialPort.readLine(temp, 500);
serialPort.flush(); // no change
serialPort.clear(); // no change by .clear() also
}
I have been stuck on this issue for a quite long time. The above code snippet is what I think is necessary but if anyone needs more clarification, I may reveal more of the code.
I also encountered with the same issue, and yes QSerialPort.clear() and QSerialPort.flush() doesn't help. Try doing readAll()
So change the part in your Rec() function to something like this:
serialPort.write("1", 2);
long long bytes_available = serialPort.bytesAvailable();
if (bytes_available >= 1)
{
serialPort.readLine(temp, 500);
serialPort.readAll(); // This reads all the data in buffer at once and clears the queue.
}
Even on QT forums, I didn't find the answer to this, was playing with all functions available with QSerialPort class and readAll() seems to work.
About readAll(), Qt documentation says:
Reads all remaining data from the device, and returns it as a byte
array.
My explanation for the resolution is that readAll captures all of the data from the communication buffer and empties it.
This should be the job of clear() function but apparently readAll() seems to work.

I2C Does not acknowledge Slave Address

I am Using STM32F767ZI MCU on Nucleo 144 board, C++ as programming language and IAR embedded workbench IDE.
TXIS bit flag Status is never getting Set (1) even when the I2C is enabled and there is no data in TXDR register.
What I have also noticed that although both master and slave have same Slave address in the relevant registers but NO ADDCODE occurs. Although as evident from code I am using the Polling method. ADDCODE register should have same address as slave address which is not happening as well.
Hardware settings have been verified as correct.
Trying to perform Loopback test on same MCU using I2C1 as master transmitter and I2C2 as slave receiver. Code is getting stuck at part as below:
while(!(IsTXISset())) // Code is getting stuck here
{
}
Where IsTXISset() is as below:
bool I2CInterface_c::IsTXISset(void) const
{
bool flag{false};
volatile uint32_t isrreg = I2C_ISR.Get();
isrreg &= TXISFLAG; //TXISFLAG = 0x02 i.e the only bit position of the TXIS is set as high
if(isrreg == TXISFLAG)
{
flag = true;
}
return flag;
}
Can Anybody assist with that please?
Finally, managed to resolve the issue after noticing that GPIO pins were not setting up properly in Alternative function open drain mode.
Second problem identified after slave started acknowledging the address match no data transfer was taking place which got resolved by writing a routine to clear the ADDR bit is ISR register of I2C.

C++ Serial Communication Issue

I am trying to make a Console C++ program that will be able to communicate through the serial port with my Arduino microcontroller, however I am having a problem with the ReadFile() function:
This is the ReadFile() function code from my C++ Console Program:
if(ReadFile(myPortHandle, &szBuf, 1, &dwIncommingReadSize, NULL) != 0)
{
cout<<"FOUND IT!"<<endl;
Sleep(100);
}
else
{
cout<<".";
Sleep(100);
}
The ReadFile function is consistently returning the "False" value, meaning it is not finding anything in the serial port. On the other side of the serial port, I have my Arduino Hooked up with the following code:
int switchPin = 4; // Switch connected to pin 4
void setup() {
pinMode(switchPin, INPUT); // Set pin 0 as an input
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (digitalRead(switchPin) == HIGH) { // If switch is ON,
Serial.write(1); // send 1 to Processing
} else { // If the switch is not ON,
Serial.write(0); // send 0 to Processing
}
delay(100); // Wait 100 milliseconds
}
And every time I press a push button, I would send a "1" value to the serial port, and a "0" every time I don't press a push button. Basically, I got the Arduino code from a tutorial I watched on how to do serial communication with the program Processing (which worked perfectly), though I am unable to do the same with a simple Console Application I made with C++ because for some reason the ReadFile() function isn't finding any information in the serial port.
Anyone happen to know why?
P.S.: The complete code in the C++ Console Program can be found here:
https://stackoverflow.com/questions/27844956/c-console-program-serial-communication-arduino
The ReadFile function is consistently returning the "False" value, meaning it is not finding anything
No, that is not what it means. A FALSE return value indicates that it failed. That is never normal, you must implement error reporting code so you can diagnose the reason. And end the program since there is little reason to continue running. Unless you setup the serial port to intentionally fail by setting a read timeout.
Use GetLastError() to obtain the underlying Windows error code.
You look to use MS Windows so try to catch the arduino output using portmon first, then you can debug your C++ code.

Android usb host input bulktransfer fails to read randomly when data available

The following code is inside a thread and reads input data coming over usb. Approximately every 80 readings it misses one of the packets coming from an stm32 board. The board is programmed to send data packets to the android tablet every one second.
// Non Working Code
while(running){
int resp = bulktransfer(mInEp,mBuf,mBuf.lenght,1000);
if(resp>0){
dispatchMessage(mBuf);
}else if(resp<0)
showsBufferEmptyMessage();
}
I was looking the Missile Launcher example in android an other libraries on the internet and they put a delay of 50ms between each poll. Doing this it solves the missing package problem.
//Working code
while(running){
int resp = bulktransfer(mInEp,mBuf,mBuf.lenght,1000);
if(resp>0){
dispatchMessage(mBuf);
}else if(resp<0)
showsBufferEmptyMessage();
try{
Thread.sleep(50);
}catch(Exception e){}
}
Does anyone knows the reason why the delay works. Most of the libraries on github has this delay an as I mention before the google example too.
I am putting down my results regarding this problem. After all seems that the UsbConnection.bulkTransfer(...) method has some bug when called continuously. The solution was to use the asynchronous API, UsbRequest class. Using this method I could read from the input endpoint without delay and no data was lost during the whole stress test. So the direction to take is asynchronous UsbRequest instead of synchronously bulktransfer.

Cannot connect Wifly to Arduino

I am just an Arduino beginner. I bought an Arduino Uno and a Wifly shield yesterday and I am not able to run the Wifly_Test example program come with WiFlySerial library.
When I look at Serial Monitor, I only saw 2 lines are printed out
1.Starting WiFly Tester.
2.Free memory:XXXX
How can I know that the Wifly Sheild that I bought is not faulty?
I soldered the heard ping to Wifly Shield and stacked it to Aurduino Uno and I can see the LEDs blinking on the Wifly Shield.
Do I need to reset the Wifly Sheild? How do I reset it?
Please point me to the most simple example on how to connect to the router.
I have also bought the shield and had trouble to start with.
If you have soldered the pins to the shield that should be fine but make sure you check they all have a connection and that they don't have solder running down the legs of the pins as this causes the shield to be temperamental.
Run the code below which is from the WiFly library (alpha 2 version) that can be found here:
http://forum.sparkfun.com/viewtopic.php?f=32&t=25216&start=30
Once you see that the shield has connected it will ask for an input, type $$$ and press enter... you have now entered the command line and CMD will be displayed.
If you do not know your network settings type scan and this will display them.
Then set your authentication by typing set wlan auth 3 (Mixed WPA1 & WPA2-PSK) or set wlan auth 4 (WPA2-PSK) this depends on the type of authentication you ise so pick the write one for your network.
Then type set wlan phrase YourPharsePhrase (Change YourPharsePhrase to whatever your WPA key is)
Then type join YourSSIDName (Change YourSSIDName to whatever your network name is)
You see something like this:
join YourSSIDName
Auto-Assoc YourSSIDName chan=1 mode=MIXED SCAN OK
Joining YourSSIDName now..
<2.15> Associated!
DHCP: Start
DHCP in 1234ms, lease=86400s
IF=UP
DHCP=ON
IP=10.0.0.116:2000
NM=255.255.255.0
GW=10.0.0.1
Listen on 2000
you are now connected to your network.
Hopefully this will get you up and running.
N.B. REMEMBER TO CAREFULLY CHECK YOUR PINS! I had great trouble with mine because only a small amount of solder is needed but enough to get a good connection, the balance of this was minute but enough that it wouldn't work. I used a magnifying to check mine in the end.
#include "WiFly.h" // We use this for the preinstantiated SpiSerial object.
void setup() {
Serial.begin(9600);
Serial.println("SPI UART on WiFly Shield terminal tool");
Serial.println("--------------------------------------");
Serial.println();
Serial.println("This is a tool to help you troubleshoot problems with the WiFly shield.");
Serial.println("For consistent results unplug & replug power to your Arduino and WiFly shield.");
Serial.println("(Ensure the serial monitor is not open when you remove power.)");
Serial.println();
Serial.println("Attempting to connect to SPI UART...");
SpiSerial.begin();
Serial.println("Connected to SPI UART.");
Serial.println();
Serial.println(" * Use $$$ (with no line ending) to enter WiFly command mode. (\"CMD\")");
Serial.println(" * Then send each command followed by a carriage return.");
Serial.println();
Serial.println("Waiting for input.");
Serial.println();
}
void loop() {
// Terminal routine
// Always display a response uninterrupted by typing
// but note that this makes the terminal unresponsive
// while a response is being received.
while(SpiSerial.available() > 0) {
Serial.write(SpiSerial.read());
}
if(Serial.available()) { // Outgoing data
//SpiSerial.print(Serial.read(), BYTE);
SpiSerial.write(Serial.read());
}
}
Sorry I forgot to mention , you reset the shield by going to the WiFly library and going to: WiFly/tools/HardwareFactoryReset
Then open the serial monitor and type in any character and this will start the reset.
Thanks everyone who tried to answer me. I finally solved my problem by using Arduino 0023 instead of 1.0.