Compare commits

...

2 Commits

Author SHA1 Message Date
zloihach
9d65806d8b c++ == .ino 2023-06-21 03:02:25 +03:00
zloihach
df75af19c2 upd 2023-06-19 18:16:59 +03:00
10 changed files with 869 additions and 298 deletions

View File

@ -0,0 +1,13 @@
cmake_minimum_required(VERSION 3.22)
project(untitled2 C)
set(CMAKE_C_STANDARD 17)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR avr)
set(CMAKE_C_COMPILER avr-gcc)
set(CMAKE_CXX_COMPILER avr-g++)
set(CMAKE_C_FLAGS "-mmcu=atmega328p")
set(CMAKE_CXX_FLAGS "-mmcu=atmega328p")
add_executable(8.PMW main.c i2c.h pwm.h)

40
Wire.h
View File

@ -1,40 +0,0 @@
#define I2C_FREQ 100000UL
void i2c_begin(uint8_t address) {
TWBR = ((F_CPU / I2C_FREQ) - 16) / 2; // Расчет предделителя для заданной частоты
TWAR = (address << 1); // Установка адреса устройства
}
void i2c_endTransaction() {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO); // Отправка условия STOP
}
void i2c_beginTransmission(uint8_t address) {
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN); // Отправка условия START
while (!(TWCR & (1 << TWINT))); // Ожидание завершения START
TWDR = (address << 1); // Отправка адреса устройства
TWCR = (1 << TWINT) | (1 << TWEN); // Отправка адреса
while (!(TWCR & (1 << TWINT))); // Ожидание завершения передачи адреса
}
void i2c_endTransmission() {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO); // Отправка условия STOP
}
void i2c_write(uint8_t data) {
TWDR = data; // Запись данных
TWCR = (1 << TWINT) | (1 << TWEN); // Отправка данных
while (!(TWCR & (1 << TWINT))); // Ожидание завершения передачи данных
}
void i2c_read(uint8_t *data, uint8_t ack) {
if (ack) {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA); // Отправка ACK
} else {
TWCR = (1 << TWINT) | (1 << TWEN); // Отправка NACK
}
while (!(TWCR & (1 << TWINT))); // Ожидание завершения приема данных
*data = TWDR; // Чтение данных
}

48
i2c.c Normal file
View File

@ -0,0 +1,48 @@
#include "i2c.h"
#define F_CPU 16000000UL
#define F_SCL 100000UL
#define I2C_READ 1
#define I2C_WRITE 0
#define SCL_CLOCK ((F_CPU/F_SCL)-16)/2
void i2c_init(void)
{
TWBR = (uint8_t)SCL_CLOCK;
}
void i2c_start(void)
{
// transmit START condition
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
// wait for end of transmission
while (!(TWCR & (1<<TWINT)));
}
void i2c_stop(void)
{
// transmit STOP condition
TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN);
// wait for end of transmission
while ((TWCR & (1<<TWSTO)));
}
void i2c_write_byte(uint8_t byte)
{
// transmit data
TWDR = byte;
TWCR = (1<<TWINT) | (1<<TWEN);
// wait for end of transmission
while (!(TWCR & (1<<TWINT)));
}
uint8_t i2c_read_byte(uint8_t ack)
{
// receive data
TWCR = (1<<TWINT) | (1<<TWEN) | (ack<<TWEA);
// wait for end of transmission
while (!(TWCR & (1<<TWINT)));
return TWDR;
}

111
i2c.h
View File

