{ "version": "https://jsonfeed.org/version/1.1", "user_comment": "This feed allows you to read the posts from this site in any feed reader that supports the JSON Feed format. To add this feed to your reader, copy the following URL -- https://eloquentarduino.github.io/tag/eloquent/feed/json/ -- and add it your reader.", "home_page_url": "https://eloquentarduino.github.io/tag/eloquent/", "feed_url": "https://eloquentarduino.github.io/tag/eloquent/feed/json/", "language": "en-US", "title": "eloquent – Eloquent Arduino Blog", "description": "Machine learning on Arduino, programming & electronics", "items": [ { "id": "https://eloquentarduino.github.io/?p=211", "url": "https://eloquentarduino.github.io/2019/12/arduino-bounded-waiting/", "title": "Eloquent bounded waiting: the await construct", "content_html": "

Sometimes you may need to wait for a certain condition to become true, but you don't want to wait forever: it may be awaiting for Serial, for the Wifi to connect to a network, or the response from a SoftwareSerial peripheral. The await construct lets you put an upper bound to the time you're willing to wait.

\n

\n

Most often, you see example code of this kind:

\n
Serial.print("Attempting to connect to WiFi");\n\nwhile (WiFi.status() != WL_CONNECTED) {\n    Serial.print(".");\n    delay(500);\n}
\n

If the connection doesn't succeed (maybe the AP is out of range or is down), you're stuck in an endless wait. A proper way for handling such situations is with a timeout that gets you out of the loop with an error status so you can handle the failure.
\nawait is exactly this: a construct to await for a condition to become true until a timeout expires, returning true or false as a response.

\n

Definition

\n
#define await(condition, timeout) await_with_interval(condition, timeout, 10)\n#define await_with_interval(condition, timeout, interval) \\\n  ([]() { \\\n    uint32_t start = millis(); \\\n    while (millis() - start <= timeout) { \\\n      if (condition) return true; \\\n      delay(interval); \\\n    } \\\n  return false; })()
\n

How to use

\n

await needs at least two arguments:

\n
    \n
  1. the condition to await for
  2. \n
  3. the timeout, in milliseconds
  4. \n
\n
// these are for greater code readability\r\n#define Millis \r\n#define Second  *1000\r\n#define Seconds *1000\r\n
\n
bool wifiConnected = await(WiFi.status() == WL_CONNECTED, 10 Seconds)
\n

The code above will wait 10 seconds for the wifi to connect: on failure, wifiConnected will be false and you can gently fail.

\n

You can use it for any kind of check, like waiting for Serial.

\n
bool serialReady = await(Serial, 5 Seconds)\nbool serialHasCharacters = await(Serial.available(), 5 Seconds)
\n

The default interval between checks is 10 milliseconds: if you need a custom delay interval you can use the more verbose await_with_interval:

\n
// await WiFi for 10 seconds, check if connected every 500 millis\nbool wifiConnected = await_with_interval(WiFi.status() == WL_CONNECTED, 10 Seconds, 500 Millis)
\n

How it works

\n

The await macro creates an inline function that loops until the timeout expires. At every loop it checks if the condition is true: if that's the case, it returns true. The inline function construct is needed to get a return value, so you can assign it to a variable or embed directly inside an if test. The following code sample gives you an idea of what's happening.

\n
bool wifiConnected = await(WiFi.status() == WL_CONNECTED, 10 Seconds)\n\n// conceptually translates to\n\nbool inline_function() {\n    uint32_t start = millis();\n\n    while (millis() - start <= 10000) {\n      if (WiFi.status() == WL_CONNECTED)\n        return true;\n\n      delay(10);\n    }\n\n   return false;\n}\n\nbool wifiConnected = inline_function();
\n

L'articolo Eloquent bounded waiting: the await construct proviene da Eloquent Arduino Blog.

\n", "content_text": "Sometimes you may need to wait for a certain condition to become true, but you don't want to wait forever: it may be awaiting for Serial, for the Wifi to connect to a network, or the response from a SoftwareSerial peripheral. The await construct lets you put an upper bound to the time you're willing to wait.\n\nMost often, you see example code of this kind:\nSerial.print("Attempting to connect to WiFi");\n\nwhile (WiFi.status() != WL_CONNECTED) {\n Serial.print(".");\n delay(500);\n}\nIf the connection doesn't succeed (maybe the AP is out of range or is down), you're stuck in an endless wait. A proper way for handling such situations is with a timeout that gets you out of the loop with an error status so you can handle the failure.\nawait is exactly this: a construct to await for a condition to become true until a timeout expires, returning true or false as a response.\nDefinition\n#define await(condition, timeout) await_with_interval(condition, timeout, 10)\n#define await_with_interval(condition, timeout, interval) \\\n ([]() { \\\n uint32_t start = millis(); \\\n while (millis() - start <= timeout) { \\\n if (condition) return true; \\\n delay(interval); \\\n } \\\n return false; })()\nHow to use\nawait needs at least two arguments:\n\nthe condition to await for\nthe timeout, in milliseconds\n\n// these are for greater code readability\r\n#define Millis \r\n#define Second *1000\r\n#define Seconds *1000\r\n\nbool wifiConnected = await(WiFi.status() == WL_CONNECTED, 10 Seconds)\nThe code above will wait 10 seconds for the wifi to connect: on failure, wifiConnected will be false and you can gently fail. \nYou can use it for any kind of check, like waiting for Serial.\nbool serialReady = await(Serial, 5 Seconds)\nbool serialHasCharacters = await(Serial.available(), 5 Seconds)\nThe default interval between checks is 10 milliseconds: if you need a custom delay interval you can use the more verbose await_with_interval:\n// await WiFi for 10 seconds, check if connected every 500 millis\nbool wifiConnected = await_with_interval(WiFi.status() == WL_CONNECTED, 10 Seconds, 500 Millis)\nHow it works\nThe await macro creates an inline function that loops until the timeout expires. At every loop it checks if the condition is true: if that's the case, it returns true. The inline function construct is needed to get a return value, so you can assign it to a variable or embed directly inside an if test. The following code sample gives you an idea of what's happening.\nbool wifiConnected = await(WiFi.status() == WL_CONNECTED, 10 Seconds)\n\n// conceptually translates to\n\nbool inline_function() {\n uint32_t start = millis();\n\n while (millis() - start <= 10000) {\n if (WiFi.status() == WL_CONNECTED)\n return true;\n\n delay(10);\n }\n\n return false;\n}\n\nbool wifiConnected = inline_function();\nL'articolo Eloquent bounded waiting: the await construct proviene da Eloquent Arduino Blog.", "date_published": "2019-12-05T19:50:59+01:00", "date_modified": "2019-12-16T23:03:25+01:00", "authors": [ { "name": "simone", "url": "https://eloquentarduino.github.io/author/simone/", "avatar": "http://1.gravatar.com/avatar/d670eb91ca3b1135f213ffad83cb8de4?s=512&d=mm&r=g" } ], "author": { "name": "simone", "url": "https://eloquentarduino.github.io/author/simone/", "avatar": "http://1.gravatar.com/avatar/d670eb91ca3b1135f213ffad83cb8de4?s=512&d=mm&r=g" }, "tags": [ "eloquent", "Eloquent library" ] }, { "id": "https://eloquentarduino.github.io/?p=209", "url": "https://eloquentarduino.github.io/2019/12/non-blocking-arduino-code/", "title": "Eloquent non-blocking code: the Every construct", "content_html": "

The every construct lets you run a piace of code at regular intervals in a fluent way. If you don't need to start, stop, pause your timer, this construct is a valid alternative to more complex timer libraries already available: it only takes a time interval as argument and will execute the code block periodically.

\n

\n

Definition

\n
#define every(interval) \\\n    static uint32_t __every__##interval = millis(); \\\n    if (millis() - __every__##interval >= interval && (__every__##interval = millis()))
\n

How to use

\n
// these are for greater code readability\r\n#define Millis \r\n#define Second  *1000\r\n#define Seconds *1000\r\n
\n
int interval = 1 Second;\n\nvoid setup() {\n    Serial.begin(115200);\n}\n\nvoid loop() {\n    every(1000 Millis) {\n        Serial.println("This line is printed every 1 second");\n    }\n\n    every(2000 Millis) {\n        Serial.println("This line is printed every 2 seconds");\n    }\n\n    every(interval) {\n        interval += 1 Second;\n        Serial.print("You can have variable intervals too! ");\n        Serial.print("This line will be printed again in ");\n        Serial.print(interval / 1000);\n        Serial.println(" seconds");\n    }\n}
\n

Caveats

\n

every is just a macro definition and is not a proper timer, so it has some limitations:

\n
    \n
  1. you can't stop, pause or resume it: once set, it will run forever
  2. \n
  3. its argument must be the suffix of a valid identifier
  4. \n
  5. you can't use several every with the exact same argument: you have to put all the code that needs to happen at the same interval in the same block
  6. \n
\n

Caveat #2

\n

The macro works by generating a variable named like __every__##argument

\n
every(1) ==> uint32_t __every__1;\nevery(2) ==> uint32_t __every__2;\nevery(a_given_interval) ==> uint32_t __every__a_given_interval;\nevery(an invalid interval) ==> uint32_t __every__an invalid interval; // Syntax error\nevery(1 Second) ==> uint32_t __every__1 *1000; // Syntax error
\n

So every integer literal and any variable are all valid arguments. Any expression is forbidden.

\n

Caveat #3

\n

If you use two every with the exact same argument, two variables with the exact same name will be created and it will rise a compile-time error.

\n

If you can live with this limitations, every only needs the space of an uint32_t to work.

\n

L'articolo Eloquent non-blocking code: the Every construct proviene da Eloquent Arduino Blog.

\n", "content_text": "The every construct lets you run a piace of code at regular intervals in a fluent way. If you don't need to start, stop, pause your timer, this construct is a valid alternative to more complex timer libraries already available: it only takes a time interval as argument and will execute the code block periodically.\n\nDefinition\n#define every(interval) \\\n static uint32_t __every__##interval = millis(); \\\n if (millis() - __every__##interval >= interval && (__every__##interval = millis()))\nHow to use\n// these are for greater code readability\r\n#define Millis \r\n#define Second *1000\r\n#define Seconds *1000\r\n\nint interval = 1 Second;\n\nvoid setup() {\n Serial.begin(115200);\n}\n\nvoid loop() {\n every(1000 Millis) {\n Serial.println("This line is printed every 1 second");\n }\n\n every(2000 Millis) {\n Serial.println("This line is printed every 2 seconds");\n }\n\n every(interval) {\n interval += 1 Second;\n Serial.print("You can have variable intervals too! ");\n Serial.print("This line will be printed again in ");\n Serial.print(interval / 1000);\n Serial.println(" seconds");\n }\n}\nCaveats\nevery is just a macro definition and is not a proper timer, so it has some limitations:\n\nyou can't stop, pause or resume it: once set, it will run forever\nits argument must be the suffix of a valid identifier\nyou can't use several every with the exact same argument: you have to put all the code that needs to happen at the same interval in the same block\n\nCaveat #2\nThe macro works by generating a variable named like __every__##argument\nevery(1) ==> uint32_t __every__1;\nevery(2) ==> uint32_t __every__2;\nevery(a_given_interval) ==> uint32_t __every__a_given_interval;\nevery(an invalid interval) ==> uint32_t __every__an invalid interval; // Syntax error\nevery(1 Second) ==> uint32_t __every__1 *1000; // Syntax error\nSo every integer literal and any variable are all valid arguments. Any expression is forbidden.\nCaveat #3\nIf you use two every with the exact same argument, two variables with the exact same name will be created and it will rise a compile-time error.\nIf you can live with this limitations, every only needs the space of an uint32_t to work.\nL'articolo Eloquent non-blocking code: the Every construct proviene da Eloquent Arduino Blog.", "date_published": "2019-12-05T19:42:45+01:00", "date_modified": "2019-12-16T22:59:36+01:00", "authors": [ { "name": "simone", "url": "https://eloquentarduino.github.io/author/simone/", "avatar": "http://1.gravatar.com/avatar/d670eb91ca3b1135f213ffad83cb8de4?s=512&d=mm&r=g" } ], "author": { "name": "simone", "url": "https://eloquentarduino.github.io/author/simone/", "avatar": "http://1.gravatar.com/avatar/d670eb91ca3b1135f213ffad83cb8de4?s=512&d=mm&r=g" }, "tags": [ "eloquent", "Eloquent library" ] }, { "id": "https://eloquentarduino.github.io/?p=164", "url": "https://eloquentarduino.github.io/2019/11/how-to-write-clean-arduino-code/", "title": "How to write clean Arduino code: introducing the Eloquent library", "content_html": "

Eloquent Arduino is an attempt to bring sanity and clarity in Arduino projects.\u00a0The purpose of this library is to create a wide range of constructs to clearly translate your ideas into meaningful code: stop writing spaghetti code only you can undestand, please! I'll show you how.

\n

\n

\"from

\n

The problem

\n

Arduino sells itself as a platform well suited for beginners, and it is for sure; lots of non-tech people are able to bring their ideas to life thanks to this awesome platform.
\nNevertheless, I often stumble upon bits of code over the internet that make me question about the quality of the projects people are producing.

\n

Even the Arduino official website is misleading in this sense, in my opinion, since it promotes a code style really straighforward, but suited for toy projects, with little logics and low complexity level.

\n

Here's an example of what I'm talking about, copy-pasted from the Arduino official site (with comments removed):

\n
const int ledPin =  LED_BUILTIN;\nint ledState = LOW;\nunsigned long previousMillis = 0; \nconst long interval = 1000; \n\nvoid setup() {\n  pinMode(ledPin, OUTPUT);\n}\n\nvoid loop() {\n  unsigned long currentMillis = millis();\n\n  if (currentMillis - previousMillis >= interval) {\n    previousMillis = currentMillis;\n\n    if (ledState == LOW) {\n      ledState = HIGH;\n    } else {\n      ledState = LOW;\n    }\n\n    digitalWrite(ledPin, ledState);\n  }\n}
\n

Can you tell what this code does with a minimum mental effort?
\nI don't think so (you may have recognized the async pattern and it actually blinks a LED in a non-blocking fashion).

\n

THIS is the problem: most Arduino code is not clear at first glance, is not eloquent. By eloquent I mean code that speaks by itself, without the need for comments.

\n

most Arduino code is not clear at first glance, is not eloquent
Click To Tweet


\n

The solution

\n

What about the following?

\n
DigitalOut led(LED_BUILTIN);\n\nvoid setup() {\n    led.begin();\n}\n\nvoid loop() {\n    every(1 Second) {\n        led.toggle();\n    }\n}
\n

I swear this is valid code that compiles just fine. Hopefully, it does the exact same thing as above, yet it is far more readable and understandable.

\n

Can you see my point now? Wouldn't it be much easier and reliable to code with the help of a set of such eloquent constructs / interfaces? I strongly believe it is, and this is why I'm writing this library.
\nAsynchronous programming, pin state managements, animations are bits of code that pop up over and over again in most of the projects, yet every time we start from zero and write the same boilerplate code over and over again.

\n

Boilerplate code is not only tedious, but error-prone. And lengthy. Start writing eloquent code now!
Click To Tweet


\n

Boilerplate code heavily relies on a fixed structure that could be hard to adapt to your specific case. Longer code means more chances to break something and more code to debug, which can waste lots of your valuable time.

\n
\n

I'm starting a series of posts where I'll document some of the classes and constructs the library provides to you. You can find the code on the Github repo.

\n

L'articolo How to write clean Arduino code: introducing the Eloquent library proviene da Eloquent Arduino Blog.

\n", "content_text": "Eloquent Arduino is an attempt to bring sanity and clarity in Arduino projects.\u00a0The purpose of this library is to create a wide range of constructs to clearly translate your ideas into meaningful code: stop writing spaghetti code only you can undestand, please! I'll show you how.\n\n\nThe problem\nArduino sells itself as a platform well suited for beginners, and it is for sure; lots of non-tech people are able to bring their ideas to life thanks to this awesome platform.\nNevertheless, I often stumble upon bits of code over the internet that make me question about the quality of the projects people are producing. \nEven the Arduino official website is misleading in this sense, in my opinion, since it promotes a code style really straighforward, but suited for toy projects, with little logics and low complexity level.\nHere's an example of what I'm talking about, copy-pasted from the Arduino official site (with comments removed):\nconst int ledPin = LED_BUILTIN;\nint ledState = LOW;\nunsigned long previousMillis = 0; \nconst long interval = 1000; \n\nvoid setup() {\n pinMode(ledPin, OUTPUT);\n}\n\nvoid loop() {\n unsigned long currentMillis = millis();\n\n if (currentMillis - previousMillis >= interval) {\n previousMillis = currentMillis;\n\n if (ledState == LOW) {\n ledState = HIGH;\n } else {\n ledState = LOW;\n }\n\n digitalWrite(ledPin, ledState);\n }\n}\nCan you tell what this code does with a minimum mental effort?\nI don't think so (you may have recognized the async pattern and it actually blinks a LED in a non-blocking fashion).\nTHIS is the problem: most Arduino code is not clear at first glance, is not eloquent. By eloquent I mean code that speaks by itself, without the need for comments.\nmost Arduino code is not clear at first glance, is not eloquentClick To Tweet\nThe solution\nWhat about the following?\nDigitalOut led(LED_BUILTIN);\n\nvoid setup() {\n led.begin();\n}\n\nvoid loop() {\n every(1 Second) {\n led.toggle();\n }\n}\nI swear this is valid code that compiles just fine. Hopefully, it does the exact same thing as above, yet it is far more readable and understandable. \nCan you see my point now? Wouldn't it be much easier and reliable to code with the help of a set of such eloquent constructs / interfaces? I strongly believe it is, and this is why I'm writing this library.\nAsynchronous programming, pin state managements, animations are bits of code that pop up over and over again in most of the projects, yet every time we start from zero and write the same boilerplate code over and over again.\nBoilerplate code is not only tedious, but error-prone. And lengthy. Start writing eloquent code now!Click To Tweet\nBoilerplate code heavily relies on a fixed structure that could be hard to adapt to your specific case. Longer code means more chances to break something and more code to debug, which can waste lots of your valuable time.\n\nI'm starting a series of posts where I'll document some of the classes and constructs the library provides to you. You can find the code on the Github repo.\nL'articolo How to write clean Arduino code: introducing the Eloquent library proviene da Eloquent Arduino Blog.", "date_published": "2019-11-03T17:05:46+01:00", "date_modified": "2019-12-22T14:40:10+01:00", "authors": [ { "name": "simone", "url": "https://eloquentarduino.github.io/author/simone/", "avatar": "http://1.gravatar.com/avatar/d670eb91ca3b1135f213ffad83cb8de4?s=512&d=mm&r=g" } ], "author": { "name": "simone", "url": "https://eloquentarduino.github.io/author/simone/", "avatar": "http://1.gravatar.com/avatar/d670eb91ca3b1135f213ffad83cb8de4?s=512&d=mm&r=g" }, "tags": [ "eloquent", "Eloquent library" ] } ] }