Freeware for education

 

Freeware for education

(a useful and interesting project: data monitoring and transmission)



Some time ago, I dedicated myself to writing a book, which I consider to be the best representation of my calling card: MMC – Measurement – Monitoring – Control.

It's a book I wrote with passion, and I hope it will inspire those who have the opportunity to read it.


During this period, following some work-related needs and drawing inspiration from that book, I would like to propose an educational project that I believe can be useful for understanding the technical field in which we operate to perform simple monitoring, in this case of a parameter related to the temperature of a liquid stored inside a silo.

The measured value will be transmitted to a "remote station," while "locally" the data will be displayed on an LCD screen. Of course, by checking this data against a reference parameter, it can be used to generate an alarm signal.

For some, this might be a "simple little project," while for others, it could be something "complex," something "not easy to achieve." These "points of view" depend on perceptions influenced by many factors that are always subjective, something individual, inherent in the personality of those who approach an operational experience in this field. Each of us has a personal way of tackling a "mental journey," but the beautiful thing is that those who start the journey, even if unsure of reaching the destination, certainly do so by putting in their willpower, experience, and intellectual abilities, and they trace, step by step, a path in the field of "knowledge," something that can also be useful for others who, like them, will face similar experiences! Perhaps we owe this to the first person who managed to light a fire, which changed the temperature of an environment where survival was possible.

 

The Concept of Temperature

 

It's trendy to use LLMs (artificial intelligences) to express concepts; once we used dictionaries, but it's just as well. So, if we ask an LLM to provide us with a description of the concept of temperature, it might respond as follows:

"Temperature is a physical quantity that measures the degree of 'hotness' or 'coldness' of a body, representing the average kinetic energy of its particles. It is distinct from heat, which is a form of thermal energy that transfers between bodies at different temperatures until thermal equilibrium is reached. Temperature is measured with instruments like thermometers and is expressed in various scales, the most common being Celsius, Fahrenheit, and Kelvin."

Key Concepts:

Physical Definition: Temperature is a measure of the thermal state of a body, directly linked to the agitation of its molecules or atoms. The faster the particles, the higher the temperature.

Difference between Temperature and Heat: Heat is energy that moves from a hotter body to a cooler one; temperature is a measure of this condition, not the energy itself.

Thermal Equilibrium: Two bodies in thermal contact exchange heat until they reach the same temperature, at which point heat transfer ceases.

Intensive Quantity: Temperature is an intensive property, meaning it does not depend on the size of the body, but only on its internal conditions.

Instruments and Scales: It is measured with instruments like thermometers. The most well-known scales include:

Celsius (°C): Commonly used, with (0 °C) for the melting point of ice and (100 °C) for the boiling point of water at atmospheric pressure.

Kelvin (K): The unit of the International System, which has absolute zero as its starting point (0K).

Fahrenheit (°F): Mainly used in Anglo-Saxon countries.

Simple, right? To measure a temperature, you just need a thermometer, something that can change its physical state in relation to the agitation state of the particles, molecules, or atoms it is in, providing an index based on a scale of values parameterized according to "cultural" conventions. You just need something that acts as a "probe" and something that "indicates" a number, and you're all set.

The "Dictionary" regarding the term defines it as a "feminine noun":

feminine noun

1. In physics, a quantity that measures heat exchanges between bodies in thermal contact: as heat flows from those at higher temperature to those at lower temperature, the comparison between the temperature of the human body and that of objects generates the subjective sensations of hot and cold, making those objects that, being at a higher temperature, transfer heat to the body, feel warm.

 

Specifically:


  • In thermodynamics, one of the state variables, linked, according to statistical mechanics, to the average energy of the elementary constituents of the system, and which can be measured in degrees Celsius, Fahrenheit, Réaumur, and Kelvin.

  • Absolute temperature, expressed in degrees Kelvin, so called because at zero on the Kelvin scale (absolute zero), the volume and pressure of an ideal gas reduce to zero.

  • Critical temperature, the temperature at which a phase transition occurs in a thermodynamic system.

  • Critical solution temperature, with reference to a pair of liquids, the temperature at which they become completely miscible.

  • Color temperature, with reference to a light source emitting thermal radiation, the temperature of the black body whose emission spectrum best approximates the spectrum of the source (e.g., in the case of the Sun, it is 5780 K).

  • Curie temperature, the temperature above which a magnetized ferromagnetic substance becomes demagnetized because the magnetic dipoles it is composed of lose their ordered orientation.

  • Dew point temperature, see dew point.

  • In astronomy: excitation temperature, the temperature of a star deduced from the intensity of various spectral lines.


2. com.

The degree of heat of the atmosphere.

"temperature decreasing"

  • Maximum temperature, minimum temperature, the highest or lowest temperature recorded in a location or during a specific period of time.

fig.

  • Tension, a situation of latent conflict.

  • "his words raised the temperature of the meeting"



3. The degree of heat of the human body: skin temperature, internal; measuring the temperature; colloquially (absolutely), a slight feverish state.

  • "the child has a bit of a temperature"

  • Basal temperature, the body temperature measured upon waking, before the interference of other factors (e.g., movement); since it rises by a few tenths of a degree Celsius due to the influence of progesterone, its measurement is useful for women to identify fertile days.





4. archaic

  • The process of tempering steel.

    • The sharpening of the quill pen tip.

    • Temperament (in the sense of physical constitution).



Origin
From Latin temperatura ‘proper mixture (of hot and cold, wet and dry)’; in meaning 4, derived from temperare •16th century.


The fact is that, since 2019, the absolute temperature scale is defined based on the "Boltzmann Constant," whose value is defined as exact! (by convention, I say)! - This topic is also discussed in the book.

 

Meaning of Temperature Measurement

First of all, it should be noted that this parameter, which somehow refers to the "Quality" of an "Energetic State", pertains to objects that can assume a variety of existential states, depending on their "Endogenous" characteristics and the environment they are in: two bodies "in contact" will eventually reach the same temperature, with heat transferred from one system to another in accordance with the principle of energy conservation, through "Conduction."

Between a solid and a fluid, this phenomenon occurs by "convection," but what is intriguing is that heat transfer from one body to another also happens through "Radiation." The most classic example occurs with every "sunrise," between us (the planet Earth) and the Sun. By "convention," we assume there is a region of "Space-time" that is "Empty": the light we see, "emitted" by the sun, takes about 8 minutes to reach us. These are "Photons," traveling from the Sun's surface and striking the "bodies" on this planet at an estimated speed of about 299,792,458 meters per second.

To us, an incredible speed, but a "Photon" doesn't even notice the passage of time! Also, from its "Birth" to its exit from the sun, thousands of years may pass without it noticing; furthermore, for the "Photon," being "In the Sun" or arriving "On Earth" probably makes no difference: its existence might be a "Non-local" phenomenon, as far as I can imagine!

