Compare commits
18
Commits
9d65806d8b
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebc47a79ee | ||
|
|
7bd019cad9 | ||
|
|
afa8ca5d02 | ||
|
|
bace9ac2d2 | ||
|
|
2aee2330c6 | ||
|
|
a7310eef77 | ||
|
|
3e466f6e48 | ||
|
|
f498e9b0cc | ||
|
|
d133eb9dd9 | ||
|
|
96295c6d50 | ||
|
|
20b8dc9d5d | ||
|
|
fe558d57e8 | ||
|
|
d1ae25e83a | ||
|
|
a0d085a0d0 | ||
|
|
46a811ea4e | ||
|
|
993ae6b624 | ||
|
|
eea13c46bf | ||
|
|
ae7b4fffba |
+326
-1
@@ -1,4 +1,4 @@
|
||||
### JetBrains template
|
||||
### CLion+iml template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
@@ -77,6 +77,173 @@ fabric.properties
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### JetBrains+all template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/**/usage.statistics.xml
|
||||
.idea/**/dictionaries
|
||||
.idea/**/shelf
|
||||
|
||||
# AWS User-specific
|
||||
.idea/**/aws.xml
|
||||
|
||||
# Generated files
|
||||
.idea/**/contentModel.xml
|
||||
|
||||
# Sensitive or high-churn files
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
.idea/**/dbnavigator.xml
|
||||
|
||||
# Gradle
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# Gradle and Maven with auto-import
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# SonarLint plugin
|
||||
.idea/sonarlint/
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### C++ template
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
|
||||
### C template
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Object files
|
||||
*.o
|
||||
*.ko
|
||||
*.obj
|
||||
*.elf
|
||||
|
||||
# Linker output
|
||||
*.ilk
|
||||
*.map
|
||||
*.exp
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Libraries
|
||||
*.lib
|
||||
*.a
|
||||
*.la
|
||||
*.lo
|
||||
|
||||
# Shared objects (inc. Windows DLLs)
|
||||
*.dll
|
||||
*.so
|
||||
*.so.*
|
||||
*.dylib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
*.i*86
|
||||
*.x86_64
|
||||
*.hex
|
||||
|
||||
# Debug files
|
||||
*.dSYM/
|
||||
*.su
|
||||
*.idb
|
||||
*.pdb
|
||||
|
||||
# Kernel Module Compile Results
|
||||
*.mod*
|
||||
*.cmd
|
||||
.tmp_versions/
|
||||
modules.order
|
||||
Module.symvers
|
||||
Mkfile.old
|
||||
dkms.conf
|
||||
|
||||
### CLion+all template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
@@ -156,3 +323,161 @@ fabric.properties
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### CLion template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/**/usage.statistics.xml
|
||||
.idea/**/dictionaries
|
||||
.idea/**/shelf
|
||||
|
||||
# AWS User-specific
|
||||
.idea/**/aws.xml
|
||||
|
||||
# Generated files
|
||||
.idea/**/contentModel.xml
|
||||
|
||||
# Sensitive or high-churn files
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
.idea/**/dbnavigator.xml
|
||||
|
||||
# Gradle
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# Gradle and Maven with auto-import
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# SonarLint plugin
|
||||
.idea/sonarlint/
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### JetBrains+iml template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/**/usage.statistics.xml
|
||||
.idea/**/dictionaries
|
||||
.idea/**/shelf
|
||||
|
||||
# AWS User-specific
|
||||
.idea/**/aws.xml
|
||||
|
||||
# Generated files
|
||||
.idea/**/contentModel.xml
|
||||
|
||||
# Sensitive or high-churn files
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
.idea/**/dbnavigator.xml
|
||||
|
||||
# Gradle
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# Gradle and Maven with auto-import
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# SonarLint plugin
|
||||
.idea/sonarlint/
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
|
||||
Generated
-8
@@ -1,8 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
Generated
-8
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/pmw.iml" filepath="$PROJECT_DIR$/.idea/pmw.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-2
@@ -1,2 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module classpath="CMake" type="CPP_MODULE" version="4" />
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,13 +0,0 @@
|
||||
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)
|
||||
@@ -10,8 +10,8 @@
|
||||
- #### Выключить ШИМ.
|
||||
- #### Увеличить частоту на 25% от текущего.
|
||||
- #### Уменьшить частоту на 20% от текущего.
|
||||
- #### Увеличить скважность.
|
||||
- #### Уменьшить скважность.
|
||||
- #### Увеличить скважность на 10% от текущего.
|
||||
- #### Уменьшить скважность на 10% от текущего.
|
||||
|
||||
### Пояснения к заданию
|
||||
|
||||
@@ -21,14 +21,14 @@
|
||||
|
||||
### Набор команд
|
||||
|
||||
| Команда | Описание |
|
||||
|:--------|:--------------------------------------|
|
||||
| TODO: | Включить ШИМ. |
|
||||
| TODO: | Выключить ШИМ. |
|
||||
| TODO: | Увеличить частоту на 25% от текущего. |
|
||||
| TODO: | Уменьшить частоту на 20% от текущего. |
|
||||
| TODO: | Увеличить скважность. |
|
||||
| TODO: | Уменьшить скважность. |
|
||||
| Команда | Описание |
|
||||
|:--------|:------------------------------------------|
|
||||
| 0x01: | Включить ШИМ. |
|
||||
| 0x02: | Выключить ШИМ. |
|
||||
| 0x03: | Увеличить частоту на 25% от текущего. |
|
||||
| 0x04: | Уменьшить частоту на 20% от текущего. |
|
||||
| 0x05: | Увеличить скважность на 10% от текущего |
|
||||
| 0x06: | Уменьшить скважность. на 10% от текущего |
|
||||
|
||||
### Описание регистров для I2C
|
||||
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
#define F_CPU 16000000UL
|
||||
#define I2C_FREQ 100000UL
|
||||
#define I2C_PRESCALER 1
|
||||
#define I2C_BITRATE ((F_CPU / I2C_FREQ) - 16) / (2 * I2C_PRESCALER)
|
||||
|
||||
#include <avr/io.h>
|
||||
#include <avr/interrupt.h>
|
||||
#include <util/delay.h>
|
||||
|
||||
float pwm_frequency = 1.0;
|
||||
uint8_t pwm_duty_cycle = 50;
|
||||
|
||||
volatile uint8_t pwm_enabled = 0;
|
||||
volatile uint8_t pwm_changed = 0;
|
||||
|
||||
void i2c_init() {
|
||||
TWBR = I2C_BITRATE;
|
||||
}
|
||||
|
||||
void i2c_start() {
|
||||
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
|
||||
while (!(TWCR & (1 << TWINT)))
|
||||
;
|
||||
}
|
||||
|
||||
void i2c_stop() {
|
||||
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
|
||||
while (TWCR & (1 << TWSTO))
|
||||
;
|
||||
}
|
||||
|
||||
void i2c_write(uint8_t data) {
|
||||
TWDR = data;
|
||||
TWCR = (1 << TWINT) | (1 << TWEN);
|
||||
while (!(TWCR & (1 << TWINT)))
|
||||
;
|
||||
}
|
||||
|
||||
uint8_t i2c_read_ack() {
|
||||
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
|
||||
while (!(TWCR & (1 << TWINT)))
|
||||
;
|
||||
return TWDR;
|
||||
}
|
||||
|
||||
uint8_t i2c_read_nack() {
|
||||
TWCR = (1 << TWINT) | (1 << TWEN);
|
||||
while (!(TWCR & (1 << TWINT)))
|
||||
;
|
||||
return TWDR;
|
||||
}
|
||||
|
||||
const uint8_t PWM_SLAVE_ADDR = 9;
|
||||
|
||||
void pwm_enable() {
|
||||
pwm_enabled = 1;
|
||||
pwm_changed = 1;
|
||||
}
|
||||
|
||||
void pwm_disable() {
|
||||
pwm_enabled = 0;
|
||||
pwm_changed = 1;
|
||||
}
|
||||
|
||||
void setPWMFrequency(float frequency) {
|
||||
if (frequency < 0 || frequency > 50000.0) {
|
||||
return; // Недопустимая частота
|
||||
}
|
||||
pwm_frequency = frequency;
|
||||
pwm_changed = 1;
|
||||
}
|
||||
|
||||
void setPWMDutyCycle(float duty_cycle) {
|
||||
if (duty_cycle < 1 || duty_cycle > 100) {
|
||||
return; // Недопустимый коэффициент заполнения
|
||||
}
|
||||
pwm_duty_cycle = duty_cycle;
|
||||
pwm_changed = 1;
|
||||
}
|
||||
|
||||
void pwm_check_state() {
|
||||
if (pwm_enabled) {
|
||||
// Включаем пин ШИМ - реализация зависит от аппаратной платформы
|
||||
Serial.print("PWM enabled. Frequency: ");
|
||||
Serial.print(pwm_frequency);
|
||||
Serial.print(" Hz, duty cycle: ");
|
||||
Serial.println(pwm_duty_cycle);
|
||||
} else {
|
||||
// Выключаем пин ШИМ - реализация зависит от аппаратной платформы
|
||||
Serial.println("PWM disabled");
|
||||
}
|
||||
}
|
||||
|
||||
void pwm_set_frequency(float frequency) {
|
||||
// Устанавливаем частоту ШИМ - реализация зависит от аппаратной платформы
|
||||
Serial.print("Setting PWM frequency to: ");
|
||||
Serial.println(frequency);
|
||||
}
|
||||
|
||||
void pwm_set_duty_cycle(float duty_cycle) {
|
||||
// Устанавливаем коэффициент заполнения ШИМ - реализация зависит от аппаратной платформы
|
||||
Serial.print("Setting PWM duty cycle to: ");
|
||||
Serial.println(duty_cycle);
|
||||
}
|
||||
|
||||
void enablePWM() {
|
||||
pwm_enable();
|
||||
// Включаем ШИМ
|
||||
sendCommand(0x01, 0.0);
|
||||
}
|
||||
|
||||
void disablePWM() {
|
||||
// Выключаем ШИМ
|
||||
sendCommand(0x02, 0.0);
|
||||
pwm_disable();
|
||||
}
|
||||
|
||||
void increaseFrequency() {
|
||||
setPWMFrequency(pwm_frequency * 1.25);
|
||||
// Выключаем ШИМ, отправляем команду и включаем обратно
|
||||
disablePWM();
|
||||
sendCommand(0x03, pwm_frequency);
|
||||
enablePWM();
|
||||
}
|
||||
|
||||
void decreaseFrequency() {
|
||||
setPWMFrequency(pwm_frequency * 0.8);
|
||||
// Выключаем ШИМ, отправляем команду и включаем обратно
|
||||
disablePWM();
|
||||
sendCommand(0x04, pwm_frequency);
|
||||
enablePWM();
|
||||
}
|
||||
|
||||
void increaseDutyCycle() {
|
||||
if (pwm_duty_cycle < 100) {
|
||||
pwm_duty_cycle+=10;
|
||||
setPWMDutyCycle(pwm_duty_cycle);
|
||||
// Выключаем ШИМ, отправляем команду и включаем обратно
|
||||
disablePWM();
|
||||
sendCommand(0x05, pwm_duty_cycle);
|
||||
enablePWM();
|
||||
} else {
|
||||
Serial.println("Maximum duty cycle reached!");
|
||||
}
|
||||
}
|
||||
|
||||
void decreaseDutyCycle() {
|
||||
|
||||
if (pwm_duty_cycle > 1) {
|
||||
pwm_duty_cycle-=10;
|
||||
setPWMDutyCycle(pwm_duty_cycle);
|
||||
// Выключаем ШИМ, отправляем команду и включаем обратно
|
||||
disablePWM();
|
||||
sendCommand(0x06, pwm_duty_cycle);
|
||||
enablePWM();
|
||||
} else {
|
||||
Serial.println("Minimum duty cycle reached!");
|
||||
}
|
||||
}
|
||||
|
||||
void checkButton(uint8_t pin, const char* message, void (*command)()) {
|
||||
if (bit_is_clear(PINC, pin)) {
|
||||
Serial.println(message);
|
||||
delay(200);
|
||||
command();
|
||||
}
|
||||
|
||||
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 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);
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#include "gpio.h"
|
||||
|
||||
void setupGPIO() {
|
||||
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);
|
||||
}
|
||||
|
||||
void setPinOutput(uint8_t pin) {
|
||||
DDRB |= (1 << pin);
|
||||
}
|
||||
|
||||
void setPinInput(uint8_t pin) {
|
||||
DDRB &= ~(1 << pin);
|
||||
}
|
||||
|
||||
void setPinHigh(uint8_t pin) {
|
||||
PORTB |= (1 << pin);
|
||||
}
|
||||
|
||||
void setPinLow(uint8_t pin) {
|
||||
PORTB &= ~(1 << pin);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#ifndef GPIO_H
|
||||
#define GPIO_H
|
||||
|
||||
#include <avr/io.h>
|
||||
|
||||
void setupGPIO();
|
||||
void setPinOutput(uint8_t pin);
|
||||
void setPinInput(uint8_t pin);
|
||||
void setPinHigh(uint8_t pin);
|
||||
void setPinLow(uint8_t pin);
|
||||
|
||||
#endif
|
||||
@@ -1,48 +1,33 @@
|
||||
#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_init() {
|
||||
TWBR = I2C_BITRATE;
|
||||
}
|
||||
|
||||
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_start() {
|
||||
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
|
||||
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_stop() {
|
||||
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
|
||||
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)));
|
||||
void i2c_write(uint8_t data) {
|
||||
TWDR = data;
|
||||
TWCR = (1 << TWINT) | (1 << TWEN);
|
||||
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)));
|
||||
uint8_t i2c_read_ack() {
|
||||
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
|
||||
while (!(TWCR & (1 << TWINT)));
|
||||
return TWDR;
|
||||
}
|
||||
|
||||
uint8_t i2c_read_nack() {
|
||||
TWCR = (1 << TWINT) | (1 << TWEN);
|
||||
while (!(TWCR & (1 << TWINT)));
|
||||
return TWDR;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef I2C_H
|
||||
#define I2C_H
|
||||
|
||||
#include <avr/io.h>
|
||||
|
||||
#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();
|
||||
void i2c_start();
|
||||
void i2c_stop();
|
||||
void i2c_write(uint8_t data);
|
||||
uint8_t i2c_read_ack();
|
||||
uint8_t i2c_read_nack();
|
||||
|
||||
#endif
|
||||
@@ -1,99 +1,120 @@
|
||||
#include <avr/io.h>
|
||||
#include <avr/interrupt.h>
|
||||
#include <util/delay.h>
|
||||
#include "i2c.h"
|
||||
#include "pwm.h"
|
||||
#include "i2c.h"
|
||||
#include "gpio.h"
|
||||
|
||||
#define I2C_ADDRESS 0x20
|
||||
const uint8_t PWM_SLAVE_ADDR = 9;
|
||||
|
||||
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
|
||||
void setup() {
|
||||
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);
|
||||
setupGPIO();
|
||||
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);
|
||||
}
|
||||
|
||||
void checkButton(uint8_t pin, const char* message, void (*command)()) {
|
||||
if (bit_is_clear(PINC, pin)) {
|
||||
Serial.println(message);
|
||||
delay(200);
|
||||
command();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -1,29 +1,58 @@
|
||||
#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);
|
||||
float pwm_frequency = 1.0;
|
||||
uint8_t pwm_duty_cycle = 50;
|
||||
|
||||
volatile uint8_t pwm_enabled = 0;
|
||||
volatile uint8_t pwm_changed = 0;
|
||||
|
||||
void pwm_enable() {
|
||||
pwm_enabled = 1;
|
||||
pwm_changed = 1;
|
||||
}
|
||||
|
||||
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_disable() {
|
||||
pwm_enabled = 0;
|
||||
pwm_changed = 1;
|
||||
}
|
||||
|
||||
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;
|
||||
void setPWMFrequency(float frequency) {
|
||||
if (frequency < 0 || frequency > 50000.0) {
|
||||
return; // Недопустимая частота
|
||||
}
|
||||
pwm_frequency = frequency;
|
||||
pwm_changed = 1;
|
||||
}
|
||||
|
||||
void setPWMDutyCycle(float duty_cycle) {
|
||||
if (duty_cycle < 1 || duty_cycle > 100) {
|
||||
return; // Недопустимый коэффициент заполнения
|
||||
}
|
||||
pwm_duty_cycle = duty_cycle;
|
||||
pwm_changed = 1;
|
||||
}
|
||||
|
||||
void pwm_check_state() {
|
||||
if (pwm_enabled) {
|
||||
// Включаем пин ШИМ - реализация зависит от аппаратной платформы
|
||||
Serial.print("PWM enabled. Frequency: ");
|
||||
Serial.print(pwm_frequency);
|
||||
Serial.print(" Hz, duty cycle: ");
|
||||
Serial.println(pwm_duty_cycle);
|
||||
} else {
|
||||
// Выключаем пин ШИМ - реализация зависит от аппаратной платформы
|
||||
Serial.println("PWM disabled");
|
||||
}
|
||||
}
|
||||
|
||||
void pwm_set_frequency(float frequency) {
|
||||
// Устанавливаем частоту ШИМ - реализация зависит от аппаратной платформы
|
||||
Serial.print("Setting PWM frequency to: ");
|
||||
Serial.println(frequency);
|
||||
}
|
||||
|
||||
void pwm_set_duty_cycle(float duty_cycle) {
|
||||
// Устанавливаем коэффициент заполнения ШИМ - реализация зависит от аппаратной платформы
|
||||
Serial.print("Setting PWM duty cycle to: ");
|
||||
Serial.println(duty_cycle);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#ifndef PWM_H
|
||||
#define PWM_H
|
||||
|
||||
#include <avr/io.h>
|
||||
#include "i2c.h"
|
||||
|
||||
extern float pwm_frequency;
|
||||
extern uint8_t pwm_duty_cycle;
|
||||
|
||||
extern volatile uint8_t pwm_enabled;
|
||||
extern volatile uint8_t pwm_changed;
|
||||
|
||||
void pwm_enable();
|
||||
void pwm_disable();
|
||||
void setPWMFrequency(float frequency);
|
||||
void setPWMDutyCycle(float duty_cycle);
|
||||
void pwm_check_state();
|
||||
void pwm_set_frequency(float frequency);
|
||||
void pwm_set_duty_cycle(float duty_cycle);
|
||||
|
||||
void enablePWM();
|
||||
void disablePWM();
|
||||
void increaseFrequency();
|
||||
void decreaseFrequency();
|
||||
void increaseDutyCycle();
|
||||
void decreaseDutyCycle();
|
||||
void checkButton(uint8_t pin, const char* message, void (*command)());
|
||||
void sendCommand(uint8_t cmd, float value);
|
||||
void sendCommandOneByte(uint8_t cmd);
|
||||
void sendCommandTwoBytes(uint8_t cmd, float value);
|
||||
void sendCommandThreeBytes(uint8_t cmd, float value);
|
||||
|
||||
#endif
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
// #include <avr/io.h>
|
||||
// #include <avr/interrupt.h>
|
||||
|
||||
// #define SLAVE_ADDRESS 9 // адрес устройства slave
|
||||
// #define COMMAND_1 0x01 //команда включения шим
|
||||
// #define COMMAND_2 0x02 //команда выключения шим
|
||||
// #define COMMAND_3 0x03 //команда изменения частоты шим
|
||||
// #define COMMAND_4 0x04 //команда изменения скважности шим
|
||||
// #define COMMAND_5 0x05 //команда изменения скважности шим
|
||||
|
||||
|
||||
// uint16_t frequency = 1 << 4;
|
||||
// uint8_t dutycycle = 50;
|
||||
// uint8_t buffer[32]; // буфер для полученных данных
|
||||
// uint8_t cnt = 0; // счетчик байтов
|
||||
// bool tran_end = false; //флаг окончания передачи
|
||||
|
||||
// void i2c_init() {
|
||||
// TWAR = SLAVE_ADDRESS << 1; // задаем адрес устройства
|
||||
// TWSR = 0; // частота шины 100 кГц (скорость передачи)
|
||||
// TWCR = (1 << TWEN) | (1 << TWEA) | (1 << TWIE); // включаем slave reciever
|
||||
// }
|
||||
|
||||
// // обработчик прерывания TWI
|
||||
// ISR(TWI_vect) {
|
||||
// switch (TWSR) {
|
||||
// case 0x60: // SLA+W received, ACK returned
|
||||
// //cnt = 0; // сброс счетчика
|
||||
// //tran_end = false;
|
||||
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE); // включаем прерывание и устанавливаем бит ACK
|
||||
// break;
|
||||
// case 0x80: // data byte received, ACK returned
|
||||
// buffer[cnt++] = TWDR; // сохраняем принятые данные
|
||||
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE);
|
||||
// break;
|
||||
// case 0x88: // last data byte received, NACK returned
|
||||
// buffer[cnt++] = TWDR; // сохраняем последний байт данных
|
||||
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE);
|
||||
// break;
|
||||
// case 0xA0: // STOP or repeated START received
|
||||
// tran_end = true;
|
||||
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE);
|
||||
// break;
|
||||
// default:
|
||||
// TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE);
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
|
||||
// void timer1_init() {
|
||||
// PORTB = 0;
|
||||
// DDRB |= (1 << PORTB1); //OC1A
|
||||
// DDRB |= (1 << PORTB2); //OC1B
|
||||
// TCCR1A = 0; // обнуляем регистры управления
|
||||
// TCCR1B = 0;
|
||||
// TCNT1 = 0; // и счетный регистр
|
||||
// }
|
||||
|
||||
// //частота приходит в 16 раз больше
|
||||
// void timer1_on(uint16_t frequency, uint8_t dutycycle) {
|
||||
// // Неинверсный режим работы
|
||||
// TCCR1A |= (0 << COM1A1) | (0 << COM1A0) | (1 << COM1B1) | (0 << COM1B0);
|
||||
|
||||
// //Fast PWM (Быстрый ШИМ)
|
||||
// TCCR1A |= (1 << WGM11) | (1 << WGM10);
|
||||
// TCCR1B |= (1 << WGM13) | (1 << WGM12);
|
||||
|
||||
// //Предделитель - 1024
|
||||
// TCCR1B |= (1 << CS12) | (0 << CS11) | (1 << CS10);
|
||||
|
||||
// //Частота
|
||||
// OCR1A = F_CPU / 1024 * 16 / frequency;
|
||||
|
||||
// //Скважность
|
||||
// OCR1B = (F_CPU / 1024 * 16 / frequency) * dutycycle / 100;
|
||||
// }
|
||||
|
||||
// void timer1_off() {
|
||||
// // TCCR1A &= ~((1 << COM1A1) | (1 << COM1A0));
|
||||
// //Fast PWM (Быстрый ШИМ)
|
||||
// TCCR1A |= (0 << WGM11) | (0 << WGM10);
|
||||
// TCCR1B |= (0 << WGM13) | (0 << WGM12);
|
||||
// TCCR1A |= (0 << COM1A1) | (0 << COM1A0) | (0 << COM1B1) | (0 << COM1B0); //шим отключен, нормальная работа порта
|
||||
// TCCR1B = 0;
|
||||
|
||||
// // OCR1A = 0;
|
||||
// // OCR1B = 0;
|
||||
// }
|
||||
|
||||
// void setup(void) {
|
||||
// i2c_init(); //инициализация i2c
|
||||
// timer1_init();
|
||||
// Serial.begin(9600);
|
||||
// Serial.println("PWM Slave started!");
|
||||
// sei(); // включаем прерывания
|
||||
// }
|
||||
|
||||
|
||||
// void loop() {
|
||||
// if (tran_end) {
|
||||
// tran_end = false;
|
||||
// for(int i = 0;i<100;i++){
|
||||
// }
|
||||
// if (buffer[0] == COMMAND_1) {
|
||||
// Serial.print("cmd: 0x");
|
||||
// Serial.println(buffer[0]);
|
||||
// timer1_on(frequency, dutycycle);
|
||||
// Serial.print(", data bytes: ");
|
||||
// Serial.print(buffer[1], HEX);
|
||||
// Serial.print(" ");
|
||||
// Serial.println(buffer[2], HEX); // Включение ШИМ
|
||||
// } else if (buffer[0] == COMMAND_2) {
|
||||
// Serial.print("cmd: 0x");
|
||||
// Serial.println(buffer[0]);
|
||||
// timer1_off();
|
||||
// Serial.print(", data bytes: ");
|
||||
// Serial.print(buffer[1], HEX);
|
||||
// Serial.print(" ");
|
||||
// Serial.println(buffer[2], HEX); // Выключение ШИМ
|
||||
// } else if (buffer[0] == COMMAND_3) {
|
||||
// Serial.print("cmd: 0x");
|
||||
// Serial.println(buffer[0]);
|
||||
// frequency = (buffer[1] << 8) + buffer[2];
|
||||
// Serial.print("frequency value: ");
|
||||
// Serial.print(frequency);
|
||||
// Serial.print(", data bytes: ");
|
||||
// Serial.print(buffer[1], HEX);
|
||||
// Serial.print(" ");
|
||||
// Serial.println(buffer[2], HEX);
|
||||
// } else if (buffer[0] == COMMAND_4) {
|
||||
// Serial.print("cmd: 0x");
|
||||
// Serial.println(buffer[0]);
|
||||
// frequency = (buffer[1] << 8) + buffer[2];
|
||||
// Serial.print("frequency value: ");
|
||||
// Serial.print(frequency);
|
||||
// Serial.print(", data bytes: ");
|
||||
// Serial.print(buffer[1], HEX);
|
||||
// Serial.print(" ");
|
||||
// Serial.println(buffer[2], HEX);
|
||||
// } else if (buffer[0] == COMMAND_5) {
|
||||
// Serial.print("cmd: 0x");
|
||||
// Serial.println(buffer[0]);
|
||||
// dutycycle = buffer[1];
|
||||
// Serial.print("dytycycle value: ");
|
||||
// Serial.println(dutycycle);
|
||||
// Serial.print(", data bytes: ");
|
||||
// Serial.print(buffer[1], HEX);
|
||||
// Serial.print(" ");
|
||||
// Serial.println(buffer[2], HEX);
|
||||
// } else if (buffer[0] == COMMAND_5) {
|
||||
// Serial.print("cmd: 0x");
|
||||
// Serial.println(buffer[0]);
|
||||
// dutycycle = buffer[1];
|
||||
// Serial.print("dytycycle value: ");
|
||||
// Serial.println(dutycycle);
|
||||
// Serial.print(", data bytes: ");
|
||||
// Serial.print(buffer[1], HEX);
|
||||
// Serial.print(" ");
|
||||
// Serial.println(buffer[2], HEX);
|
||||
// }
|
||||
// cnt = 0;
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
#include <avr/io.h>
|
||||
#include <avr/interrupt.h>
|
||||
|
||||
#define SLAVE_ADDRESS 9 // адрес устройства slave
|
||||
#define COMMAND_1 0x01 //команда включения шим
|
||||
#define COMMAND_2 0x02 //команда выключения шим
|
||||
#define COMMAND_3 0x03 //команда изменения частоты шим
|
||||
#define COMMAND_4 0x04 //команда изменения скважности шим
|
||||
#define COMMAND_5 0x05 //команда изменения скважности шим
|
||||
#define COMMAND_6 0x06 //команда изменения скважности шим
|
||||
|
||||
|
||||
|
||||
uint16_t frequency = 1 << 4;
|
||||
uint8_t dutycycle = 50;
|
||||
uint8_t buffer[32]; // буфер для полученных данных
|
||||
uint8_t cnt = 0; // счетчик байтов
|
||||
bool tran_end = false; //флаг окончания передачи
|
||||
|
||||
void i2c_init() {
|
||||
TWAR = SLAVE_ADDRESS << 1; // задаем адрес устройства
|
||||
TWSR = 0; // частота шины 100 кГц (скорость передачи)
|
||||
TWCR = (1 << TWEN) | (1 << TWEA) | (1 << TWIE); // включаем slave reciever
|
||||
}
|
||||
|
||||
// обработчик прерывания TWI
|
||||
ISR(TWI_vect) {
|
||||
switch (TWSR) {
|
||||
case 0x60: // SLA+W received, ACK returned
|
||||
//cnt = 0; // сброс счетчика
|
||||
//tran_end = false;
|
||||
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE); // включаем прерывание и устанавливаем бит ACK
|
||||
break;
|
||||
case 0x80: // data byte received, ACK returned
|
||||
buffer[cnt++] = TWDR; // сохраняем принятые данные
|
||||
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE);
|
||||
break;
|
||||
case 0x88: // last data byte received, NACK returned
|
||||
buffer[cnt++] = TWDR; // сохраняем последний байт данных
|
||||
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE);
|
||||
break;
|
||||
case 0xA0: // STOP or repeated START received
|
||||
tran_end = true;
|
||||
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE);
|
||||
break;
|
||||
default:
|
||||
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA) | (1 << TWIE);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void timer1_init() {
|
||||
PORTB = 0;
|
||||
DDRB |= (1 << PORTB1); //OC1A
|
||||
DDRB |= (1 << PORTB2); //OC1B
|
||||
TCCR1A = 0; // обнуляем регистры управления
|
||||
TCCR1B = 0;
|
||||
TCNT1 = 0; // и счетный регистр
|
||||
}
|
||||
|
||||
//частота приходит в 16 раз больше
|
||||
void timer1_on(uint16_t frequency, uint8_t dutycycle) {
|
||||
// Неинверсный режим работы
|
||||
TCCR1A |= (0 << COM1A1) | (0 << COM1A0) | (1 << COM1B1) | (0 << COM1B0);
|
||||
|
||||
//Fast PWM (Быстрый ШИМ)
|
||||
TCCR1A |= (1 << WGM11) | (1 << WGM10);
|
||||
TCCR1B |= (1 << WGM13) | (1 << WGM12);
|
||||
|
||||
//Предделитель - 1024
|
||||
TCCR1B |= (1 << CS12) | (0 << CS11) | (1 << CS10);
|
||||
|
||||
//Частота
|
||||
OCR1A = F_CPU / 1024 * 16 / frequency;
|
||||
|
||||
//Скважность
|
||||
OCR1B = (F_CPU / 1024 * 16 / frequency) * dutycycle / 100;
|
||||
}
|
||||
|
||||
void timer1_off() {
|
||||
// TCCR1A &= ~((1 << COM1A1) | (1 << COM1A0));
|
||||
//Fast PWM (Быстрый ШИМ)
|
||||
TCCR1A |= (0 << WGM11) | (0 << WGM10);
|
||||
TCCR1B |= (0 << WGM13) | (0 << WGM12);
|
||||
TCCR1A |= (0 << COM1A1) | (0 << COM1A0) | (0 << COM1B1) | (0 << COM1B0); //шим отключен, нормальная работа порта
|
||||
TCCR1B = 0;
|
||||
|
||||
// OCR1A = 0;
|
||||
// OCR1B = 0;
|
||||
}
|
||||
|
||||
void setup(void) {
|
||||
i2c_init(); //инициализация i2c
|
||||
timer1_init();
|
||||
Serial.begin(9600);
|
||||
Serial.println("PWM Slave started!");
|
||||
sei(); // включаем прерывания
|
||||
}
|
||||
|
||||
|
||||
void loop() {
|
||||
if (tran_end) {
|
||||
tran_end = false;
|
||||
Serial.println(" ");
|
||||
|
||||
for (int i = 0; i < cnt; i++) {
|
||||
Serial.print(buffer[i], HEX); // вывод байтов в шестнадцатеричном формате
|
||||
Serial.print(" ");
|
||||
}
|
||||
if (buffer[0] == COMMAND_1) {
|
||||
timer1_on(frequency, dutycycle);
|
||||
} else if (buffer[0] == COMMAND_2) {
|
||||
timer1_off();
|
||||
} else if (buffer[0] == COMMAND_3) {
|
||||
frequency = (buffer[1] << 8) + buffer[2];
|
||||
} else if (buffer[0] == COMMAND_4) {
|
||||
frequency = (buffer[1] << 8) + buffer[2];
|
||||
} else if (buffer[0] == COMMAND_5) {
|
||||
dutycycle = buffer[1];
|
||||
} else if (buffer[0] == COMMAND_6) {
|
||||
dutycycle = buffer[1];
|
||||
}
|
||||
cnt = 0;
|
||||
}
|
||||
}
|
||||
@@ -1,678 +0,0 @@
|
||||
// #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); // Пауза между отправкой нового значения
|
||||
// }
|
||||
Reference in New Issue
Block a user