@ -1,111 +0,0 @@
//
// Created by FSB-PC on 22.05.2023.
//
#ifndef INC_8_PMW_I2C_H
#define INC_8_PMW_I2C_H
typedef struct {
uint8_t address; // адрес устройства на шине I2C
uint8_t data[32]; // буфер для передачи и приема данных
uint8_t length; // длина передаваемых данных
};
void i2c_begin(i2c_device_t *i2c){
TWBR = ((F_CPU / i2c->speed) - 16) / 2;
TWAR = (i2c->address << 1);
}
void i2c_beginTransmission(i2c_device_t *i2c, uint8_t address){
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
TWDR = (address << 1);
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
i2c->address = address;
}
void i2c_write(i2c_device_t *i2c, uint8_t data){
TWDR = data;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
}
void i2c_read(i2c_device_t *i2c, uint8_t *data, uint8_t ack){
if (ack){
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
} else {
TWCR = (1 << TWINT) | (1 << TWEN);
}
while (!(TWCR & (1 << TWINT)));
*data = TWDR;
}
void i2c_endTransmission(i2c_device_t *i2c){
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
}
void i2c_sendByte(i2c_device_t *i2c, uint8_t address, uint8_t data){
i2c_beginTransmission(i2c, address);
i2c_write(i2c, data);
i2c_endTransmission(i2c);
}
#endif //INC_8_PMW_I2C_H
//void i2c_begin(I2C *i2c) {
// TWBR = ((F_CPU / i2c->speed) - 16) / 2;
// TWAR = (i2c->address << 1);
//}
//
//void i2c_beginTransmission(I2C *i2c, uint8_t address) {
// TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
// while (!(TWCR & (1 << TWINT)));
//
// TWDR = (address << 1);
// TWCR = (1 << TWINT) | (1 << TWEN);
// while (!(TWCR & (1 << TWINT)));
// i2c->address = address;
//}
//
//void i2c_write(I2C *i2c, uint8_t data) {
// TWDR = data;
// TWCR = (1 << TWINT) | (1 << TWEN);
// while (!(TWCR & (1 << TWINT)));
//}
//
//void i2c_read(I2C *i2c, uint8_t *data, uint8_t ack) {
// if (ack) {
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
// } else {
// TWCR = (1 << TWINT) | (1 << TWEN);
// }
// while (!(TWCR & (1 << TWINT)));
// *data = TWDR;
//}
//
//void i2c_endTransmission(I2C *i2c) {
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
//}
//
//void sendByte(uint8_t data) {
// sendByteRaw(data);
// _writes++;
// if (_writes >= 16) {
// endTransm();
// beginData();
// }
//}
//
//void sendByteRaw(uint8_t data) {
// i2c_write(data);
//}
//
//void sendCommand(uint8_t cmd1) {
// beginOneCommand();
// sendByteRaw(cmd1);
// i2c_endTransmission();
//}

98
main.c
View File

@ -1,5 +1,99 @@
#define I2C_FREQ 100000UL #include <util/delay.h>
#include "i2c.h" #include "i2c.h"
#include "pmw.h" #include "pwm.h"
#define I2C_ADDRESS 0x20
void send_data(void)
{
// read state of PWM from master and send to slave
i2c_start();
i2c_write_byte(I2C_ADDRESS | I2C_WRITE);
i2c_write_byte(0x00);
i2c_start();
i2c_write_byte(I2C_ADDRESS | I2C_READ);
uint8_t state = i2c_read_byte(0);
i2c_stop();
// set PWM state
if (state) {
TCCR1B |= (1<<CS11);
} else {
TCCR1B &= ~(1<<CS11);
}
}
void set_frequency(float frequency)
{
// set PWM frequency
pwm_set_frequency(frequency);
}
void increase_frequency(void)
{
// increase PWM frequency by 25%
float frequency = ICR1 * 1.25 / PWM_MAX_FREQ;
frequency = (frequency > 1.0) ? 1.0 : frequency;
set_frequency(frequency);
}
void decrease_frequency(void)
{
// decrease PWM frequency by 20%
float frequency = ICR1 * 0.8 / PWM_MAX_FREQ;
set_frequency(frequency);
}
void set_duty_cycle(float duty_cycle)
{
// set PWM duty cycle
pwm_set_duty_cycle(duty_cycle);
}
void increase_duty_cycle(void)
{
// increase PWM duty cycle by 10%
float duty_cycle = OCR1A * 1.1 / ICR1;
duty_cycle = (duty_cycle > 1.0) ? 1.0 : duty_cycle;
set_duty_cycle(duty_cycle);
}
void decrease_duty_cycle(void)
{
// decrease PWM duty cycle by 10%
float duty_cycle = OCR1A * 0.9 / ICR1;
set_duty_cycle(duty_cycle);
}
int main(void)
{
// initialize I2C and PWM
i2c_init();
pwm_init();
// set default PWM frequency and duty cycle
set_frequency(1000);
set_duty_cycle(0.5);
// main loop
while (1) {
send_data();
// read buttons and execute actions
if (!(PIND & (1<<PD1))) { // increase frequency
increase_frequency();
}
if (!(PIND & (1<<PD2))) { // decrease frequency
decrease_frequency();
}
if (!(PIND & (1<<PD3))) { // increase duty cycle
increase_duty_cycle();
}
if (!(PIND & (1<<PD4))) { // decrease duty cycle
decrease_duty_cycle();
}
if (!(PIND & (1<<PD5))) { // turn on PWM
TCCR1B |= (1<<CS11);
}
if (!(PIND & (1<<PD6))) { // turn off PWM
TCCR1B &= ~(1<<CS11);
}
_delay_ms(50);
}
}