The fact is, in the "so-called vacuum," there is cosmic radiation, "There are photons that "Travel," that move, that "Vibrate," so to speak, or rather, "There are electromagnetic radiations" (CMB, from the English cosmic microwave background), so, to this minimal energetic activity, of "agitation"... corresponds a "Temperature": about 2.73 K!

Note: by definition (we might say)... "Photons" are "Massless" particles, but they can be identified as "Vectors" that carry "Quantities of energy"... to put it simply.

Incidentally: mass is considered "The measure of a body's inertia", that is, the measure of the resistance a body offers to a change in its state of rest or motion, so if "a body" is at rest, it is "Well-defined," but if it is "in motion," relative to a coordinate system, it might not be "Well-defined," defining its velocity of movement in reference to an arbitrary coordinate system, and defining its mass... might not be simple, there could be "Objective limits," as indeed the "Heisenberg Uncertainty Principle" suggests.

Heisenberg demonstrated that it is not possible to know two conjugate variables precisely at the same instant in time. In his case, the two variables were the electron's velocity (momentum) and its position in the described orbit: increasing the precision of one measurement inevitably affects the other.

Note that in "Classical Mechanics," the momentum of an object is a vector quantity defined as the "Product of the object's mass and its velocity."

In billiards, the momentum of a ball is transferred to others through collision (I learned this during the hours Umberto Cibien and I preferred to spend outside of school, whose mathematics texts I reference on the site https://www.academia.edu/).

It is important to note that momentum and energy are related: if the former is the product of mass (m) and velocity (v) → (p=mv), the latter (kinetic energy) can be expressed by the following relation: , then, the relationship between kinetic energy and momentum can be expressed through this relation: 

In the theory of relativity, the relationship is more general and links the total energy (E) to the momentum (p) through the relativistic Pythagorean theorem: where (m0) is the rest mass and (c) is the speed of light.

However, "Relativistic" momentum takes into account a relational factor between the "Velocity of an object" and the "Speed of light": the Lorentz factor, which is expressed by this equation:, Therefore, the relativistic momentum is expressed as: pr = ɣmv

It should be noted, then, that in general relativity, the rest energy (m0), which represents the energy possessed by a stationary object, is zero for a photon, as it has no mass.

Therefore, the energy of a photon is E = prc (it is radiation, a wave form!).

So, when there are "Collisions" or even "Interferences," "Confusion" is generated: could a single photon exist in a "Spacetime Point"? I don't think so! Rather, we might talk about a "Spacetime Region," but in this case, we should refer to the "Planck Length", which takes into account the "Gravitational Constant," the "Speed of photon transfer (the speed of light)," and a value of "Proportionality" between energy quantities and "Oscillatory frequencies" of these strange "Massless Particles" that carry "Energy" from one "point to another" in a "Multidimensional Environment."

Incidentally, the Planck length is the fundamental unit of length in the Planck unit system, with a value of approximately 1.6167 x 10-35 meters, representing the smallest possible length scale, below which physical relationships derived from mathematical formulas, combining "Quantum Mechanics" and "General Relativity" theories, would no longer be applicable.

In other terms, the Planck length is "the measure of the radius of the event horizon" of a "Planck Mass" and helps define, when referred to the wavelength of electromagnetic radiation, "the maximum possible energy for a photon" before it "collapses" into mass form.

I emphasize that the volume of a sphere is derived using the following formula:

 

where "Lp" refers to a radius, which in this case, might coincide with the Planck length. In reality, the Planck volume is defined as the cube of the Planck distance: equivalent to approximately

1,6 * 10-105.

 

 

his volume thus represents the "Limit of physics", or the limit of applicability of current physical laws, such as quantum mechanics and general relativity. So within this volume, if there is something, it might be radiation, which could have a certain temperature (something that vibrates at a certain frequency) in this universe!

I understand that these concepts can generate some confusion, but at these levels, if we were to "Measure" the "Confusion," we would have to refer to a parameter called "Entropy": that is, the measure of the "Degree of energy dispersion"... at a given temperature.

It should be well noted that energy has a natural tendency to migrate from a hot body to a cold one, (up to that lower limit, where "Absolute Zero" would be measured! And the reverse process is not spontaneous! Moreover, doing it (adding energy) at a certain temperature involves an "energy cost," and doing it at another temperature changes the cost! Furthermore, energy, if it were "Localized or concentrated," tends to disperse and spread... even in a vacuum!

Therefore, wanting to use a temperature gradient to produce "Work," understood as the scalar product between force and displacement vectors, and calculated as W=F·s·cos(α), it would not be possible to completely transform the "Exchanged energy" into "Useful Work," as part of it will disperse into the surrounding environment as thermal energy (heat).

This means only one thing: "Substances," the matter we know, have a characteristic, that of being able to accumulate energy in relation to their "molecular geometries," and they do so by heating or cooling with a certain "Inertia."

In this sense, "Specific heat" can be defined as the energy required to increase the temperature of a given substance by one degree.

No process, therefore, can achieve 100% energy efficiency, so all energy exchange processes in the universe contribute to increasing the dispersion and diffusion of energy, as part of it is always dispersed into the environment.

Entropy is thus measurable in units of energy per temperature: a quantitative definition given by Clausius. (dS = dqrev/T).

It should be noted that there is no instrument capable of directly measuring entropy, while thermometers and calorimeters, used to measure temperature and energy exchanges, are part of the equipment for physicists and chemists but are also tools usable by ordinary people.

This seems to me a fairly "solid" basis on which to start talking about "Temperature" measurements, as it introduces a broader overview than the usual approach: "To measure a temperature, there are various methods, which refer to various types of instruments," among which, historically, perhaps we should mention Galileo's "thermobaroscope," which before 1600 devised this instrument capable of indicating a temperature change, albeit very imprecisely. However, shortly after, the "Florentine" thermometers appeared and were adopted throughout Europe, but at that point, the problem was "The measurement scales"...

Who doesn't remember liquid thermometers? Those that use the different thermal expansion between a liquid and its glass container. I remember very well the mercury ones (replaced for ecological reasons with Galinstan ones—gallium, indium, and tin) and the alcohol ones, but these instruments have a limited measurement range compared to the spectrum of possible measurements. Just think that, on one side, the lower limit is given by "Absolute zero," the theoretical minimum possible temperature of any thermodynamic system, while on the other, the so-called "Planck temperature" would define the maximum theoretical temperature achievable by particles (photons).

(≈1,41679×1032 K). (which would cause a black hole to evaporate!).

A liquid thermometer, when placed under the armpit, receives energy in the form of "collisions" of particles that transfer as vibrations to the glass and the liquid, which evidently increases in volume as it heats up, if the body temperature is higher than the ambient temperature.

However, modern thermometers detect temperature from a distance by exploiting the radiation of light rays emitted by a body, including stars and celestial bodies! And light "travels in a vacuum," following non-linear geodesics in relation to the deformation of "Spacetime."

 

 

Temperature Sensors

Modern ones are transducers because they convert the temperature into an electrical quantity (an analog potential difference parameter), which is usually converted into digital data. These sensors are differentiated into contact or non-contact temperature sensors.

Among contact temperature sensors, the most common are thermocouples and resistance thermometers, made of thermoresistive materials or RTDs – Resistance Temperature Detectors, or thermistors, as they were called in my time.

Sensors that do not require contact with the substance to be measured are infrared thermometers or optical pyrometers, namely, infrared thermal cameras.

But the oldest ones originated from the studies of Alessandro Volta towards the end of the 1700s, and were further developed by Thomas Johann Seebeck in the early 1800s, particularly for the use of thermocouples. These are made of two metallic conductors joined at one point ("hot junction," where the measurement is taken) and connected at the other two ends to a terminal block ("cold junction"), which is in turn connected to the measuring instrument.

Simplifying the description of the operating principle, I would only refer to the fact that different materials have different molecular compositions and therefore geometries and dynamics that respond differently to "collision stresses," resulting in a change in the electromagnetic field state due to the temperature difference between their junctions (cold and hot), which results in a measurable electrical potential difference on the order of a few μV per degree Kelvin or Celsius.

Based on the fact that the temperature value of a material is a "function" of a dynamic molecular state, there are materials that, in relation to the increase in temperature they are subjected to, assume different "resistivity" values. Some increase their specific resistance, while others decrease it. In particular, there are thermoresistances: RTD – Resistance Temperature Detector and thermistors or temperature-sensitive resistors.

Specifically, thermistors can be NTC – Negative Temperature Coefficient, with a negative coefficient, or PTC – Positive Temperature Coefficient, with a positive coefficient.

But, as mentioned above, there are instruments that measure the light radiation emitted by bodies, such as "optical pyrometers", which use a lens to direct the object's radiation onto a receiver. This radiation is first converted into an electrical signal and then digitally processed to be displayed on a screen, generating a thermal image that represents the heat distribution of the reference object.

At the core of everything are "Vibrations," states of "Particles" that change position and endogenous characteristics to the point of being considered as "Waves" or "corpuscles"

For macroscopic objects, the "wavelength" is so small that it is negligible, but for subatomic particles like electrons, the wavelength is comparable in size to atomic structures, making wave effects observable and measurable.


The Datalogger

It is an electronic device that automatically records data such as temperature, humidity, the presence of gases in certain atmospheres, physical states of solids or liquids, and, of course, values of frequency, voltage amplitude, or electrical current over time, using internal or external sensors.

This type of device is used to monitor and analyze specific conditions in various sectors, from the space industry to agriculture, and can range from simple models to complex systems with the possibility of alarms, real-time data download via wireless, and automatic reports.

Historically, the first instrument conceptually similar to a datalogger was built by Charles Babbage in the 1800s, who connected a mechanical dynamometer to a railway wagon to record various parameters on a roll of paper.

In 1901, the magazine "L’elettricità" published the creation of an instrument capable of detecting electrical discharges produced by lightning, with the recording of the time of the phenomenon, by Prof. Pietro Lancetta.

Of course, there are all types available on the market, but I think it might be interesting to propose the construction of a simple datalogger for temperature monitoring, as this can be accessible to many people both economically and educationally.

Modern dataloggers are electronic devices that can be miniaturized, some of which can even be disposable! Used, for example, in temperature-controlled transport.

Naturally, the combination of electronics and computer science allows for continuous evolution between "Hardware" and "Software," and in particular, low-cost components, such as boards containing microcontrollers, and software platforms are available to a wide audience, with which programs capable of processing and transmitting data remotely can be produced.



So, in summary, a datalogger consists of:

  • One or more probes or sensors for measuring physical quantities

  • A board for data processing and transmission

  • A display for data visualization

  • Software for data processing and transmission


An Educational Example

As previously mentioned, let's suppose we want to measure the temperature of a liquid contained in a silo using a temperature probe, perhaps setting two threshold parameters to detect a minimum and maximum storage temperature.

The hardware components used for this project are listed below:

  • A DS18B20 probe

  • A Raspberry Pi Pico-W (to be used as a client)

  • An IIC LCD1602 display

  • A USB power supply

  • A containment box (IP55)

  • Screws, cables, and accessories



Optional:

  • A Raspberry Pi to be used as a remote server



Necessary:

  • A PC for software programming (or an equipped Raspberry Pi).

 

Image generated by https://nanobanana.ai/


The DS18B20 Probe

The DS18B20 module consists of a sensor capable of measuring temperatures from -55 to +125 degrees Celsius with an accuracy of 0.5 degrees. It also includes a signal converter chip that converts analog signals to digital and can perform additional functions.

 

 

The module is powered by a source ranging from 3 to 5.5 volts and has its own serial number (each DS18B20 module has a unique serial number).

The acronym for the serial number of electronic components, such as IMEI, stands for International Mobile Equipment Identity, a unique 15-digit code that identifies each mobile device. It should not be confused with the serial number (S/N), which identifies devices of the same series.

 

 

This particular feature allows for multiple modules to be connected, as the software available in libraries (C++ or MicroPython) can recognize the number and thus provide the temperature of each individual environment where a module is located.

The chip features non-volatile memory where two temperatures (typically a minimum and a maximum) can be stored. If these thresholds are exceeded, it sends an alarm signal, always in the form of digital pulses, which can be read and interpreted by a hardware board.

The module can also be powered by the energy present on the data line, allowing connections to be limited to just ground and the data line.

The thermometer's resolution is programmable from 9 to 12 bits with a latency time of 750ms.

The block diagram of the probe can be inferred from the following image:

 

 

The classic schematic for the electrical connection (with the possibility of connecting another probe on the data line)

 

The main functionality of the DS18B20 is its direct digital temperature sensor.

The resolution of the DS18B20 is configurable (9, 10, 11, or 12 bits), with 12-bit readings as the factory default setting. This corresponds to a temperature measurement resolution of 0.5 °C, 0.25 °C, 0.125 °C, or 0.0625 °C.

 

The data conversion is represented in two bytes:

 


 

 

The "1-Wire" bus is a system with a single bus master and one or more slaves: the DS18B20 acts as a slave.

The 1-Wire bus has only one line for data transmission and reception, by definition; therefore, it is crucial that every device on the bus can drive it at the appropriate time.

Every device connected to the 1-Wire bus must have open-drain or tri-state outputs. The 1-Wire port of the DS18B20 (DQ pin) is open-drain with an internal circuit equivalent to the one shown in the Figure:

 

 

A multidrop bus consists of a 1-Wire bus with multiple connected slaves.

The 1-Wire bus requires a pull-up resistor of 4.7kΩ.

The DS18B20 requires strict protocols to ensure data integrity.

The protocol consists of several types of signaling on a line: reset pulse, presence pulse, write 0, write 1, read 0, and read 1.

All these signals, except for the presence pulse, are initiated by the bus master.

In summary: the bus master transmits (TX) a reset pulse (a low signal for a minimum of 480 µs). The bus master then releases the line and switches to receive mode (RX). The 1-Wire bus is brought to a high state via the 4.7k pull-up resistor.

After detecting the rising edge on the DQ pin, the DS18B20 waits 15-60 µs and then transmits the presence pulse (a low signal for 60-240 µs).

The write command: [4Eh], writes to the DS18B20's scratchpad memory, starting at the "TH" register. The next 3 bytes written will be saved in the scratchpad memory, at address positions 2 to 4. All 3 bytes must be written before a reset is executed.

The read command: [BEh], reads the contents of the scratchpad. Reading will start from byte 0 and continue through the scratchpad until the ninth byte (byte 8, CRC) is read. If not all positions need to be read, the master can issue a reset to terminate the reading at any time.

The conversion command: [44h], initiates a temperature conversion. No further data is required. The temperature conversion will be performed, and then the DS18B20 will remain idle. If the bus master issues read time slots after this command, the DS18B20 will output 0 on the bus while it is busy performing a temperature conversion; it will return 1 when the conversion is complete.

If powered by a parasitic device, the bus master must enable a strong pull-up for a period greater than “tconv” immediately after issuing this command.

The flowchart of the device's functionality (part 1):

 

 

The flowchart of the device's functionality (part 2):

 

 

The flowchart of the device's functionality (part 3):

 

Command Table:

 

 

Important Note: Temperature conversion requires up to 750 ms. After receiving the Convert T protocol, if the component does not receive power from the VDD pin, the DQ line for the DS18B20 must be held high for at least a period longer than tconv to provide power during the conversion process. Therefore, no other activity can take place on the 1-Wire bus for at least this period after issuing a Convert T command.

 

Typical Error Curve:

 

 

The Raspberry Pi Pico-W

The Raspberry Pi Pico-W is a "Microcontroller" from the Raspberry family. It could be described as a small computer on a single chip that integrates a CPU, memory (RAM and ROM/Flash), and various input/output (I/O) peripherals, also featuring a port for WIFI connectivity.

It is worth noting that the main difference between a microcontroller (MPU, Micro Processor Unit) and a microprocessor (CPU) is that the processing unit "CPU" (the microprocessor or Central Processing Unit) requires external components (memory, I/O), while a microcontroller is a single chip that integrates CPU, memory (RAM and ROM), and input/output peripherals.

This makes microcontrollers ideal for embedded and low-power applications like household appliances, whereas microprocessors are used for general-purpose and high-performance tasks such as in computers.

This is its layout:

 

The components of the Raspberry Pi Pico – W can be identified in the following list:

  • RP2040 microcontroller chip designed by Raspberry Pi in the United Kingdom

    • Dual-core Arm Cortex M0+ processor, with a flexible clock running up to 133 MHz

    • 264KB of SRAM, and 2MB of on-board flash memory

    • USB 1.1 with device and host support

    • Low-power sleep and dormant modes

    • Drag-and-drop programming using mass storage over USB

    • 26 × multi-function GPIO pins

    • 2 × SPI, 2 × I2C, 2 × UART, 3 × 12-bit ADC, 16 × controllable PWM channels

    • Accurate clock and timer on-chip

    • Temperature sensor

    • Accelerated floating-point libraries on-chip

    • 8 × Programmable I/O (PIO) state machines for custom peripheral support

    • Wireless (802.11n), single-band (2.4 GHz)

    • WPA3

    • Soft access point supporting up to four clients

    • Bluetooth 5.2



The Raspberry Pi Pico W series devices support programming languages like C/C++ or MicroPython.

These devices feature a BOOTSEL button that is used to put the equipment into bootloader mode—essentially a mass storage mode—when connected to a computer via USB. In this mode, the Pico appears as a USB drive named "RPI-RP2," allowing you to easily drag and drop the firmware or “uf2” code to update or program it.

 

The IIC LCD1602 Display

module uses the widely popular LCD (Liquid Crystal Display) 1602C, which has 16 characters and 2 lines. It includes a converter to the "I2C bus," allowing it to connect to the control circuit with just two wires.

 

 

 

The block diagram of the device:

 

Main Features:

Data Transmission Bus:

 

signals:

 

 

 

The I2C Protocol

The "I2C" (Inter-Integrated Circuit) transmission protocol is a two-wire serial bus developed by Philips, used for communication between multiple devices on the same motherboard or between different integrated circuits. It operates on a master-slave model, where the master controls the communication and the slaves respond. The two fundamental lines are SDA (Serial Data) for data and SCL (Serial Clock) for transmission synchronization.

How it works:

By observing the signal graph shown above, the following processes can be deduced:

Start:

  • The master signals the start of communication by pulling the SDA line from high to low while SCK is high.

Addressing:

  • The master sends the unique address of the slave it wants to communicate with.

Read/Write:

  • The master sends an additional bit indicating whether it needs to read from or write to the device.

Data Transfer:

  • Data is exchanged bit by bit, synchronized by the SCK signal.

  • After each byte, the receiver sends an "ACK" (Acknowledgement) signal to confirm receipt.

Stop:

  • The master signals the end of communication by pulling the SDA line from low to high while SCK is high. 

     

     

    A USB Power Supply

    Universal Serial Bus, commonly known as USB, is simply an interface designed to simplify the connection between computers and peripherals like keyboards, mice, scanners, printers, digital cameras, and mobile phones. USB was initially designed by American companies, particularly Intel, IBM, and Microsoft Corporation, in the mid-1990s. The idea was to provide a standard method for connecting various peripherals to computers. Since then, USB has evolved and replaced many specialized connectors with a standard USB interface.

    USB acts as a bridge between the host and the peripheral, performing two functions: data transmission and powering peripherals.

    A standard USB interface consists of four pins: two for data transfer and two for power. The data transfer pins are used for sending and receiving data, while the power pins are used for providing +5 V power and ground connection (GND). Each of the wires, of course, is marked with a unique color.

     


A USB Power Supply is powered by the single-phase network (230V - 50Hz) in Italy, and its output can vary from 500mA for USB 2.0 to 1.5A for USB BC 1.2, reaching up to 3A for standard USB-C ports.

 

 

Types of USB

USB technology offers a variety of types and configurations to meet specific device needs. The most common USB types are USB Type-A, USB Type-B, Micro USB, Mini USB, and USB Type-C.

  1. USB Type-A: Type A is the standard rectangular connector commonly found on computers, flash drives, and chargers. There are two versions of Type A connectors: male (plug) and female (socket). The female (socket) is found on the host controller, while the male (plug) is found on peripheral devices like keyboards, mice, and other devices. The USB Type-A pinout consists of four pins, two for data transfer and two for power. However, a newer version of USB Type-A consists of nine pins. USB Type-A connectors are widely used in personal computers, mobile phone chargers, gaming devices, smart TVs, and stereo systems.



  1. USB Type-B: These connectors are square-shaped and are mainly found on scanners and printers. Type B ports are upstream connectors found only on peripherals. Just like the USB Type-A connector, the Type B connector also has four pins (VCC, D+, D-, and GND). USB 3.0 and later versions feature nine pins with an additional five pins for higher data transfer speeds.



  1. Micro USB: As the intelligence of modern devices advanced, traditional USB Type-A and USB Type-B connectors became less suitable. This led to the creation of Micro USB connectors. Unlike Type-A and Type-B connectors, Micro USB connectors are smart, compact, and smaller. The Micro USB connector pinout is different from that of Type-A and Type-B connectors. The Micro USB connector consists of five pins: power pins (VBUS (+5V), GND), data transfer pins (D+, D-), and an identification pin (ID). The Micro USB connector is widely used in smart devices like mobile phones, gadgets, tablets, audio systems, wireless headphones, and other portable devices.



  1. Mini USB: The Mini USB connector was initially designed for digital cameras and older smartphones. Mini USB connectors are larger than Micro USB and smaller than Type-A/Type-B connectors. The pin configuration of Mini USB and Micro USB is the same: power pins (VBUS (+5V), GND), data transfer pins (D+, D-), and an identification pin (ID).



  1. USB Type-C: The USB Type-C connector is a reversible connector, meaning it can be used for both the host and devices. USB Type-C connectors have gradually replaced Type-A/Type-B connectors. Among all connector types, the USB Type-C connector offers the highest data transfer speed (up to 10 Gbps). The USB Type-C connector has a 24-pin configuration, which will be discussed in the next section. USB Type-C connectors are among the most widely used, with applications including, but not limited to, digital cameras, smartwatches, rechargeable earbuds, and game controllers, as well as miniaturized equipment.



USB Connectors:

 

Each pin on the connector has a specific function, depending on the type of connector, as well as the power it can deliver.

 
 
 

USB cables are designed to meet specific connectivity needs for data transfer and power supply.



  1. USB Type-A to Type-B Cables: Standard USB cables are used to connect devices like computers, scanners, and printers. Applications include file transfer and device charging. The wiring diagram from USB Type-A to Type-B features four wires (VCC, D-, D+, and GND).

  • Mini USB Cables: Most portable devices use Mini USB Type-A cables, such as digital cameras, electronic devices, and MP3 players. Mini USB cables had a compact design but have been replaced by Micro USB cables due to technological advancements.

  • Micro USB Cables: Until recently, most modern devices, like power banks, smartphones, tablets, and digital cameras, used Micro USB cables for their compact design. The wiring diagram of a Micro USB cable includes five wires (VBUS, D-, D+, ID, GND). The pin configurations of Micro USB and Mini USB are the same, but they differ in size. Both have an additional pin for mode identification.

  • USB Type-C Cables: In today's modern technology, USB Type-C is the most versatile, fast, and reliable among all. Type-C cables are found in most modern devices, including gaming computers, modern digital cameras, smartwatches, and earbuds. The wiring diagram of a Type-C cable features 24 pins.

 

The Enclosure Box

For housing the equipment, it is sufficient to modify a junction box with an IP55 protection rating:

 

 

Equipping it with suitable cable glands:

 

 

 
 

Of course, the modification will compromise the protective characteristics of the box, but by applying a suitably sized plexiglass sheet and some accessory adjustments, it will be possible to protect the LCD display from dust and even potential water splashes.

 

 

 

IP Protection Ratings

IP (International Protection or Ingress Protection) ratings indicate the resistance of a device to foreign solid objects (first digit) and liquids (second digit). The first digit ranges from 0 (no protection) to 6 (dust-tight), while the second digit ranges from 0 (no protection) to 9 (resistant to high-pressure water jets).

In reality, the complete IP code is structured as follows:

  • First Digit: Protection of people against contact with hazardous parts and protection of materials against the ingress of solid objects.

  • Second Digit: Protection of materials against harmful ingress of water.

  • Additional Letter: Used when the protection of people against contact with hazardous parts is higher than the protection against the ingress of solid objects required by the first characteristic digit.

  • Supplementary Letter: Used to provide additional information related to the material.



NOTE: When a characteristic digit is not required, it is replaced by the letter "X" ("XX" if both digits are omitted). Additional and/or supplementary letters can be omitted without being replaced.

 

 

Software

The etymology of this word likely refers to a "technical interpretation," stemming from the necessary distinction between the physical part (hardware) of a data processing system or machine and the "intangible" part related to the instructions referenced by algorithms (software), "coined" by mathematician John Tukey in 1958.

The term "Software" is generic and refers to both the programs and the data processed by modern equipment, but it can generally be categorized in different ways:



  • System Software: The basic software that manages the essential functions and resources of the machine, such as the operating system (e.g., Windows, macOS, Android).

  • Application Software: Programs that users use to perform specific tasks, such as spreadsheets, web browsers, video games, and smartphone applications.

  • Programming Software (languages): Tools used by developers to create other software.



There is a part of the software closely linked to the hardware necessary for data processing, the system software, which consists of an operating system (its core, called the kernel) solely dedicated to managing the hardware and resources of the device, and other essential components like the file system for data organization, drivers for communication with peripherals, and the user interface that allows the user to interact with the system. It also includes utility programs and firmware (like the BIOS).

The Raspberry Pi Pico-W does not have a true BIOS but boots from a "bootloader" called UF2, which is mounted as a disk drive (RPI-RP2) when the board is connected to the PC while holding down the BOOTSEL button. The UF2 file (USB Flashing Format) is "firmware" that can be easily loaded onto the Raspberry Pi Pico-W by connecting it to a computer, allowing a functional interpreter for "Embedded" systems: MicroPython.

 

 

MicroPython

As the name suggests, it is a programming language derived from Python(3) and specifically implemented to be used on devices with "limited resources" and to operate at a "low level," through specifically designed modules architected to interact with Input/Output devices.

The entire "core" of MicroPython is available for general use under the very liberal MIT license. Most libraries and extension modules (some of which are third-party) are also available under the MIT license or similar (OPEN SOURCE). You can freely use and adapt MicroPython for personal, educational, and commercial product use.

This language is written in "C99," a language designed by Dennis Ritchie in the 1970s to develop the UNIX operating system, thus a "code" very oriented towards hardware and the machine, rather than the human.

MicroPython, however, has aspects more oriented towards the programmer:



Main Features:

  • Lightweight and Efficient: It is optimized to run on devices with limited resources.

  • Easy to Use: Brings the benefits of Python, such as clear syntax and high productivity, to the embedded world.

  • Hardware Access: Includes specific modules that allow the programmer to directly control hardware, such as sensors and input/output pins.

  • Interactivity: Offers an interactive prompt (REPL) that allows executing commands and testing code in real-time.



Advantages:

  • Faster Development: Allows writing and testing code more quickly compared to traditional languages like C or C++.

  • Greater Code Reuse: Code written in MicroPython is more portable across different devices, reducing development time.

  • Accessible to Makers: Makes microcontroller programming more intuitive for a broad audience, such as makers.



MicroPython is developed in an open-source manner on GitHub, 
and the source code is available on the GitHub page and the download page.


Program Overview

The code written in MicroPython can be summarized as follows:

Main Logical Flow (Main Loop)

The program is essentially an infinite loop (while True) that manages three main operations with different timed intervals:

  1. WiFi Connection Check (every 60 seconds).

  2. Sensor Reading and LCD Display Update (every 30 seconds).

  3. Data Sending to Server (every 240 seconds).


Pseudocode:

START

INITIAL CONFIGURATION

Attempt WiFi connection (wlan = connect_to_wifi())

Initialize DS18B20 and LCD I2C 

If LCD is initialized:

Display "Pico W Client" and "Starting..."

Set TIMED COUNTERS (last_read_time, last_send_time, last_check_time)

Set ALARM THRESHOLDS (MIN_TEMP_ALARM, MAX_TEMP_ALARM)

alarm_on = FALSE

START MAIN LOOP (WHILE TRUE):

current_time = current time

 

# 1. Connection Check (Every 60s)

IF current_time - last_check_time >= 60:

wlan = check_connection(wlan)

last_check_time = current_time


# 2. Reading and Alarms (Every 30s)

IF current_time - last_read_time >= 30:

temperature = read_temperature()

motor_on = FALSE

alarm_on = FALSE


**# ALARM CHECK**

IF `temperature IS NOT None`:

IF `temperature <= MIN_TEMP_ALARM OR temperature >= MAX_TEMP_ALARM`:

`alarm_on = TRUE` (Temperature Alarm)


**# MIXER CHECK**

IF `MIX == TRUE`:

`motor_on = read_mix()` # Blocks for 3s, checks rotation

IF `motor_on == FALSE`:

`alarm_on = TRUE` (Mixer Stopped Alarm)

 

 **# LCD UPDATE**

IF LCD is initialized:

`update_lcd(temperature, alarm_on)` # Displays alarm if active

`last_read_time = current_time`


# 3. Data Sending (Every 240s)

IF WiFi connected AND current_time - last_send_time >= 240:

IF temperature IS NOT None AND temperature IS available:

IF send_data_to_server(temperature) IS TRUE:

last_send_time = current_time # Update only on success

ELSE:

Print "Send failed"

ELSE:

Print "Data not available"


Pause for 1 second (time.sleep(1))

END LOOP

END


Going into more detail:


  1. connect_to_wifi(ssid, password)

This block represents an initialization flow with a loop and timeout.

FUNCTION connect_to_wifi(ssid, password):

  • Activate WLAN (STA_IF)

  • Attempt connection (wlan.connect)

  • max_wait = 20

  • WHILE LOOP max_wait > 0:

    • IF connection Successful OR Failed (status < 0 OR status >= 3):

      • EXIT LOOP (break)

    • ELSE:

      • Wait 5 seconds

      • max_wait = max_wait - 1

  • IF wlan.isconnected() IS TRUE:

    • Print "Connection successful" and the IP

    • RETURN WLAN Object

  • ELSE:

    • Print "Connection failed"

    • RETURN None


2. read_temperature()

Flow for reading the DS18B20 sensor.

FUNCTION read_temperature():

  • TRY:

    • IF No sensor found (roms empty):

      • RETURN None

  • Send conversion command to the sensor (ds_sensor.convert_temp())

  • Wait 750 milliseconds

  • temperature = Read value from the first sensor (roms[0])

  • RETURN temperature rounded to 2 decimal places

  • EXCEPTION (If reading fails):

    • Print the error

    • Attempt a reset (ds_sensor.convert_temp())

    • RETURN None 

       

3. read_mix()

Flow for monitoring the MIX/Agitator, based on a time-limited loop.

FUNCTION read_mix():

  • motor_on = FALSE

  • interval_time_seconds = 3

  • time_start = current time in ms

  • START LOOP (Monitoring for 3 seconds):

    • current_time = current time in ms

    • pin_state = mix_pin.value()

  • DECISION: Signal detected (falling edge, 1 -> 0)

    • IF pin_state == 0 AND last_signal == 1:

      • motor_on = TRUE

      • Print "Rotation detected"

      • EXIT LOOP (break)

  • DECISION: Time Limit exceeded

    • IF current_time > time_start + 3000ms:

      • EXIT LOOP (break)

  • last_signal = pin_state

  • Wait 0.5 seconds

  • IF motor_on IS TRUE:

    • Print "Rotation detected"

  • ELSE:

    • Print "No rotation detected"

  • RETURN motor_on (True or False)  

     

4. update_lcd(temp, alarm_status)

Flow for conditional display on the LCD.

FUNCTION update_lcd(temp, alarm_status):

  • IF lcd IS None: RETURN (quick exit)

  • Clear LCD

  • DECISION: Alarm Active?

    • IF alarm_status IS TRUE:

      • Line 1: Display the temperature

- **SPECIFIC ALARM DECISIONS** - IF `temp <= MIN_TEMP_ALARM`: - Line 2: "ALARM! < MIN_TEMP_ALARM" - ELSE IF `temp >= MAX_TEMP_ALARM`: - Line 2: "ALARM! > MAX_TEMP_ALARM" - Wait 1 second - ELSE IF `motor_on == FALSE`: # Mixer alarm - Line 2: "ALARM MIX"
  • DECISION: Normal State or Error

    • ELSE IF temp IS NOT None:

      • Line 1: Display the temperature (Normal format)

      • Line 2: "CP4 TS_gr" (Standard message)

    • ELSE:

      • Line 1: "Temp: N/A"

      • Line 2: "Reading Error"



5. send_data_to_server(temp)

This function handles the preparation of the URL and the sending of the HTTP GET request to the server (Raspberry Pi/ or Ubuntu PC), including error handling.

FUNCTION send_data_to_server(temp):

  • IF temp IS None:

    • Print "Invalid data, skipping send."

    • RETURN FALSE

  • url = SERVER_URL / temp

  • TRY:

    • response = Send HTTP GET request to url

  • DECISION: Server OK?

    • IF response.status_code == 200:

      • Print "Data sent: X°C, Server OK."

      • Close the response

      • RETURN TRUE

    • ELSE:

      • Print "Server Error: Status Code Y"

      • Close the response

      • RETURN FALSE

  • EXCEPTION (Connection or HTTP Error):

    • Print "Error sending data to server: E"

    • RETURN FALSE



Optional Integration of the Main Loop

This is a part of the block within the while True loop that checks the 240-second interval and calls the data transmission function via an HTTP GET request. The logic is crucial: it updates the last send time only if the send was successful.

 
 

... (Part of the Main Loop) ...



# 3. Sending Data to Server (Every 240 seconds)

IF wlan is connected AND current_time - last_send_time >= 240:



# DECISION: Is there valid temperature data to send?

IF temperature IS defined AND temperature IS NOT None:



# DECISION: Did the function call succeed?

IF send_data_to_server(temperature) IS TRUE:

last_send_time = current_time # Success: update the timer for the next send

ELSE:

Print "Data send failed, forwarding to the next send interval."

# NOTE: last_send_time is NOT updated, forcing a retry

# as soon as possible after the pause (time.sleep(1))

ELSE:

Print "Temperature data not yet available for sending."



# ... (End Loop) ...


Specifications:

The GET request is an HTTP method used to request data from a web server. Unlike POST, which sends data in the body of the request, GET adds parameters directly in the URL after a question mark (?), separated by an ampersand (&). This type of request is considered idempotent (the same result is obtained by repeating the request) and its results can be cached, making it suitable for retrieving resources that do not change frequently.




Program Code:

The program installed on the Raspberry Pi Pico W is written in MicroPython and reflects the pseudocode outlined above. The proposed version is one of the very first beta releases (R.beta_0.2). A software release is a "version" of a program that identifies the "state of the art." Releases can be "major" for significant changes or "minor" for smaller updates, such as patches.

Purpose of a Release:

  • Introduction of New Features: Adds new characteristics and options to enhance the usability and value of the software.

  • Bug Fixes: Resolves errors and malfunctions present in previous versions.

  • Performance Improvements: Optimizes the software's efficiency to make it faster and more responsive.

  • Security Updates: Introduces changes to protect the software from vulnerabilities and threats.

  • User Experience Enhancements: Sometimes includes changes to the design or workflow to make the interface more intuitive.

  • Support and Compatibility: Ensures the software remains compatible with new operating systems or other devices.



Alpha Phase:

  • Internal Testing: The software is primarily tested within the company by the developers themselves.

  • Incomplete Features: Features may not be fully implemented, and bugs are frequent.

  • Objective: Identify and correct the most severe bugs before making it available to external users.



Beta Phase:

  • External Testing: The version is made available to a selected group of external users (called beta testers) or the public.

  • Complete Features: The software is more stable and complete compared to the alpha version.

  • Objective: Gather feedback on usability, performance, and identify residual bugs not found in internal testing.



After the Beta Phases:

  • After the beta phase, the software can move to the "Release Candidate" (RC) phase, which is the last version before the final release.

  • Once all critical bugs are resolved, the official and stable version of the software is released. (See recommended reading for further insights)

 
 main.py
# main.py (Pico-w) release Beta_0.2
# funziona e trasmette al server il dato temp
import time
import machine
import network
import urequests as requests

# DS18B20 Imports
import onewire, ds18x20

# I2C LCD Imports
from machine import I2C
# Le librerie I2C LCD (lcd_api.py e i2c_lcd.py) devono essere caricate separatamente
from LCD_API import LcdApi
from I2C_LCD import I2CLcd

# --- Configurazione Hardware e Network ---
# Impostazioni WiFi
ssid = 'SSID'
password = 'PASSWORD'

# Configurazione Server
SERVER_IP = '10.10.10.10' # Cambia con l'IP locale del PC
SERVER_PORT = 5000
SERVER_URL = f"http://{SERVER_IP}:{SERVER_PORT}/temperatura"

# Configurazione DS18B20 (Assegnato il pin GPIO 0)
DS_PIN = 0
ds_pin = machine.Pin(DS_PIN)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
# Cerca il dispositivo
roms = ds_sensor.scan()
print('Trovato DS18B20:', roms)

# Configurazione MIX
# MIX_PIN = xx
mix_pin = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_DOWN)
MIX = True
# Configurazione I2C LCD (I2C(0) con pin standard)
I2C_ADDR = 0x27 # Indirizzo I2C standard per PCF8574 (potrebbe essere 0x3F)
I2C_NUM = 0
I2C_SCL = 5 # GPIO 5 (Pin 7)
I2C_SDA = 4 # GPIO 4 (Pin 6)
LCD_ROWS = 2
LCD_COLS = 16

i2c = I2C(I2C_NUM, scl=machine.Pin(I2C_SCL), sda=machine.Pin(I2C_SDA), freq=400000)
try:
lcd = I2CLcd(i2c, I2C_ADDR, LCD_ROWS, LCD_COLS)
except Exception as e:
print(f"Errore inizializzazione LCD: {e}")
lcd = None

# --- Funzioni di Utility ---
def connect_to_wifi(ssid, password):
# global SSID, PASSWORD
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)

