2026-02-22: Intro: OS And C++ (Live Demo)#
Note
This session was entirely live demonstrated by teacher. No need to repeat all the steps.
Login to Pi at home:
ssh -p 2022 jfasch.bounceme.net
$ ls -l /sys/class/hwmon/
$ ls -l /sys/class/hwmon/hwmon2/
Show how to use that sensor from the commandline (Linux and OneWire (using DS18B20 Temperature Sensor as Slave))
Write a C program that reads the sensor value in a loop (a “data logger”, so to say). (System Calls)
Transform the sensor into a dedicated type/class (Data Encapsulation)
#include <iostream>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <string>
#include <stdexcept>
class Thermometer
{
public:
Thermometer(const std::string& filename)
{
_fd = open(filename.c_str(), O_RDONLY);
if (_fd == -1)
throw std::runtime_error("nix open");
}
~Thermometer()
{
close(_fd);
}
double get_temperature() const
{
char buffer[64];
ssize_t nbytes = read(_fd, buffer, sizeof(buffer)-1);
if (nbytes == -1)
throw std::runtime_error("nix read");
off_t newpos = lseek(_fd, 0, SEEK_SET);
if (newpos == -1) {
throw std::runtime_error("nix lseek64");
}
buffer[nbytes] = '\0';
int milli_celsius = std::stoi(buffer);
double celsius = milli_celsius / 1000.0;
return celsius;
}
private:
int _fd;
};
int main(int argc, char** argv)
{
if (argc != 2) {
std::cerr << "nix zwei argumente" << std::endl;
return 1;
}
const char* filename = argv[1];
Thermometer thermo(filename);
while (true) {
std::cout << thermo.get_temperature() << std::endl;
timespec interval = { 1, 0 };
int rv = nanosleep(&interval, nullptr);
if (rv == -1) {
std::cerr << "nix sleep?" << std::endl;
return 1;
}
}
return 0;
}