29
pwm.c Normal file
View File

@ -0,0 +1,29 @@
#include "pwm.h"
void pwm_init(void)
{
// initialize timer 1 for PWM
TCCR1A = (1<<WGM11) | (1<<COM1A1);
TCCR1B = (1<<WGM13) | (1<<WGM12) | (1<<CS11);
OCR1A = 0;
// set PWM pin as output
DDRB |= (1<<PB1);
}
void pwm_set_frequency(float frequency)
{
// calculate timer 1 TOP value
uint16_t top = (uint16_t)(PWM_MAX_FREQ / frequency);
top = (top > 0xffff) ? 0xffff : top;
// set timer 1 TOP value
ICR1 = top;
}
void pwm_set_duty_cycle(float duty_cycle)
{
// calculate OCR1A value from duty cycle
uint16_t ocr = (uint16_t)(duty_cycle * ICR1);
ocr = (ocr > ICR1) ? ICR1 : ocr;
// set OCR1A value
OCR1A = ocr;
}

70
pwm.h
View File

@ -1,70 +0,0 @@
//
// Created by FSB-PC on 22.05.2023.
//
#ifndef INC_8_PMW_PMW_H
#define INC_8_PMW_PMW_H
struct PWM {
uint8_t pin; // номер пина
uint16_t frequency; // частота ШИМ сигнала
uint8_t duty_cycle; // коэффициент заполнения
};
void pwm_begin(struct PWM *pwm) {
TCCR0A = (1 << COM0A1) | (1 << WGM00) | (1 << WGM01);
TCCR0B = (1 << CS00) | (1 << CS01);
OCR0A = 0;
pwm->duty_cycle = 0;
}
void pwm_set_duty_cycle(struct PWM *pwm, uint8_t duty_cycle) {
pwm->duty_cycle = duty_cycle;
OCR0A = (duty_cycle * 255) / 100;
}
void pwm_increase_speed(struct PWM *pwm) {
pwm->duty_cycle += 25;
TCCR0B = (1 << CS00) | (1 << CS01);
}
void pwm_decrease_speed(struct PWM *pwm) {
pwm->duty_cycle -= 20;
TCCR0B = (1 << CS00) | (1 << CS01);
}
void pwm_end(struct PWM *pwm) {
TCCR0B = 0;
}
//void pmw_begin(PMW *pmw) {
// TCCR0A = (1 << COM0A1) | (1 << WGM00) | (1 << WGM01);
// TCCR0B = (1 << CS00) | (1 << CS01);
// OCR0A = 0;
// pmw->speed = 0;
// pmw->duty_cycle = 0;
//}
//
//void pmw_set_duty_cycle(PMW *pmw, uint8_t duty_cycle) {
// pmw->duty_cycle = duty_cycle;
// OCR0A = (duty_cycle * 255) / 100;
//}
//
//void pmw_increase_speed(PMW *pmw) {
// pmw->speed += 25;
// TCCR0B = (1 << CS00) | (1 << CS01);
//}
//
//void pmw_decrease_speed(PMW *pmw) {
// pmw->speed -= 20;
// TCCR0B = (1 << CS00) | (1 << CS01);
//}
//
//void pmw_end(PMW *pmw) {
// TCCR0B = 0;
//}
#endif //INC_8_PMW_PMW_H

75
test.c
View File