# Attesa connessione o timeout
max_wait = 20
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('In attesa connessione WiFi...')
time.sleep(5)


if wlan.isconnected():
status = wlan.ifconfig()
print('Connessione WiFi riuscita! IP:', status[0])
return wlan
else:
print('Connessione WiFi fallita.')
return None

def check_connection(wlan):
if wlan is None or not wlan.isconnected():
print("Connessione persa. Riconnessione...")
return connect_to_wifi(ssid, password)
return wlan

def read_temperature():
global temperature
try:
if not roms:
print("Nessun sensore DS18B20 trovato.")
return None

ds_sensor.convert_temp() # Richiede la conversione
time.sleep_ms(750) # Attesa del tempo di conversione (max 750ms per 12-bit)
temperature = ds_sensor.read_temp(roms[0]) # Legge il primo sensore
return round(temperature, 2)
except Exception as e:
print(f"Errore lettura DS18B20: {e}")
ds_sensor.convert_temp() # Prova a resettare
return None
def read_mix():
global motor_on
# Variabili per la misurazione
ultimo_segnale = 0
stato_pin = 0
intervallo_tempo_secondi = 3 # si potrebbe anche verificare la velocità di rotazione...
motor_on = False
print("Avvio del monitoraggio di rotazione utensile...")
time_start = time.ticks_ms()
while True:
ora_attuale = time.ticks_ms() # tempo attuale in millisecondi
print("ora attuale ", ora_attuale)
stato_pin = mix_pin.value()
print("stato_pin ", stato_pin)
# variante per raffreddatore o riscaldatore
# il contatto relè (NC) o (NO) rilevela che un blocco nella apparecchiatura associata
# if stato_pin == 1:
# variante per MIXER
# Controlla se il pin è passato da LOW a HIGH (rilevando un segnale MIXER)
if stato_pin != ultimo_segnale:
motor_on = True
print("Rotazione rilevata")
# Calcola il tempo trascorso dall'ultimo segnale
tempo_trascorso = time.ticks_diff(ora_attuale, ultimo_segnale) / 1000
print("tempo trascorso ", tempo_trascorso)
break
tempo_limite = time_start + intervallo_tempo_secondi * 1000
if ora_attuale > tempo_limite:
# print("Nessuna rotazione nell'intervallo di tempo prestabilito!")
break # Esce dal loop

