Before we start, I have a github repository with the code, so check it here
After the grub bootloader and our simple kernel, we want to start dividing our code, so I want now to have all the clear screen and print stuff into a different file. So asking ChatGPT (the good part of chatgpt is that it is not only giving the code but also suggesting next steps) he told me that putting prints in a separate file will be good. Not only that, also we can print in colors (we are using VGA mode)
Here is video.c that ChatGPT did for me:
#include "video.h"
#define VIDEO_ADDRESS 0xb8000
#define MAX_ROWS 25
#define MAX_COLS 80
// Colors (Need some more constants?)
#define WHITE_ON_BLACK 0x0F
static int cursor_row = 0;
static int cursor_col = 0;
// Writes a character on a position
static void put_char_at(char c, int row, int col, char attr) {
char *video = (char*)VIDEO_ADDRESS;
int offset = 2 * (row * MAX_COLS + col);
video[offset] = c;
video[offset + 1] = attr;
}
// Deletes screen
void clear_screen() {
for (int row = 0; row < MAX_ROWS; row++) {
for (int col = 0; col < MAX_COLS; col++) {
put_char_at(' ', row, col, WHITE_ON_BLACK);
}
}
cursor_row = 0;
cursor_col = 0;
}
// Prints a string
void print(const char *str) {
while (*str) {
if (*str == '\n') {
cursor_row++;
cursor_col = 0;
} else {
put_char_at(*str, cursor_row, cursor_col, WHITE_ON_BLACK);
cursor_col++;
if (cursor_col >= MAX_COLS) {
cursor_col = 0;
cursor_row++;
}
}
if (cursor_row >= MAX_ROWS) {
cursor_row = 0; // On overflow, wrap to the top (TODO: Scroll)
}
str++;
}
}
//Prints with a specific color attribute
void print_color(const char *str, char attr) {
while (*str) {
if (*str == '\n') {
cursor_row++;
cursor_col = 0;
} else {
put_char_at(*str, cursor_row, cursor_col, attr);
cursor_col++;
if (cursor_col >= MAX_COLS) {
cursor_col = 0;
cursor_row++;
}
}
if (cursor_row >= MAX_ROWS) {
cursor_row = 0; // Simple wrap (TODO: Scroll)
}
str++;
}
}
The interesting part of this project so far is that I thought that it was going to be like chinese for me, but for now, the code seems to be pretty simple to understand.
The other interesting part is that when I was young consoles were 80x25. Now seems to be the same, good and easy to use.
Obviously, the header was also updated adding the new functions
#ifndef VIDEO_H
#define VIDEO_H
void clear_screen();
void print(const char *str);
void print_color(const char *str, char attr);
#endif
With this, the kernel main file looks a lot cleaner, now I don't need to add the video part to it, for now I can add there things like
clear_screen();
Or to print stuff things like
print("This is a simple kernel written in C.");
Or if I want colors:
print_color("Welcome to the Pythonist OS!\n\n", 0x1E);
This will print stuff in yellow and blue.
As always I made the video (it is in spanish)
Top comments (0)