@ -1,75 +0,0 @@
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#define F_CPU 8000000UL
#define I2C_FREQ 100000UL
#include "i2c.h"
#define PWM_ADDRESS 0x50
#define BUTTONS_ADDRESS 0x40
#define PWM_ENABLE_CMD 0x0001
#define PWM_DISABLE_CMD 0x0002
#define PWM_INCREASE_FREQ_CMD 0x0011
#define PWM_DECREASE_FREQ_CMD 0x0012
#define PWM_INCREASE_DUTY_CYCLE_CMD 0x0021
#define PWM_DECREASE_DUTY_CYCLE_CMD 0x0022
struct PWM pwm;
struct I2C buttons_i2c;
void setup() {
i2c_begin(&buttons_i2c);
i2c_beginTransmission(&buttons_i2c, BUTTONS_ADDRESS);
i2c_write(&buttons_i2c, 0x00);
i2c_endTransmission(&buttons_i2c);
pwm.pin = PB3;
pwm.frequency = 1000;
pwm_begin(&pwm);
}
void loop() {
i2c_beginTransmission(&buttons_i2c, BUTTONS_ADDRESS);
i2c_read(&buttons_i2c, buttons_i2c.data, 1);
i2c_endTransmission(&buttons_i2c);
uint16_t command = ((uint16_t)(buttons_i2c.data[0]) << 8) | buttons_i2c.data[1];
if (command == PWM_ENABLE_CMD) {
pwm_increase_speed(&pwm);
i2c_sendByte(&buttons_i2c, PWM_ADDRESS, 1);
} else if (command == PWM_DISABLE_CMD) {
pwm_decrease_speed(&pwm);
i2c_sendByte(&buttons_i2c, PWM_ADDRESS, 0);
} else if (command == PWM_INCREASE_FREQ_CMD) {
pwm.frequency += round(pwm.frequency * 0.25);
pwm_set_frequency(&pwm, pwm.frequency);
i2c_sendByte(&buttons_i2c, PWM_ADDRESS, 1);
} else if (command == PWM_DECREASE_FREQ_CMD) {
pwm.frequency -= round(pwm.frequency * 0.2);
pwm_set_frequency(&pwm, pwm.frequency);
i2c_sendByte(&buttons_i2c, PWM_ADDRESS, 0);
} else if (command == PWM_INCREASE_DUTY_CYCLE_CMD) {
pwm_increase_duty_cycle(&pwm);
i2c_sendByte(&buttons_i2c, PWM_ADDRESS, 1);
} else if (command == PWM_DECREASE_DUTY_CYCLE_CMD) {
pwm_decrease_duty_cycle(&pwm);
i2c_sendByte(&buttons_i2c, PWM_ADDRESS, 0);
}
_delay_ms(100);
}
int main() {
setup();
while (true) {
loop();
}
return 0;
}

5
test.cpp Normal file
View File

@ -0,0 +1,5 @@
//
// Created by FSB-PC on 21.06.2023.
//
#include "test.h"

678
test.h Normal file
View File