ultimo_segnale = stato_pin
print("ultimo segnale", ultimo_segnale)
time.sleep(0.5) # Piccola attesa per non sovraccaricare la CPU
if motor_on:
print("La rotazione meccanica e' avvenuta entro il limite di tempo")
else:
print("Nessuna rotazione meccanica rilevata nel tempo specificato.")
return motor_on


def update_lcd(temp, alarm_status):
if lcd is None:
return

lcd.clear()
lcd.putstr("Temp:")

if alarm_status:
lcd.move_to(0, 0)
line1 = f"temp= {temp:.2f} C"
lcd.putstr(line1)
if temp <= MIN_TEMP_ALARM:
line2 = f"ALARM! < {MIN_TEMP_ALARM:.2f}C"
lcd.move_to(0, 1)
lcd.putstr(line2)
elif temp >= MAX_TEMP_ALARM:
line2 = f"ALARM! > {MAX_TEMP_ALARM:.2f}C"
lcd.move_to(0, 1)
lcd.putstr(line2)
time.sleep(1)
elif motor_on == False:
line2 = f"ALARM MIX"
lcd.move_to(0, 1)
lcd.putstr(line2)

elif temp is not None:
line1 = f" {temp:.2f} C"
lcd.putstr(line1)
lcd.move_to(0, 1)
lcd.putstr("CP4 TS_gr")
else:
lcd.putstr(" N/A")
lcd.move_to(0, 1)
lcd.putstr("Errore Lettura")


