Because its what you guys are posting as solutions!
This is rediculous.. Look at Robin's excellent serial basics and get some understanding about the topic..
In reality, you are asking for SOFTWARE interrupts on an Arduino. Not going to happen.
But even his example 2 (for a message with endmarker) blocks, because it's in a while() inside loop().
while (Serial.available() > 0 && newData == false) {
It would be easy enough though to take the while() out and just append the next character as it becomes available as you loop().
Solutions are flags set by the OP who had to ask the question.
Serial is already handled by interrupts, no need to add to that functionality.
NO!
This is madness, I want my mommy! ![]()
while (Serial.available() > 0 && newData == false) {
does not block.
Well it does in the sense that it would read 10 characters in a "batch" so to speak if there were 10 there, but it doesn't block to wait for a character if there are none at the moment.
Look at the processor's data sheet. You will find a list of vectors, maybe even one for each UART.
Replace these Vectors with the address of your own handler function.
if ( LIDARSerial.available() >= 1 )
{
while ( LIDARSerial.available() )
{
This if ( LIDARSerial.available() >= 1 ) can be changed to if ( LIDARSerial.available() >= 5 ) or even if ( LIDARSerial.available() >= 10 ) if so desired to defer the serial checking thing.
Another way is to use one of the cycle clocks, an Uno retrieves cycle clock values with the use of millis() and micros().
Here I use an ESP32 cycle clock to trigger run times.
void fDoMoistureDetector( void * parameter )
{
//wait for a mqtt connection
while ( !MQTTclient.connected() )
{
vTaskDelay( 250 );
}
int TimeToPublish = 5000000; //5000000uS
int TimeForADreading = 100 * 1000; // 100mS
uint64_t TimePastPublish = esp_timer_get_time(); // used by publish
uint64_t TimeADreading = esp_timer_get_time();
TickType_t xLastWakeTime = xTaskGetTickCount();
const TickType_t xFrequency = 10; //delay for 10mS
float RemainingMoisture = 100.0f; //prevents pump turn on during start up
bool pumpOn = false;
uint64_t PumpOnTime = esp_timer_get_time();
int PumpRunTime = 11000000;
uint64_t PumpOffWait = esp_timer_get_time();
uint64_t PumpOffWaitFor = 60000000; //one minute
float lowMoisture = 23.0f;
float highMoisture = 40.0f;
for (;;)
{
//read AD values every 100mS.
if ( (esp_timer_get_time() - TimeADreading) >= TimeForADreading )
{
xEventGroupSetBits( eg, evtADCreading );
TimeADreading = esp_timer_get_time();
}
xQueueReceive(xQ_RM, &RemainingMoisture, 0 ); //receive queue stuff no waiting
//read gpio 0 is water level good. Yes: OK to run pump : no pump off. remaining moisture good, denergize water pump otherwise energize water pump.
if ( RemainingMoisture >= highMoisture )
{
WaterPump0_off();
}
if ( !pumpOn )
{
log_i( "not pump on ");
if ( gpio_get_level( GPIO_NUM_0 ) )
{
if ( RemainingMoisture <= lowMoisture )
{
//has one minute passed since last pump energize, if so then allow motor to run
if ( (esp_timer_get_time() - PumpOffWait) >= PumpOffWaitFor )
{
WaterPump0_on();
log_i( "pump on " );
pumpOn = !pumpOn;
PumpOnTime = esp_timer_get_time();
}
}
//xSemaphoreGive( sema_RemainingMoisture );
} else {
log_i( "water level bad " );
WaterPump0_off();
PumpOffWait = esp_timer_get_time();
}
} else {
/*
pump goes on runs for X seconds then turn off, then wait PumpOffWaitTime before being allowed to energize again
*/
if ( (esp_timer_get_time() - PumpOnTime) >= PumpRunTime )
{
log_i( "pump off " );
WaterPump0_off(); // after 5 seconds turn pump off
pumpOn = !pumpOn;
PumpOffWait = esp_timer_get_time();
}
}
// publish to MQTT every 5000000uS
if ( (esp_timer_get_time() - TimePastPublish) >= TimeToPublish )
{
xQueueOverwrite( xQ_RemainingMoistureMQTT, (void *) &RemainingMoisture );// data for mqtt publish
TimePastPublish = esp_timer_get_time(); // get next publish time
}
xLastWakeTime = xTaskGetTickCount();
vTaskDelayUntil( &xLastWakeTime, xFrequency );
}
vTaskDelete( NULL );
}// end fDoMoistureDetector()
The ESP32 macro esp_timer_get_time(); returns the cycle count of microseconds that the ESP32 has been running, since a unit64_t is used the roll over time is >200 years.
These if statements if ( (esp_timer_get_time() - PumpOnTime) >= PumpRunTime ) and if ( (esp_timer_get_time() - TimePastPublish) >= TimeToPublish ) are only satisfied when a certain amount of time has passed. Thus the code contained within those if statements only run on a periodic basis.
The OP can look at File|Examples|02.Digital|BlinkWithoutDelay for the Arduino way.
With the use of if ( LIDARSerial.available() >= 1 ) and only checking for serial available once a millisecond and only doing the serial thing when a certain number of received characters exits the blocking of receiving of serial data can be greatly reduced.
Also, reading the link from post#22 would be a good idea.
I would shout it from the roof top but shouting is considered impolite.
You should not use while-loops !!
That expression will always be true, so, no wait ...
(You can have pretend SWIs using a spare IO pin and pin change interrupts.
Or you can be sensible, and use Serial.available() ) - I suspect interrupt overheads will take longer than a call to Serial.available...)
There are three hardware interrupts centering the UART Port of ATmega328P MCU. These are:
1. RXC0 : UART Receive Complete
ISR(USART_RX_vect){}
2. TXC0: UART Transmit Complete
ISR(USART_TX_vect){}
3. UDRE0: UART Data Register Empty
ISR(USART_UDRE_vect){}
4. The Arduino Development Team has used the the RX interrupt to automatically fill up the Serial Buffer with the data bytes that are coming via UDR0's receiver.
5. They have handed over the Serial.available() method to test if there is any data in the Serial Buffer before executing the following command:
Serial.read();
6. TX interrupt comes into scene during the execution of the following code:
Serial.write(buffer, sizeof buffer);
7. Is there any interrupt handler to notify the user that the Serial Buffer has accumulated a data byte? To my knowledge, there is none!
8. There is serialEvent(){} function which is automatically called upon by the loop() function. This function is not found to have wide usage. A sample example of serialEvent() function:
volatile bool flag;
volatile char y;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (flag == true)
{
Serial.println(y);
flag = false;
}
}
void serialEvent()
{
while (Serial.available())
{
y = Serial.read();
}
flag = true;
}
Such an interrupt does not make sense. It does not make a difference whether the main program loop checks a flag set by an ISR or checks for available characters.
IIRC this is called at the end of each loop, not different from checking it yourself except you can control frequency of polling
That seems to be correct.
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
and
void serialEventRun(void)
{
#if defined(HAVE_HWSERIAL0)
if (Serial0_available && serialEvent && Serial0_available()) serialEvent();
#endif
// etc.
I have not heard of this function before until today.
What does the above mean?
This is part of the Arduino AVR core code. It calls both setup() and loop() and apparently also this serialEvent().
[edit] It happens in this file if you are interested.
It was easy enough to check.
void serialEventRun(void)
{
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
#if defined(HAVE_HWSERIAL0)
if (Serial0_available && serialEvent && Serial0_available()) serialEvent();
#endif
// etc.
This blinks the builtin LED.
If the function exists, call it.