#include #include #include #include "pwm.h" const uint8_t PWM_SLAVE_ADDR = 9; void setup() { i2c_init(); DDRC &= ~(1 << PINC0) & ~(1 << PINC1) & ~(1 << PINC2) & ~(1 << PINC3) & ~(1 << PINC4) & ~(1 << PINC5); PORTC |= (1 << PINC0) | (1 << PINC1) | (1 << PINC2) | (1 << PINC3) | (1 << PINC4) | (1 << PINC5); Serial.begin(9600); Serial.println("PWM Controller started!"); sendCommand(0x01, 0.0); } void loop() { checkButton(0, "Turn on PWM!", enablePWM); checkButton(1, "Turn off PWM!", disablePWM); checkButton(2, "Increase frequency by 25%!", increaseFrequency); checkButton(3, "Decrease frequency by 20%!", decreaseFrequency); checkButton(4, "Increase duty cycle by 10%!", increaseDutyCycle); checkButton(5, "Decrease duty cycle by 10%!", decreaseDutyCycle); if (pwm_changed) { pwm_changed = 0; pwm_check_state(); if (pwm_enabled) { pwm_set_frequency(pwm_frequency); pwm_set_duty_cycle(pwm_duty_cycle); } } } void sendCommand(uint8_t cmd, float value) { uint16_t cmd_value; switch (cmd) { case 0x01: case 0x02: sendCommandOneByte(cmd); break; case 0x03: case 0x04: sendCommandThreeBytes(cmd, value); break; case 0x05: case 0x06: sendCommandTwoBytes(cmd, value); break; default: Serial.println("Unknown command"); break; } } void sendCommandOneByte(uint8_t cmd) { i2c_start(); i2c_write(PWM_SLAVE_ADDR << 1); i2c_write(cmd); i2c_stop(); Serial.print("Sent command: 0x"); Serial.println(cmd, HEX); } void sendCommandTwoBytes(uint8_t cmd, float value) { uint16_t cmd_value = round(value); i2c_start(); i2c_write(PWM_SLAVE_ADDR << 1); i2c_write(cmd); i2c_write(cmd_value & 0xFF); i2c_stop(); Serial.print("Sent command: 0x"); Serial.print(cmd, HEX); Serial.print(", value: "); Serial.print(value); Serial.print(", cmd value: "); Serial.print(cmd_value); Serial.print(", data bytes: 0x"); Serial.println(cmd_value & 0xFF, HEX); } void sendCommandThreeBytes(uint8_t cmd, float value) { uint16_t cmd_value = round(value * 16); // приводим к 12 бит и 4 бита дробной части uint8_t data_bytes[2] = {(cmd_value >> 8) & 0xFF, cmd_value & 0xFF}; i2c_start(); i2c_write(PWM_SLAVE_ADDR << 1); i2c_write(cmd); i2c_write(data_bytes[0]); i2c_write(data_bytes[1]); i2c_stop(); Serial.print("Sent command: 0x"); Serial.print(cmd, HEX); Serial.print(", value: "); Serial.print(value); Serial.print(", cmd value: "); Serial.print(cmd_value); Serial.print(", data bytes: 0x"); Serial.print(data_bytes[0], HEX); Serial.print(" "); Serial.println(data_bytes[1], HEX); }