def send_data_to_server(temp):
if temp is None:
print("Dato non valido, salto l'invio al server.")
return False

url = f"{SERVER_URL}/{temp}"
try:
response = requests.get(url)
if response.status_code == 200:
print(f"Dato inviato: {temp}C, Server OK.")
response.close()
return True
else:
print(f"Errore Server: Status Code {response.status_code}")
response.close()
return False
except Exception as e:
print(f"Errore invio dati al server: {e}")
return False

# --- Loop Principale ---
wlan = connect_to_wifi(ssid, password)

# Contatori per le azioni temporizzate (in secondi)
read_interval = 30
send_interval = 240
check_interval = 60
last_read_time = 0
last_send_time = 0
last_check_time = 0

MIN_TEMP_ALARM = 20.0 # Soglia di allarme inferiore
MAX_TEMP_ALARM = 30.0 # Soglia di allarme superiore
motor_on = False # Motore agitatore fermo
lcd_initialized = lcd is not None # Flag per evitare loop se l'LCD non è collegato

if lcd_initialized:
lcd.clear()
lcd.putstr("Pico W Client")
lcd.move_to(0, 1)
lcd.putstr("Avvio...")
time.sleep(3)
alarm_on = False
while True:
current_time = time.time()
print("current time", current_time)
# 1. Controllo Connessione (Ogni 60 secondi)
if current_time - last_check_time >= check_interval:
print("Controllo connessione...")
wlan = check_connection(wlan)
if wlan is None or not wlan.isconnected():
print("Nessuna connessione, riprovo al prossimo ciclo.")
last_check_time = current_time