@ -0,0 +1,678 @@
// #include <avr/io.h>
// void pwm_init() {
// TCCR1A |= (1 << COM1A1) | (1 << WGM11); // non-inverting mode, Fast PWM (mode 14)
// TCCR1B |= (1 << WGM12) | (1 << WGM13) | (1 << CS10); // Fast PWM (mode 14), prescaler = 1
// DDRB |= (1 << PB1); // set pin PB1 as output
// }
// void pwm_set_frequency(uint16_t frequency) {
// uint16_t prescaler = 1;
// uint32_t top = F_CPU / (prescaler * frequency) - 1;
// ICR1 = top;
// }
// void pwm_set_duty_cycle(uint8_t dutyCycle) {
// uint16_t value = ICR1 * dutyCycle / 100.0;
// OCR1A = value;
// }
// void pwm_init();
// void pwm_set_frequency(uint16_t frequency);
// void pwm_set_duty_cycle(uint8_t dutyCycle);
// #define F_CPU 16000000UL
// #define I2C_FREQ 100000UL
// #define I2C_PRESCALER 1
// #define I2C_BITRATE ((F_CPU / I2C_FREQ) - 16) / (2 * I2C_PRESCALER)
// void i2c_init() {
// TWBR = I2C_BITRATE;
// }
// void i2c_start() {
// // отправляем START bit
// TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
// // ожидаем пока START bit будет успешно отправлен
// while (!(TWCR & (1 << TWINT)));
// }
// void i2c_stop() {
// // отправляем STOP bit
// TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
// // ожидаем пока STOP bit будет успешно отправлен
// while (TWCR & (1 << TWSTO));
// }
// void i2c_write(uint8_t data) {
// // загружаем данные в регистр TWDR
// TWDR = data;
// // отправляем данные
// TWCR = (1 << TWINT) | (1 << TWEN);
// // ожидаем пока данные будут успешно отправлены
// while (!(TWCR & (1 << TWINT)));
// }
// uint8_t i2c_read_ack() {
// // разрешаем отправку ACK после прочтения байта
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
// // ожидаем пока данные будут успешно прочитаны
// while (!(TWCR & (1 << TWINT)));
// // возвращаем прочитанный байт
// return TWDR;
// }
// uint8_t i2c_read_nack() {
// // запрещаем отправку ACK после прочтения байта
// TWCR = (1 << TWINT) | (1 << TWEN);
// // ожидаем пока данные будут успешно прочитаны
// while (!(TWCR & (1 << TWINT)));
// // возвращаем прочитанный байт
// return TWDR;
// }
// void i2c_init();
// void i2c_start();
// void i2c_stop();
// void i2c_write(uint8_t data);
// uint8_t i2c_read_ack();
// uint8_t i2c_read_nack();
// const uint8_t BUTTON_PIN[] = {0, 1, 2, 3, 4, 5};
// const uint8_t PWM_SLAVE_ADDR = 9;
// uint16_t command = 0x00;
// float frequency = 1000.0;
// float dutyCycle = 50.0;
// void setup() {
// i2c_init();
// pwm_init();
// // Инициализируем пины кнопок
// DDRC &= ~(1 << PINC0) & ~(1 << PINC1) & ~(1 << PINC2) & ~(1 << PINC3) & ~(1 << PINC4) & ~(1 << PINC5); // подключены кнопки на пинах А0, А1, А2, А3, А4, А5
// PORTC |= (1 << PINC0) | (1 << PINC1) | (1 << PINC2) | (1 << PINC3) | (1 << PINC4) | (1 << PINC5); // включение подтягивающего резистора
// Serial.begin(9600); // Инициализируем Serial монитор
// Serial.println("PWM Controller started!");
// sendCommand(0x01, 0.0); // Включить ШИМ при запуске
// }
// void loop() {
// // Обработка нажатий на кнопки
// checkButton(0, "Turn on PWM!", 0x01, 0.0);
// checkButton(1, "Turn off PWM!", 0x02, 0.0);
// checkButton(2, "Increase frequency!", 0x03, 1.25);
// checkButton(3, "Decrease frequency!", 0x04, 0.8);
// checkButton(4, "Increase duty cycle!", 0x05, 1.1);
// checkButton(5, "Decrease duty cycle!", 0x06, 0.9);
// }
// void checkButton(uint8_t pin, const char* message, uint16_t cmd, float value) {
// if (bit_is_clear(PINC, pin)) {
// Serial.println(message);
// delay(500);
// sendCommand(cmd, value);
// if (cmd == 0x03) {
// frequency *= value;
// pwm_set_frequency(frequency);
// } else if (cmd == 0x04) {
// frequency *= value;
// pwm_set_frequency(frequency);
// } else if (cmd == 0x05) {
// dutyCycle *= value;
// pwm_set_duty_cycle(dutyCycle);
// } else if (cmd == 0x06) {
// dutyCycle *= value;
// pwm_set_duty_cycle(dutyCycle);
// } else if (cmd == 0x02) {
// pwm_set_duty_cycle(0);
// } else if (cmd == 0x01) {
// pwm_set_duty_cycle(dutyCycle);
// }
// command = cmd;
// }
// }
// void sendCommand(uint16_t cmd, float value) {
// if (cmd != 0x01 && cmd != 0x02) { // если команда изменения параметров
// switch (cmd) {
// case 0x03: // Увеличить частоту на 25% от текущего.
// value = frequency;
// value *= 0.25;
// break;
// case 0x04: // Уменьшить частоту на 20% от текущего.
// value = frequency;
// value *= 0.2;
// break;
// case 0x05: // Увеличить скважность на 10% от текущего.
// value = dutyCycle;
// value *= 0.1;
// break;
// case 0x06: // Уменьшить скважность на 10% от текущего.
// value = dutyCycle;
// value *= 0.1;
// break;
// }
// }
// uint16_t data = (uint16_t)(value * 16.0);
// data |= cmd << 4;
// i2c_start();
// i2c_write(PWM_SLAVE_ADDR << 1);
// i2c_write(data >> 8);
// i2c_write(data & 0xFF);
// i2c_stop();
// Serial.print("Sent command: ");
// Serial.print(cmd, HEX);
// Serial.print(", value: ");
// Serial.println(value);
// }
//VERSION #2
#include <avr/io.h>
void pwm_init() {
TCCR1A |= (1 << COM1A1) | (1 << WGM11); // non-inverting mode, Fast PWM (mode 14)
TCCR1B |= (1 << WGM12) | (1 << WGM13) | (1 << CS10); // Fast PWM (mode 14), prescaler = 1
DDRB |= (1 << PB1); // set pin PB1 as output
}
void pwm_set_frequency(uint16_t frequency) {
uint16_t prescaler = 1;
uint32_t top = F_CPU / (prescaler * frequency) - 1;
ICR1 = top;
}
void pwm_set_duty_cycle(uint8_t dutyCycle) {
uint16_t value = ICR1 * dutyCycle / 100.0;
OCR1A = value;
}
void pwm_enable() {
pwm_set_duty_cycle(50); // Начальная скважность
}
void pwm_disable() {
pwm_set_duty_cycle(0); // Выключение ШИМ
}
void pwm_init();
void pwm_set_frequency(uint16_t frequency);
void pwm_set_duty_cycle(uint8_t dutyCycle);
void pwm_enable();
void pwm_disable();
#define F_CPU 16000000UL
#define I2C_FREQ 100000UL
#define I2C_PRESCALER 1
#define I2C_BITRATE ((F_CPU / I2C_FREQ) - 16) / (2 * I2C_PRESCALER)
void i2c_init() {
TWBR = I2C_BITRATE;
}
void i2c_start() {
// отправляем START bit
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
// ожидаем пока START bit будет успешно отправлен
while (!(TWCR & (1 << TWINT)));
}
void i2c_stop() {
// отправляем STOP bit
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
// ожидаем пока STOP bit будет успешно отправлен
while (TWCR & (1 << TWSTO));
}
void i2c_write(uint8_t data) {
// загружаем данные в регистр TWDR
TWDR = data;
// отправляем данные
TWCR = (1 << TWINT) | (1 << TWEN);
// ожидаем пока данные будут успешно отправлены
while (!(TWCR & (1 << TWINT)));
}
uint8_t i2c_read_ack() {
// разрешаем отправку ACK после прочтения байта
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
// ожидаем пока данные будут успешно прочитаны
while (!(TWCR & (1 << TWINT)));
// возвращаем прочитанный байт
return TWDR;
}
uint8_t i2c_read_nack() {
// запрещаем отправку ACK после прочтения байта
TWCR = (1 << TWINT) | (1 << TWEN);
// ожидаем пока данные будут успешно прочитаны
while (!(TWCR & (1 << TWINT)));
// возвращаем прочитанный байт
return TWDR;
}
void i2c_init();
void i2c_start();
void i2c_stop();
void i2c_write(uint8_t data);
uint8_t i2c_read_ack();
uint8_t i2c_read_nack();
const uint8_t BUTTON_PIN[] = {0, 1, 2, 3, 4, 5};
const uint8_t PWM_SLAVE_ADDR = 9;
uint16_t command = 0x00;
float frequency = 1000.0;
float dutyCycle = 50.0;
void setup() {
i2c_init();
pwm_init();
pwm_enable(); // Включение ШИМ
// Инициализируем пины кнопок
DDRC &= ~(1 << PINC0) & ~(1 << PINC1) & ~(1 << PINC2) & ~(1 << PINC3) & ~(1 << PINC4) & ~(1 << PINC5); // подключены кнопки на пинах А0, А1, А2, А3, А4, А5
PORTC |= (1 << PINC0) | (1 << PINC1) | (1 << PINC2) | (1 << PINC3) | (1 << PINC4) | (1 << PINC5); // включение подтягивающего резистора
Serial.begin(9600); // Инициализируем Serial монитор
Serial.println("PWM Controller started!");
sendCommand(0x01, 0.0); // Включить ШИМ при запуске
}
void loop() {
// Обработка нажатий на кнопки
checkButton(0, "Turn on PWM!", 0x01, 0.0);
checkButton(1, "Turn off PWM!", 0x02, 0.0);
checkButton(2, "Increase frequency!", 0x03, 1.25);
checkButton(3, "Decrease frequency!", 0x04, 0.8);
checkButton(4, "Increase duty cycle!", 0x05, 1.1);
checkButton(5, "Decrease duty cycle!", 0x06, 0.9);
}
void checkButton(uint8_t pin, const char* message, uint16_t cmd, float value) {
if (bit_is_clear(PINC, pin)) {
Serial.println(message);
delay(500);
sendCommand(cmd, value);
if (cmd == 0x03) {
frequency *= value;
pwm_set_frequency(frequency);
} else if (cmd == 0x04) {
frequency *= value;
pwm_set_frequency(frequency);
} else if (cmd == 0x05) {
dutyCycle *= value;
pwm_set_duty_cycle(dutyCycle);
} else if (cmd == 0x06) {
dutyCycle *= value;
pwm_set_duty_cycle(dutyCycle);
} else if (cmd == 0x02) {
pwm_disable(); // Выключение ШИМ
} else if (cmd == 0x01) {
pwm_enable(); // Включение ШИМ
}
command = cmd;
}
}
void sendCommand(uint16_t cmd, float value) {
if (cmd != 0x01 && cmd != 0x02) { // если команда изменения параметров
switch (cmd) {
case 0x03: // Увеличить частоту на 25% от текущего.
value = frequency;
value *= 0.25;
break;
case 0x04: // Уменьшить частоту на 20% от текущего.
value = frequency;
value *= 0.2;
break;
case 0x05: // Увеличить скважность на 10% от текущего.
value = dutyCycle;
value *= 0.1;
break;
case 0x06: // Уменьшить скважность на 10% от текущего.
value = dutyCycle;
value *= 0.1;
break;
}
}
uint16_t data = (uint16_t)(value * 16.0);
data |= cmd << 4;
i2c_start();
i2c_write(PWM_SLAVE_ADDR << 1);
i2c_write(data >> 8);
i2c_write(data & 0xFF);
i2c_stop();
Serial.print("Sent command: ");
Serial.print(cmd, HEX);
Serial.print(", value: ");
Serial.println(value);
// uint16_t data = (uint16_t)(value * 16.0);
// data |= cmd << 4;
// i2c_start();
// i2c_write(PWM_SLAVE_ADDR << 1);
// i2c_write(data >> 8);
// Serial.print("Sent byte 1: ");
// Serial.println(data >> 8, HEX);
// i2c_write(data & 0xFF);
// Serial.print("Sent byte 2: ");
// Serial.println(data & 0xFF, HEX);
// i2c_stop();
// Serial.print("Sent command: ");
// Serial.print(cmd, HEX);
// Serial.print(", value: ");
// Serial.println(value);
}
//VERSION 3.x
// #include <avr/io.h>
// #include <util/delay.h>
// #include <stdbool.h>
// void i2c_init();
// void i2c_start();
// void i2c_stop();
// void i2c_write(uint8_t data);
// uint8_t i2c_read_ack();
// uint8_t i2c_read_nack();
// #define F_CPU 16000000UL
// #define I2C_FREQ 100000UL
// #define I2C_PRESCALER 1
// #define I2C_BITRATE ((F_CPU / I2C_FREQ) - 16) / (2 * I2C_PRESCALER)
// void i2c_init() {
// TWBR = I2C_BITRATE;
// }
// void i2c_start() {
// // отправляем START bit
// TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
// // ожидаем пока START bit будет успешно отправлен
// while (!(TWCR & (1 << TWINT)));
// }
// void i2c_stop() {
// // отправляем STOP bit
// TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
// // ожидаем пока STOP bit будет успешно отправлен
// while (TWCR & (1 << TWSTO));
// }
// void i2c_write(uint8_t data) {
// // загружаем данные в регистр TWDR
// TWDR = data;
// // отправляем данные
// TWCR = (1 << TWINT) | (1 << TWEN);
// // ожидаем пока данные будут успешно отправлены
// while (!(TWCR & (1 << TWINT)));
// }
// uint8_t i2c_read_ack() {
// // разрешаем отправку ACK после прочтения байта
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
// // ожидаем пока данные будут успешно прочитаны
// while (!(TWCR & (1 << TWINT)));
// // возвращаем прочитанный байт
// return TWDR;
// }
// uint8_t i2c_read_nack() {
// // запрещаем отправку ACK после прочтения байта
// TWCR = (1 << TWINT) | (1 << TWEN);
// // ожидаем пока данные будут успешно прочитаны
// while (!(TWCR & (1 << TWINT)));
// // возвращаем прочитанный байт
// return TWDR;
// }
// #ifndef PWM_H
// #define PWM_H
// void pwm_init();
// void pwm_set_frequency(uint16_t frequency);
// void pwm_set_duty_cycle(uint8_t dutyCycle);
// void pwm_enable();
// void pwm_disable();
// #endif
// void pwm_init() {
// TCCR1A |= (1 << COM1A1) | (1 << WGM11); // non-inverting mode, Fast PWM (mode 14)
// TCCR1B |= (1 << WGM12) | (1 << WGM13) | (1 << CS10); // Fast PWM (mode 14), prescaler = 1
// DDRB |= (1 << PB1); // set pin PB1 as output
// }
// void pwm_set_frequency(uint16_t frequency) {
// uint16_t prescaler = 1;
// uint32_t top = F_CPU / (prescaler * frequency) - 1;
// ICR1 = top;
// }
// void pwm_set_duty_cycle(uint8_t dutyCycle) {
// uint16_t value = ICR1 * dutyCycle / 100.0;
// OCR1A = value;
// }
// void pwm_enable() {
// pwm_set_duty_cycle(50); // Начальная скважность
// }
// void pwm_disable() {
// pwm_set_duty_cycle(0); // Выключение ШИМ
// }
// #define F_CPU 16000000UL
// #define I2C_FREQ 100000UL
// #define I2C_PRESCALER 1
// #define I2C_BITRATE ((F_CPU / I2C_FREQ) - 16) / (2 * I2C_PRESCALER)
// #define BUTTON_PIN_CNT 6
// const uint8_t BUTTON_PIN[] = {0, 1, 2, 3, 4, 5};
// const uint8_t PWM_SLAVE_ADDR = 9;
// uint16_t command = 0x00;
// float frequency = 1000.0;
// float dutyCycle = 50.0;
// bool is_button_pressed(uint8_t pin);
// void process_button_press(uint8_t pin);
// void send_command(uint16_t cmd, float value);
// int main(void) {
// i2c_init();
// pwm_init();
// pwm_enable(); // Включение ШИМ
// for (uint8_t i = 0; i < BUTTON_PIN_CNT; i++) {
// DDRC &= ~(1 << BUTTON_PIN[i]);
// PORTC |= (1 << BUTTON_PIN[i]);
// }
// Serial.begin(9600); // Инициализируем Serial монитор
// Serial.println("PWM Controller started!");
// send_command(0x01, 0.0); // Включить ШИМ при запуске
// while (true) {
// for (uint8_t i = 0; i < BUTTON_PIN_CNT; i++) {
// if (is_button_pressed(BUTTON_PIN[i])) {
// process_button_press(BUTTON_PIN[i]);
// _delay_ms(500);
// }
// }
// }
// }
// bool is_button_pressed(uint8_t pin) {
// return bit_is_clear(PINC, pin);
// }
// void process_button_press(uint8_t pin) {
// switch (pin) {
// case 0:
// send_command(0x01, 0.0);
// Serial.println("Turn on PWM!");
// break;
// case 1:
// send_command(0x02, 0.0);
// Serial.println("Turn off PWM!");
// break;
// case 2:
// if (frequency * 1.25 < 10000) {
// frequency *= 1.25;
// pwm_set_frequency(frequency);
// send_command(0x03, 1.25);
// Serial.println("Increased frequency!");
// } else {
// Serial.println("Maximum frequency reached!");
// }
// break;
// case 3:
// if (frequency * 0.8 > 1) {
// frequency *= 0.8;
// pwm_set_frequency(frequency);
// send_command(0x04, 0.8);
// Serial.println("Decreased frequency!");
// } else {
// Serial.println("Minimum frequency reached!");
// }
// break;
// case 4:
// if (dutyCycle * 1.1 <= 100) {
// dutyCycle *= 1.1;
// pwm_set_duty_cycle(dutyCycle);
// send_command(0x05, 1.1);
// Serial.println("Increased duty cycle!");
// } else {
// Serial.println("Maximum duty cycle reached!");
// }
// break;
// case 5:
// if (dutyCycle * 0.9 >= 0) {
// dutyCycle *= 0.9;
// pwm_set_duty_cycle(dutyCycle);
// send_command(0x06, 0.9);
// Serial.println("Decreased duty cycle!");
// } else {
// Serial.println("Minimum duty cycle reached!");
// }
// break;
// default:
// break;
// }
// }
// void send_command(uint16_t cmd, float value) {
// if (cmd != 0x01 && cmd != 0x02) { // если команда изменения параметров
// switch (cmd) {
// case 0x03: // Увеличить частоту на 25% от текущего.
// value = frequency;
// value *= 0.25;
// break;
// case 0x04: // Уменьшить частоту на 20% от текущего.
// value = frequency;
// value *= 0.2;
// break;
// case 0x05: // Увеличить скважность на 10% от текущего.
// value = dutyCycle;
// value *= 0.1;
// break;
// case 0x06: // Уменьшить скважность на 10% от текущего.
// value = dutyCycle;
// value *= 0.1;
// break;
// }
// }
// uint16_t data = (uint16_t)(value * 16.0);
// data |= cmd << 4;
// i2c_start();
// i2c_write(PWM_SLAVE_ADDR << 1);
// i2c_write(data >> 8);
// i2c_write(data & 0xFF);
// i2c_stop();
// Serial.print("Sent command: ");
// Serial.print(cmd, HEX);
// Serial.print(", value: ");
// Serial.println(value);
// }
///test
// #include <Wire.h>
// #define PWM_ADDR 9 // Адрес устройства на шине I2C
// void setup() {
// Wire.begin();
// Serial.begin(9600);
// Serial.println("PWM Master device started!");
// Serial.println("I2C connection established");
// }
// void loop() {
// // Генерация случайного значения ШИМ-сигнала
// int pwmValue = random(256);
// // Отправка значения по шине I2C на адрес устройства PWM_ADDR
// Wire.beginTransmission(PWM_ADDR);
// Wire.write(pwmValue);
// Wire.endTransmission();
// Serial.print("Sent PWM value: ");
// Serial.println(pwmValue);
// delay(1000); // Пауза между отправкой нового значения
// }