microcontrolling/lib/7segment_4digits.c

60 lines
1.6 KiB
C
Raw Normal View History

2023-08-27 19:01:23 +00:00
#include <avr/io.h>
#include <stdbool.h>
#include <util/delay.h>
#include <math.h>
#include "util.h"
#include "7segment.h"
uint8_t display[4] = { 0, 0, 0, 0 };
uint8_t current_digit = 0;
2023-08-27 19:01:23 +00:00
void display_value(uint8_t digit, uint8_t data) {
// The left part sets the last 4 bits high (turns the
// according digit off) except for the one we want to address.
// The right part makes sure the first 4 bits remain unchanged.
PORTK = (0b00001111 & ~(1 << digit)) | (PORTK & 0b11110000);
PORTF = data;
}
void set_display_value(uint8_t digit, uint8_t data) {
display[digit] = data;
}
void update_next_digit() {
update_display_digit(current_digit++);
if (current_digit >= 4) current_digit = 0;
}
void update_display_digit(int digit) {
display_value(digit, display[digit]);
}
2023-09-08 08:46:07 +00:00
// Returns the amount of milliseconds we blocked for
uint32_t update_display_all_sync() {
uint32_t sleep_time_ms = 1;
2023-08-27 19:01:23 +00:00
for (int i = 0; i < 4; i++) {
2023-09-08 08:46:07 +00:00
update_display_digit(i);
_delay_ms(sleep_time_ms);
2023-08-27 19:01:23 +00:00
}
2023-09-08 08:46:07 +00:00
return sleep_time_ms * 4;
2023-08-27 19:01:23 +00:00
}
void show_float(float value) {
2023-08-29 08:58:36 +00:00
if (value >= 10000 || value < 0) {
for (int i = 0; i < 4; i++) {
set_display_value(i, 0b01000000); // minus character
}
return;
}
2023-08-27 19:01:23 +00:00
int digits = num_digits((int)value);
int full_number = value * (int)roundf(powf(10, 4 - digits));
for (int i = 0; i < 4; i++) {
bool show_period = digits == i + 1;
int digit = get_digit_at_position(full_number, 3 - i);
set_display_value(i, digit_to_binary(show_period, digit));
2023-08-27 19:01:23 +00:00
}
}