# 2. Lettura dati temperatura, stato MIXER e Aggiornamento LCD (Ogni 30 secondi)
if current_time - last_read_time >= read_interval:
temperature = read_temperature()
if temperature is not None and temperature <= MIN_TEMP_ALARM:
alarm_on = temperature is not None and temperature <= MIN_TEMP_ALARM
print("allarme temperatura bassa")
elif temperature is not None and temperature >= MAX_TEMP_ALARM:
alarm_on = temperature is not None and temperature >= MAX_TEMP_ALARM
print("allarme temperatura alta")

else:
alarm_on = False
print ("nessun allarme di temperatura")
print(f"Temperatura letta: {temperature}C. Allarme: {alarm_on}")
motor_on = False



if MIX == True and motor_on == False:
motor_on = read_mix()
print("stato di motor_ON", motor_on)
alarm_on = MIX == True and motor_on == False
print("allarme mixer fermo", alarm_on)
if lcd_initialized:
update_lcd(temperature, alarm_on)

last_read_time = current_time

# 3. Invio Dati al Server (Ogni 240 secondi)
# Si assicura di inviare l'ultima temperatura letta (quella del ciclo read_interval)
if wlan is not None and wlan.isconnected() and current_time - last_send_time >= send_interval:
# Usa l'ultima temperatura letta
if 'temperature' in locals() and temperature is not None:
if send_data_to_server(temperature):
last_send_time = current_time
else:
# Non aggiorna last_send_time in caso di fallimento,ritenta al prossimo ciclo
print("Invio dati fallito, inoltro al prossimo intervallo di invio.")
else:
print("Dato di temperatura non ancora disponibile per l'invio.")

