I stumble across an issue which I can't solve in multiple attempts.
I'm trying to turn on and turn off an OLED SSD1306 display attached to the hardware I2C on Atmega328PB. The device has button on PD3 and P-channel MOSFET gate attached to PD6. The problem is, the output is initialized properly and the display is on, also it turns off properly, but cannot be turned on again. (PORTD &= ~(1 << PD6))
doesn't change the state of the output.
That is confirmed and with voltmeter. As soon as comment the display libraries and code, the output pin works fine and I can flip the state. I test that with multiple different libraries in Arduino and also with C OLED libraries with avr-gcc code. Can't find anything in those libraries to interfere with the port manipulation and I'm looking for help.
#include <avr/io.h>
#include <util/delay.h>
#include "main.h"
#include "i2c.h"
#include "SSD1306.h"
uint8_t powerOn = 1;
int main(void) {
initIOs();
OLED_Init(); // Initialize the OLED
OLED_Clear(); // Clear the display
while (1) {
OLED_SetCursor(0, 0); // Set the cursor position to (0,0)
OLED_Printf("Hello World!"); // Print out some text
if (!(PIND & (1 << PD3)) && !(powerOn)) {
PORTD &= ~(1 << PD6);
_delay_ms(500);
OLED_Clear(); // Clear the display (for good measure)
OLED_SetCursor(0, 0); // Set the cursor position to (0,0)
OLED_Printf("Hello World!"); // Print out some text
powerOn = 1;
}
if (!(PIND & (1 << PD3)) && (powerOn)) {
OLED_Clear(); // Clear the display when turning off
_delay_ms(500);
PORTD |= (1 << PD6);
powerOn = 0;
}
_delay_ms(50); // Add a small delay for switch debouncing
}
return 0; // Never reached
}
void initIOs(void) {
DDRD |= (1 << PD6); // Set power switch pin as output
PORTD &= ~(1 << PD6); // Set power switch pin low
DDRD &= ~(1 << PD3); // Set power button pin as input
PORTD |= (1 << PD3); // Set power button pin pull-up resistor
_delay_ms(100); // Delay for stabilization
}
```