How is the operating system able to know the battery level?

Solution 1:

The operating system interfaces with the firmware of an embedded controller that is part of the Advanced Configuration and Power Interface (ACPI).

Wikipedia defines it as :

In a computer, the Advanced Configuration and Power Interface (ACPI) provides an open standard that operating systems can use to discover and configure computer hardware components, to perform power management by (for example) putting unused components to sleep, and to perform status monitoring. First released in December 1996, ACPI aims to replace Advanced Power Management (APM), the MultiProcessor Specification, and the Plug and Play BIOS (PnP) Specification.[1] ACPI brings the power management under the control of the operating system, as opposed to the previous BIOS-centric system that relied on platform-specific firmware to determine power management and configuration policies.

Internally, ACPI advertises the available components and their functions to the operating system kernel using instruction lists ("methods") provided through the system firmware (Unified Extensible Firmware Interface (UEFI) or BIOS), which the kernel parses. ACPI then executes the desired operations (such as the initialization of hardware components) using an embedded minimal virtual machine.

The answer is then that a circuit or micro-chip is embedded in the motherboard, that itself contains a micro operating system which makes available some services via the computer firmware - UEFI or BIOS. It controls many aspects of power and device management.

The computer operating system has a system driver that is dedicated to interfacing with ACPI. Once ACPI is activated, it takes exclusive control of all aspects of power management and device configuration.

In many aspects ACPI is an operating system behind your operating system, except that it comes with the motherboard and is not under your control. There have been voices likening it to a Trojan horse and calling it a security risk. It may be disabled, but some computers may not boot without it, and advanced power management is then in any case disabled as well.

For more information about its use in Windows see the article Battery and power subsystem hardware design.

Solution 2:

As a complement to the other answer, how does the software running on the computer know what the battery level is? It asks the battery.

Most laptop batteries are smart batteries that have their own microcontroller or "fuel gauge" ASIC, which the host can communicate with over SMBus. People have reverse engineered some examples.

The SMBus may or may not be exposed directly to the operating system in a way that allows the administrator to query it directly. There are various programs like OpenHardwareMonitor or Speccy or lm-sensors that can interrogate the bus to find out about the hardware.