# Pausa principale di 1 secondo per il controllo
time.sleep(1)


 


Final Considerations:

I hope this contribution is useful for those who will take some time to read it, in which I have tried to include interesting concepts of various nature, driven by the curiosity that has always accompanied me in trying to best interpret the environment in which we live.

I also hope that this "educational project," which nonetheless has a practical sense, can be shared by teachers and students of all kinds and levels, as well as by people who, for hobby or practical needs, intend to actually realize it, also because it is relatively inexpensive and can find applications of various kinds, with the necessary integrations and modifications.

"Learning to learn" is something that is usually not taught in school; one must have the spirit of a "self-taught" person. However, in these "modern times," this activity can be made enjoyable also through the use of "inferential machines."

What is usually referred to as "artificial intelligence," if used properly, can greatly facilitate learning. It can be used to "stimulate the mind" instead of "putting neurons to sleep."

Even this text, in part, was written with the suggestions of some agents that exploit LLMs, and in doing so, I must say, I also had fun. On the other hand, it made my task easier, saved me time, and gave me the opportunity to expand the context of the discussion without having to search for the information I needed in the depths of the web. This does not mean that, between the lines of what is reported, especially in the early pages, there are not hidden questions of enormous scientific relevance that would deserve further investigation, particularly regarding the counterintuitive understanding of "quantum mechanics." However, I leave this path to those who wish to pursue it with youthful enthusiasm. I, as an "old cyberneticist," am fascinated by it, like a mountain landscape that I would not know how to climb but that reminds me of the paths walked in my youth.

I thank you for reading and thank all those who have contributed in various ways to disseminating "scientific culture," free from political or religious orientations, but full of "living" and dynamic concepts that, since the beginning of time, have accompanied humanity on a fascinating journey, that journey that, starting from pictograms, has brought us to icons, passing through numbers and words. ;-)

Recommended Reading for Further Insights:

https://www.intelligenzaartificialeitalia.net/post/git-il-tool-essenziale-per-l-intelligenza-artificiale



P.S.
If humanity had learned to use
VCS (Version Control Systems), perhaps the world would be a better place!
Romeo Ceccato






 

 
 
 
 


Internet Bar (Clients and Servers)

    introduction The title is certainly ironic, but I wrote it because in this article, I would like to describe without going ...