init commit

This commit is contained in:
vpodberezsky
2025-12-13 12:45:11 +03:00
parent 6272e6fa7d
commit 6ca6f3cac9
38 changed files with 724853 additions and 0 deletions

5
blood-meter-stm32-arduino/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

View File

@@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

Binary file not shown.

View File

@@ -0,0 +1,37 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the convention is to give header files names that end with `.h'.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

View File

@@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into the executable file.
The source code of each library should be placed in a separate directory
("lib/your_library_name/[Code]").
For example, see the structure of the following example libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional. for custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
Example contents of `src/main.c` using Foo and Bar:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
The PlatformIO Library Dependency Finder will find automatically dependent
libraries by scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

View File

@@ -0,0 +1,31 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:bluepill_f103c8]
platform = ststm32
board = bluepill_f103c8
framework = arduino
upload_protocol = stlink
debug_tool = stlink
monitor_speed = 115200
upload_flags = -c set CPUTAPID 0x1ba01477
debug_server =
c:\Users\vpodberezsky\.platformio\packages\tool-openocd\bin\openocd
-s c:\Users\vpodberezsky\.platformio\packages\tool-openocd\scripts
-f interface/stlink.cfg
-c "transport select hla_swd"
-c "set CPUTAPID 0x1ba01477"
-f target/stm32f1x.cfg
-c "reset_config none"
lib_deps =
thomasfredericks/Bounce2@^2.72
adafruit/Adafruit ST7735 and ST7789 Library@^1.11.0
adafruit/Adafruit GFX Library @ ^1.11.9
stm32duino/STM32duino RTC@^1.7.0

View File

@@ -0,0 +1,559 @@
#include <Arduino.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SPI.h>
#include <Bounce2.h>
#include <STM32RTC.h>
// Настройки SPI для ST7735
#define TFT_CS PB0 // Chip Select
#define TFT_RST PB9 // Reset
#define TFT_DC PB8 // Data/Command
#define TFT_SCLK PB3 // SPI Clock (SCK)
#define TFT_MOSI PB5 // SPI Data (MOSI)
// Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
#define BTN_1_PIN PA3
#define BTN_2_PIN PA4
#define BTN_3_PIN PA5
#define BUZZER_PIN PA2
Bounce2::Button btn1 = Bounce2::Button();
Bounce2::Button btn2 = Bounce2::Button();
Bounce2::Button btn3 = Bounce2::Button();
void buzzerOn(unsigned int freq, unsigned long duration);
void buzzerOff();
uint32_t mes();
#define DAC_1_CS PA6 // SIN1 // яркосить
#define DAC_2_CS PA7 // SIN2
#define RINT PB1 // RINT
uint32_t ANOUT = 0;
uint32_t ANCTRL = 0;
int x = 12 * 8;
int y = 16 * 1;
uint32_t SIGNAL_COUNTER = 0;
uint32_t SIGNAL_COUNTER_PREV = 0;
// uint32_t SIGNAL_COUNTER_TOTAL = 0;
#define SIGNAL_MAX 1500
// Получаем экземпляр RTC
STM32RTC &rtc = STM32RTC::getInstance();
bool ISRUN = false;
byte sec = 0;
byte sec_prev = 0;
uint32_t ANOUT_PREV = 0;
uint32_t ANCTRL_PREV = 0;
#define counter_max 500
uint16_t counter = counter_max;
byte STATE = 0;
#define CALIBRATE_MENU 1
int SPEED = 1;
int SPEEDCOUNTER;
// Функция для отправки данных в DAC
void writeDAC(int CS_PIN, uint16_t value)
{
value = map(value, 0, 3300, 0, 1023);
if (value > 1023)
value = 1023; // Ограничение до 10 бит
// Формируем 16-битное слово для отправки
uint16_t data = 0x0000; // Команда и данные
data |= (0x00 << 12); // Команда: запись и обновление выхода
data |= (value << 2); // 10-битное значение, сдвинутое на 2 бита влево
// Активируем чип
digitalWrite(CS_PIN, LOW);
// Отправляем данные через SPI
SPI.transfer16(data);
// Деактивируем чип
digitalWrite(CS_PIN, HIGH);
}
// #define FONT_COLOR ST7735_WHITE
// #define BACK_COLOR ST7735_BLACK
inline void setBrightness(int mV)
{
writeDAC(DAC_1_CS, mV); // яркосить
}
inline void secCompensation(int mV)
{
writeDAC(DAC_2_CS, mV);
}
void pause()
{
if (ISRUN)
{
tft.setTextColor(ST7735_BLACK);
tft.setTextSize(2);
tft.setCursor(1, 1);
tft.println("ANOUT : ");
// tft.setCursor(1, y);
// tft.println("ANCTRL: ");
}
ISRUN = !ISRUN;
if (ISRUN)
{
tft.setTextColor(ST7735_GREEN);
tft.setCursor(1, y * 4);
tft.println("START");
tft.setTextColor(ST7735_BLACK);
tft.setCursor(1, y * 4);
tft.println("PAUSE");
}
else
{
tft.setTextColor(ST7735_GREEN);
tft.setCursor(1, y * 4);
tft.println("PAUSE");
tft.setTextColor(ST7735_BLACK);
tft.setCursor(1, y * 4);
tft.println("START");
}
}
inline void clearScreen(int color)
{
tft.setCursor(0, 0);
tft.fillScreen(color);
}
void setup()
{
// Инициализация встроенного светодиода
// pinMode(PC13, OUTPUT);
delay(500);
// DAC
pinMode(DAC_1_CS, OUTPUT);
digitalWrite(DAC_1_CS, HIGH);
pinMode(DAC_2_CS, OUTPUT);
digitalWrite(DAC_2_CS, HIGH);
//
pinMode(PA0, INPUT);
pinMode(PA1, INPUT);
// RINT
pinMode(RINT, OUTPUT);
digitalWrite(RINT, LOW);
// buzzer
pinMode(BUZZER_PIN, OUTPUT);
// кнопки
btn1.attach(BTN_1_PIN, INPUT);
btn2.attach(BTN_2_PIN, INPUT);
btn3.attach(BTN_3_PIN, INPUT);
btn1.interval(5);
btn2.interval(5);
btn3.interval(5);
btn1.setPressedState(LOW);
btn2.setPressedState(LOW);
btn3.setPressedState(LOW);
pinMode(TFT_CS, OUTPUT);
pinMode(TFT_RST, OUTPUT);
pinMode(TFT_DC, OUTPUT);
// 1. Ручной сброс дисплея
pinMode(TFT_RST, OUTPUT);
digitalWrite(TFT_RST, HIGH);
delay(50);
digitalWrite(TFT_RST, LOW);
delay(150);
// void setMISO(uint32_t miso)
// void setMOSI(uint32_t mosi)
// void setSCLK(uint32_t sclk)
// void setSSEL(uint32_t ssel)
pinMode(TFT_MOSI, OUTPUT);
pinMode(TFT_SCLK, OUTPUT);
SPI.setMISO(PB4);
SPI.setMOSI(TFT_MOSI);
SPI.setSCLK(TFT_SCLK);
// SPI.setSSEL(PA15);
// SPI.setDataMode(SPI_MODE0);
// SPI.setBitOrder(MSBFIRST);
// SPI.setClockDivider(8);
// SPI.begin();
// SPIClass mySPI(PB5, PB4, PB3, PB15); //mosi, miso, sclk, ssel
// ⚡ Уменьшаем скорость SPI до 1 МГц (по умолчанию обычно 18 МГц)
SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0)); // работает
// SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
// Инициализация дисплея
tft.initR(INITR_MINI160x80_PLUGIN); // Для ST7735S
tft.setRotation(3);
// Инициализация RTC
rtc.begin(); // По умолчанию использует LSE (внешний кварц 32.768 кГц)
// Если кварца нет, можно использовать LSI (внутренний генератор, менее точный)
rtc.setClockSource(STM32RTC::LSE_CLOCK);
// Установка времени (РАСКОММЕНТИРУЙТЕ ПРИ ПЕРВОМ ЗАПУСКЕ!)
rtc.setTime(12, 0, 0); // Часы, минуты, секунды
rtc.setDate(7, 6, 2024); // День, месяц, год (год 4-значный)
// analogReference(AR_DEFAULT);
analogReadResolution(12); // 12 бит (0-4095)
Serial.begin(115200);
// writeDAC(DAC_1_CS, 1500); // яркосить
setBrightness(1500);
writeDAC(DAC_2_CS, 2000);
buzzerOn(4000, 100);
delay(300);
buzzerOn(4000, 100);
delay(500);
/************************************************************************************/
tft.fillScreen(ST7735_BLACK);
tft.setTextColor(ST7735_WHITE);
tft.setTextSize(2);
tft.setCursor(30, 30);
tft.println("KPOBEMEP");
tft.setCursor(3, 3);
tft.setTextSize(1);
tft.println("XAH38");
delay(3000);
/************************************************************************************/
ISRUN = true;
clearScreen(ST7735_GREEN);
pause();
}
void calibrite()
{
setBrightness(0);
secCompensation(0);
buzzerOn(4000, 500);
delay(1000);
setBrightness(2000); // 1500
delay(100);
int cnt[10];
for (byte i = 0; i < 10; i++)
{
// mes();
ANCTRL = map(analogRead(PA1), 0, 4095, 0, 3300);
cnt[i] = ANCTRL;
delay(10);
}
ANCTRL = 0;
for (byte i = 0; i < 10; i++)
{
ANCTRL += cnt[i];
}
ANCTRL = ANCTRL / 10;
secCompensation(ANCTRL);
}
void calibrite_menu()
{
ISRUN = false;
clearScreen(ST7735_BLACK);
tft.setTextColor(ST7735_WHITE);
tft.setTextSize(2);
tft.setCursor(25, 20);
tft.println("CALIBRITE");
// установка нуля
tft.setCursor(1, 40);
tft.setTextSize(1);
tft.println("press to set zero");
delay(500);
btn3.update();
while (!btn3.pressed())
{
btn3.update();
}
calibrite();
tft.setCursor(5, 50);
tft.setTextColor(ST7735_WHITE);
tft.println((String)ANCTRL);
delay(3000);
// установка скорости
clearScreen(ST7735_BLACK);
tft.setTextColor(ST7735_WHITE);
tft.setTextSize(2);
tft.setCursor(25, 20);
tft.println("CALIBRITE");
tft.setCursor(1, 40);
tft.setTextSize(1);
tft.println("press to set speed");
tft.setCursor(5, 50);
tft.setTextColor(ST7735_WHITE);
tft.println((String)SPEED);
delay(500);
btn3.update();
// while (!btn3.pressed())
int speed_prev = SPEED;
for (;;)
{
btn3.update();
if (btn3.pressed())
{
buzzerOn(6000, 250);
switch (SPEED)
{
case 1:
SPEED = 5;
break;
case 5:
SPEED = 10;
break;
case 10:
SPEED = 20;
break;
case 20:
SPEED = 30;
break;
default:
SPEED = 1;
break;
}
}
if (SPEED != speed_prev)
{
tft.setCursor(5, 50);
tft.setTextColor(ST7735_BLACK);
tft.println((String)speed_prev);
speed_prev = SPEED;
tft.setCursor(5, 50);
tft.setTextColor(ST7735_WHITE);
tft.println((String)SPEED);
}
btn1.update();
if (btn1.pressed())
{
SPEEDCOUNTER = SPEED;
break;
}
}
// завершение
buzzerOn(6000, 250);
delay(500);
buzzerOn(6000, 250);
delay(2000);
clearScreen(ST7735_GREEN);
ISRUN = true;
pause();
}
void rfr()
{
tft.setTextColor(ST7735_GREEN);
tft.setCursor(1, y * 2);
tft.println((String)SIGNAL_COUNTER_PREV);
tft.setTextColor(ST7735_BLACK);
tft.setCursor(1, y * 2);
tft.println((String)SIGNAL_COUNTER);
// tft.println((String)SIGNAL_COUNTER_TOTAL);
SIGNAL_COUNTER_PREV = SIGNAL_COUNTER;
// SIGNAL_COUNTER_PREV = SIGNAL_COUNTER_TOTAL;
sec_prev = sec;
}
void loop()
{
if (STATE == CALIBRATE_MENU)
{
calibrite_menu();
STATE = 0;
}
if (ISRUN)
{
mes();
if (ANOUT >= SIGNAL_MAX)
{
// сигнал сброса
digitalWrite(RINT, HIGH);
delay(10);
digitalWrite(RINT, LOW);
SIGNAL_COUNTER++;
// SIGNAL_COUNTER_TOTAL++;
}
}
// start-stop
btn1.update();
if (btn1.pressed())
{
buzzerOn(6000, 250);
pause();
}
// сброс
btn2.update();
if (btn2.pressed())
{
SIGNAL_COUNTER = 0;
// SIGNAL_COUNTER_TOTAL = 0;
buzzerOn(6000, 250);
delay(500);
buzzerOn(6000, 250);
rfr();
}
// калибровка
btn3.update();
if (btn3.pressed())
{
// calibrite();
STATE = CALIBRATE_MENU;
}
if (ISRUN)
{
// обновим показания
sec = rtc.getSeconds();
if (sec != sec_prev)
{
// тик в 1 секунду
if (SPEEDCOUNTER == 0)
{
SPEEDCOUNTER = SPEED;
// SIGNAL_COUNTER = 0;
// встаём на паузу
pause();
}
else
{
SPEEDCOUNTER--;
}
rfr();
}
}
}
uint32_t mes()
{
// int voltage_mV = map(adcValue, 0, 4095, 0, 3300); // 0..4095 -> 0..3300 мВ
ANOUT = map(analogRead(PA0), 0, 4095, 0, 3300);
// ANCTRL = map(analogRead(PA1), 0, 4095, 0, 3300);
if (0 == counter--)
{
counter = counter_max;
tft.setTextColor(ST7735_GREEN);
tft.setCursor(x, 1);
tft.println((String)ANOUT_PREV);
// tft.setCursor(x, y);
// tft.println((String)ANCTRL_PREV);
tft.setTextColor(ST7735_BLACK);
tft.setCursor(x, 1);
tft.println((String)ANOUT);
// tft.setCursor(x, y);
// tft.println((String)ANCTRL);
ANOUT_PREV = ANOUT;
ANCTRL_PREV = ANCTRL;
tft.setCursor(0, y * 1);
byte level = map(ANOUT, 0, SIGNAL_MAX, 0, 11);
// level = 11;
if (level > 11)
level = 11;
tft.setTextColor(ST7735_BLACK);
tft.print("[");
for (byte i = 0; i < level; i++)
{
tft.print("=");
}
tft.setTextColor(ST7735_GREEN);
for (byte i = level; i < 11; i++)
{
tft.print("=");
}
tft.setTextColor(ST7735_BLACK);
tft.print("]");
}
// sec = rtc.getSeconds();
// if (sec != sec_prev)
// {
// tft.setTextColor(ST7735_GREEN);
// tft.setCursor(1, y * 2);
// tft.println((String)SIGNAL_COUNTER_PREV);
// tft.setTextColor(ST7735_BLACK);
// tft.setCursor(1, y * 2);
// tft.println((String)SIGNAL_COUNTER);
// SIGNAL_COUNTER_PREV = SIGNAL_COUNTER;
// sec_prev = sec;
// }
return ANCTRL;
}
void buzzerOn(unsigned int freq, unsigned long duration)
{
tone(BUZZER_PIN, freq, duration);
}
void buzzerOff()
{
noTone(BUZZER_PIN);
}

View File

@@ -0,0 +1,11 @@
This directory is intended for PlatformIO Test Runner and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html

5
lc-meter-stm32-arduino/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

View File

@@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

View File

@@ -0,0 +1,5 @@
{
"files.associations": {
"*.cpp3": "cpp"
}
}

Binary file not shown.

View File

@@ -0,0 +1,37 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the convention is to give header files names that end with `.h'.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

View File

@@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into the executable file.
The source code of each library should be placed in a separate directory
("lib/your_library_name/[Code]").
For example, see the structure of the following example libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional. for custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
Example contents of `src/main.c` using Foo and Bar:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
The PlatformIO Library Dependency Finder will find automatically dependent
libraries by scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

View File

@@ -0,0 +1,62 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
;[env:bluepill_f103c8]
;platform = ststm32
;board = bluepill_f103c8
;framework = arduino
;upload_protocol = stlink
;debug_tool = stlink
;monitor_speed = 115200
[env:bluepill_f103c8]
platform = ststm32
board = bluepill_f103c8
framework = arduino
# Ключевая настройка: используем протокол HID
upload_protocol = hid
# Важные флаги для работы USB CDC (виртуального COM-порта)
build_flags =
-D PIO_FRAMEWORK_ARDUINO_ENABLE_CDC
-D PIO_FRAMEWORK_ARDUINO_ENABLE_HID ; Может потребоваться
-D USBCON
-D USBD_VID=0x0483
-D USBD_PID=0x5740
-D USB_MANUFACTURER="Unknown"
-D USB_PRODUCT="BLUEPILL_XAH"
;upload_port = \\.\HID\VID_1209&PID_BEBA
; Включение USB Serial (CDC)
;build_flags =
; -D PIO_FRAMEWORK_ARDUINO_ENABLE_CDC
; -D USBCON
; -D USBD_VID=0x0483
; -D USBD_PID=0x5740
; -D USB_MANUFACTURER="Unknown"
; -D USB_PRODUCT="BLUEPILL_XAH"
; -D HAL_PCD_MODULE_ENABLED
; Важно для работы Serial Monitor в PlatformIO
monitor_dtr = 1
;board_build.core = maple
; Change microcontroller
board_build.mcu = stm32f103c8t6
; Change MCU frequency
board_build.f_cpu = 72000000L
; may be needed for the first code download
;board_upload.require_upload_port = no
;board_upload.use_1200bps_touch = no
;upload_protocol = dfu
monitor_speed = 115200
monitor_encoding = utf-8

View File

@@ -0,0 +1,302 @@
#include <Arduino.h>
#include <SPI.h>
#define PIN_ADC A6
#define AD9951_RESET PB1
#define AD9951_IO_UPDATE PB10
const float MAX_FREQUENCY = 400e6; // Максимальная частота (400 МГц)
// Частота системного генератора (без PLL)
#define SYSTEM_CLOCK 100e6 // 100 МГц
void resetAD9951()
{
digitalWrite(AD9951_RESET, HIGH);
delayMicroseconds(10);
digitalWrite(AD9951_RESET, LOW);
}
// Функция для записи в регистр AD9951
void writeAD9951Register(byte address, byte data[], byte numBytes)
{
// digitalWrite(AD9951_CS, LOW);
SPI.transfer(address); // Отправляем адрес регистра
for (byte i = 0; i < numBytes; i++)
{
SPI.transfer(data[i]); // Отправляем данные
}
// digitalWrite(AD9951_CS, HIGH);
// Обновление вывода
digitalWrite(AD9951_IO_UPDATE, HIGH);
delay(1);
digitalWrite(AD9951_IO_UPDATE, LOW);
}
// Функция для настройки частоты
void setFrequency(double frequency)
{
// Рассчитываем значение для регистра частоты (32 бита)
// unsigned long freqWord = (unsigned long)((frequency * pow(2, 32)) / (SYSTEM_CLOCK * 4));
// Clock rate = 100MHz
// unsigned long freqWord = (unsigned long)frequency * 42.94967296;
// Clock rate = 400MHz
unsigned long freqWord = (unsigned long)frequency * 10.73741824;
byte freqData[4];
freqData[0] = (freqWord >> 24) & 0xFF; // MSB
freqData[1] = (freqWord >> 16) & 0xFF;
freqData[2] = (freqWord >> 8) & 0xFF;
freqData[3] = freqWord & 0xFF; // LSB
// Отправка регистра частоты
// SPI.transfer((frequencyWord >> 24) & 0xFF); // MSB
// SPI.transfer((frequencyWord >> 16) & 0xFF);
// SPI.transfer((frequencyWord >> 8) & 0xFF);
// SPI.transfer(frequencyWord & 0xFF); // LSB
writeAD9951Register(0x04, freqData, 4); // Запись в регистр частоты (CFR)
}
// Функция для настройки амплитуды (0-1023 соответствует 0-полная амплитуда)
void setAmplitude(unsigned int amplitude)
{
if (amplitude > 1023)
amplitude = 1023;
byte ampData[2];
ampData[0] = (amplitude >> 8) & 0x03; // Только 2 младших бита
ampData[1] = amplitude & 0xFF;
writeAD9951Register(0x03, ampData, 2); // Запись в регистр амплитуды (ACR)
}
// Функция для настройки PLL (множитель 4)
// Функция для настройки PLL (множитель 4)
void configurePLL()
{
byte cfr1Data[2];
// CFR1: PLL множитель 4 (биты D7-D4 = 0011)
cfr1Data[0] = 0x00; // PLL=4x, VCO gain=high (бит D3=0)
cfr1Data[1] = 0x30; // 0011 в старших битах для PLL=4x
writeAD9951Register(0x01, cfr1Data, 2);
}
/********************************************************************************************* */
// void RESET2()
// {
// digitalWrite(AD9951_RESET, HIGH);
// delayMicroseconds(10);
// digitalWrite(AD9951_RESET, LOW);
// }
uint32_t multiplier = 4;
void CONFIG()
{ // Множитель от 4 до 20
uint32_t cfr1_value = (multiplier - 4) << 4; // Сдвиг битов для D7-D4
// spi_send_byte(0x24);// 0x04 << 3
// CS_LOW();
SPI.transfer(0x01);
// SPI.transfer(cfr1_value);
SPI.transfer(0);
SPI.transfer(0);
SPI.transfer(0x24); // Младший байт
// CS_HIGH();
// Обновить регистры (IO_UPDATE)
digitalWrite(AD9951_IO_UPDATE, HIGH);
delay(1);
digitalWrite(AD9951_IO_UPDATE, LOW);
}
void setFrequency2(unsigned long ftw)
{
// Активировать выбор микросхемы
// CS_LOW();
// Передать адрес регистра FTW (0x04)
SPI.transfer(0x04);
// Передать 32-битное значение FTW
SPI.transfer((ftw >> 24) & 0xFF); // Старший байт
SPI.transfer((ftw >> 16) & 0xFF);
SPI.transfer((ftw >> 8) & 0xFF);
SPI.transfer(ftw & 0xFF); // Младший байт
// Деактивировать выбор микросхемы
// CS_HIGH();
// Обновить регистры (IO_UPDATE)
digitalWrite(AD9951_IO_UPDATE, HIGH);
delay(1);
digitalWrite(AD9951_IO_UPDATE, LOW);
}
/********************************************************************************************* */
// void setPLLMultiplier(byte multiplier)
// {
// byte cfr1Data[3] = {0};
// // Установка множителя PLL (биты D7-D4 регистра CFR1)
// switch (multiplier)
// {
// case 1:
// cfr1Data[2] = 0x00; // 0000
// break;
// case 2:
// cfr1Data[2] = 0x10; // 0001
// break;
// case 4:
// cfr1Data[2] = 0x30; // 0011 (для 4x)
// break;
// case 8:
// cfr1Data[2] = 0x50; // 0101
// break;
// case 16:
// cfr1Data[2] = 0x70; // 0111
// break;
// case 20:
// cfr1Data[2] = 0x90; // 1001
// break;
// default:
// cfr1Data[2] = 0x30; // по умолчанию 4x
// }
// // Дополнительные настройки CFR1:
// cfr1Data[0] |= 0x00; // VCO gain (0 = high, 1 = low)
// cfr1Data[2] |= 0x01; // PLL enabled (бит D0)
// writeAD9951Register(0x01, cfr1Data, 3); // Адрес CFR1 = 0x01
// }
void setPLLMultiplier(byte multiplier)
{
byte cfr1Data[3] = {0};
// Правильная настройка PLL множителя (биты D7-D4)
switch (multiplier)
{
case 1:
cfr1Data[0] = 0x00; // PLL bypass (0x0)
cfr1Data[2] = 0x00; // PLL disabled
break;
case 2:
cfr1Data[0] = 0x00; // VCO gain high
cfr1Data[2] = 0x11; // 0001 (2x) + PLL enabled
break;
case 4:
cfr1Data[0] = 0x00; // VCO gain high
cfr1Data[2] = 0x31; // 0011 (4x) + PLL enabled
break;
case 8:
cfr1Data[0] = 0x00; // VCO gain high
cfr1Data[2] = 0x51; // 0101 (8x) + PLL enabled
break;
case 16:
cfr1Data[0] = 0x00; // VCO gain high
cfr1Data[2] = 0x71; // 0111 (16x) + PLL enabled
break;
case 20:
cfr1Data[0] = 0x00; // VCO gain high
cfr1Data[2] = 0x91; // 1001 (20x) + PLL enabled
break;
default:
cfr1Data[0] = 0x00; // по умолчанию 4x
cfr1Data[2] = 0x31; // 0011 (4x) + PLL enabled
}
writeAD9951Register(0x01, cfr1Data, 3); // Адрес CFR1 = 0x01
}
void setup()
{
delay(500);
Serial.begin(115200); // Инициализация последовательного порта
while (!Serial)
{
// yield;
}
Serial.println("");
Serial.println("hello");
delay(500);
return;
// pinMode(CS_PIN, OUTPUT);
pinMode(AD9951_RESET, OUTPUT);
pinMode(AD9951_IO_UPDATE, OUTPUT);
// digitalWrite(CS_PIN, HIGH);
// Инициализация SPI
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0); // !!!!!!!
SPI.setClockDivider(SPI_CLOCK_DIV32);
delay(500);
/***********************************************************************************/
resetAD9951();
CONFIG();
// setPLLMultiplier(4);
setFrequency(10e6);
// setAmplitude(1023);
return;
// Сброс AD9951
resetAD9951();
delay(100);
// Настройка PLL (множитель 4)
configurePLL();
delay(100);
// Настройка частоты (например, 10 МГц)
setFrequency(10e6);
delay(100);
// Настройка амплитуды (максимальная)
// setAmplitude(1023);
// // Обновление вывода
// digitalWrite(AD9951_IO_UPDATE, HIGH);
// delay(1);
// digitalWrite(AD9951_IO_UPDATE, LOW);
Serial.println("ready");
}
int cnt = 0;
void loop()
{
Serial.println(cnt++);
delay(1000);
}
void loop2()
{
if (Serial.available() > 0)
{
long frequency = Serial.parseInt(); // Чтение частоты из UART
if (frequency > 0 && frequency <= MAX_FREQUENCY)
{
setFrequency(frequency);
Serial.print("Frequency set to: ");
Serial.println(frequency);
}
else
{
Serial.println("Invalid frequency. Please enter a value between 0 and 400000000.");
}
}
}

View File

@@ -0,0 +1,95 @@
#include <Arduino.h>
#include <SPI.h>
// #include "main.h"
// Определение пинов
// const int CS_PIN = 4; // Chip Select !!!!!!
const int IO_UPDATE_PIN = PB10; // IO_UPDATE
const int RESET_PIN = PB1; // RESET
// Настройки
const long REF_CLOCK = 100e6; // Частота опорного генератора (100 MГц)
void resetAD9951();
void setFrequency(long frequency);
void writeRegister(uint8_t registerAddress, uint8_t data);
void configureAD9951();
void setup()
{
Serial.begin(115200); // Инициализация последовательного порта
// pinMode(CS_PIN, OUTPUT);
pinMode(IO_UPDATE_PIN, OUTPUT);
pinMode(RESET_PIN, OUTPUT);
// digitalWrite(CS_PIN, HIGH);
digitalWrite(RESET_PIN, HIGH);
SPI.begin(); // Инициализация SPI
SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0)); // Настройки SPI
// Сброс AD9951
resetAD9951();
// Конфигурация AD9951
configureAD9951();
// Установка начальной частоты
setFrequency(10e6); // Установка частоты 10 МГц
}
void loop()
{
// Основной цикл
}
void resetAD9951()
{
digitalWrite(RESET_PIN, LOW); // Установить RESET в LOW
delay(10); // Задержка для сброса
digitalWrite(RESET_PIN, HIGH); // Установить RESET в HIGH
}
void configureAD9951()
{
// Конфигурация регистра управления (Control Register)
uint8_t controlRegister = 0b00000000; // Пример настройки
// Настройте биты в зависимости от ваших требований
// Например, включение синхронизации, выбор режима работы и т.д.
writeRegister(0x00, controlRegister); // Запись в Control Register
}
void setFrequency(long frequency)
{
// Расчет значения для AD9951
unsigned long frequencyWord = (unsigned long)((double)frequency / REF_CLOCK * (1 << 32));
// Отправка данных в AD9951
// digitalWrite(CS_PIN, LOW);
// Отправка регистра частоты
SPI.transfer((frequencyWord >> 24) & 0xFF); // MSB
SPI.transfer((frequencyWord >> 16) & 0xFF);
SPI.transfer((frequencyWord >> 8) & 0xFF);
SPI.transfer(frequencyWord & 0xFF); // LSB
// digitalWrite(CS_PIN, HIGH);
// Обновление
digitalWrite(IO_UPDATE_PIN, LOW);
digitalWrite(IO_UPDATE_PIN, HIGH);
}
void writeRegister(uint8_t registerAddress, uint8_t data)
{
// digitalWrite(CS_PIN, LOW);
// Запись адреса регистра
SPI.transfer(registerAddress);
// Запись данных
SPI.transfer(data);
// digitalWrite(CS_PIN, HIGH);
}

View File

@@ -0,0 +1,253 @@
#include <Arduino.h>
// #include <EEPROM.h>
#include <SPI.h>
// #include "utils.h"
// #include "GyverPWM.h"
// #define PIN_PWM PB1
#define PIN_ADC A6
const unsigned int oreset = PB1; // PD3 // 43;
const unsigned int ioupdate = PB10; // A3; // PC3 // 11;
// const unsigned int cs = 4; // PD4 // 41;
unsigned long quartz = 0;
float rate = 1;
// void setPwm(int currentPwm);
void RESET2()
{
digitalWrite(oreset, HIGH);
delayMicroseconds(10);
digitalWrite(oreset, LOW);
}
void CS_LOW()
{
// digitalWrite(cs, LOW);
}
void CS_HIGH()
{
// digitalWrite(cs, HIGH);
}
void IO_UPDATE_LOW()
{
digitalWrite(ioupdate, LOW);
}
void IO_UPDATE_HIGH()
{
digitalWrite(ioupdate, HIGH);
}
void setFrequency(unsigned long ftw)
{
// Активировать выбор микросхемы
CS_LOW();
// Передать адрес регистра FTW (0x04)
SPI.transfer(0x04);
// Передать 32-битное значение FTW
SPI.transfer((ftw >> 24) & 0xFF); // Старший байт
SPI.transfer((ftw >> 16) & 0xFF);
SPI.transfer((ftw >> 8) & 0xFF);
SPI.transfer(ftw & 0xFF); // Младший байт
// Деактивировать выбор микросхемы
CS_HIGH();
// Обновить регистры (IO_UPDATE)
IO_UPDATE_HIGH();
delayMicroseconds(1);
IO_UPDATE_LOW();
}
void CONFIG()
{
uint32_t multiplier = 10; // Множитель от 4 до 20
uint32_t cfr1_value = (multiplier - 4) << 4; // Сдвиг битов для D7-D4
CS_LOW();
SPI.transfer(0x01);
SPI.transfer(cfr1_value);
SPI.transfer(0);
SPI.transfer(0); // Младший байт
CS_HIGH();
// Обновить регистры (IO_UPDATE)
IO_UPDATE_HIGH();
delayMicroseconds(1);
IO_UPDATE_LOW();
}
// Функция для расчета FTW (Frequency Tuning Word)
uint32_t calculateFTW(float frequency, float refClock)
{
return (uint32_t)((frequency / refClock) * 4294967296UL); // 2^32
}
void setup()
{
Serial.begin(115200);
Serial.println("");
Serial.println("hello");
pinMode(LED_BUILTIN, OUTPUT);
// pinMode(PIN_PWM, OUTPUT);
pinMode(PIN_ADC, INPUT);
pinMode(oreset, OUTPUT); // RESET
digitalWrite(oreset, LOW);
pinMode(ioupdate, OUTPUT); // IO_UPDATE
digitalWrite(ioupdate, LOW);
// pinMode(cs, OUTPUT); // CS
// digitalWrite(cs, HIGH);
// PWM_frequency(3, 10000, FAST_PWM);
// setPwm(50);
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0); // !!!!!!!
SPI.setClockDivider(SPI_CLOCK_DIV32);
Serial.println("start");
// EEPROM.get(0, quartz);
// Serial.print("quartz :: ");
// Serial.println(quartz);
// rate = 4294967296.0 / quartz;
// Serial.print("rate :: ");
// Serial.println(rate);
delay(500);
RESET2();
delay(100);
CONFIG();
delay(100);
float frequency = 20e6;
float refClock = 100e6; // Опорная частота (100 МГц)
uint32_t ftw = calculateFTW(frequency, refClock);
// setFrequency(ftw);
}
int getAdc()
{
int val = analogRead(PIN_ADC);
return val;
}
// void setPwm(int currentPwm)
// {
// long level = map(currentPwm, 0, 100, 0, 255);
// PWM_set(3, level);
// }
// void pool()
// {
// if (Serial.available())
// {
// String cmd = Serial.readString();
// // $$|sr|10000|150000|500|50
// if (cmd.startsWith(F("$$|sr")))
// {
// // $$|sr|start|stop|step|pwm|
// unsigned long start = (splitString(cmd, '|', 2)).toInt();
// unsigned long stop = (splitString(cmd, '|', 3)).toInt();
// unsigned long step = (splitString(cmd, '|', 4)).toInt();
// unsigned int pwm = (splitString(cmd, '|', 5)).toInt();
// setPwm(pwm);
// // speedrun(start, stop, step); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// }
// if (cmd.startsWith(F("set q="))) // сохраняем частоту кварца
// {
// String _intStr = cmd.substring(cmd.indexOf("=") + 1, cmd.length());
// unsigned long quartz = _intStr.toInt() * 1000 * 1000;
// EEPROM.put(0, quartz);
// delay(10);
// EEPROM.get(0, quartz);
// Serial.print("quartz :: ");
// Serial.println(quartz);
// rate = 4294967296.0 / quartz;
// Serial.print("rate :: ");
// Serial.println(rate);
// }
// if (cmd.startsWith(F("set f="))) // установить частоту
// {
// unsigned long freq = 0;
// String _intStr = cmd.substring(cmd.indexOf("=") + 1, cmd.length());
// if (_intStr == "R")
// {
// // for (byte i = 0; i <= 80; i += 10)
// for (unsigned long i = 100000; i <= 2500000; i += 10000)
// {
// // freq = 10000 + i;
// // setF(freq * 1000);
// setF(i);
// delay(500);
// }
// setF(2500000);
// // setF(5000000);
// return;
// }
// freq = _intStr.toInt();
// setF(freq * 1000);
// }
// if (cmd.startsWith(F("set p="))) // установить ШИМ
// {
// String _intStr = cmd.substring(cmd.indexOf("=") + 1, cmd.length());
// int pwm = _intStr.toInt();
// setPwm(pwm);
// Serial.println("pwm :: " + (String)pwm + "%");
// }
// }
// }
float refClock = 100e6; // Опорная частота (100 МГц)
void loop()
{
// RESET2();
// CONFIG();
// uint32_t ftw = calculateFTW(10 * 1e6, refClock);
// setFrequency(ftw);
// return;
int i = 0;
for (i = 5; i <= 50; i += 5)
{
// delay(2500);
float frequency = i * 1e6;
uint32_t ftw = calculateFTW(frequency, refClock);
RESET2();
CONFIG();
// delay(100);
setFrequency(ftw);
Serial.print("F = ");
Serial.println(i);
delay(5000);
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
// pool();
// delay(500);
// digitalWrite(LED_BUILTIN, LOW);
// delay(500);
// digitalWrite(LED_BUILTIN, HIGH);
}

View File

@@ -0,0 +1,5 @@
#include <Arduino.h>
void resetAD9951();
void setFrequency(long frequency);
void writeRegister(uint8_t registerAddress, uint8_t data);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -0,0 +1,266 @@
[Form1]
Edit1Text=
sRadioButton1=0
sRadioButton2=1
sRadioButton3=1
sRadioButton4=0
sRadioButton5=1
sRadioButton6=0
sComboBox1ItIn=10
sComboBox2ItIn=1
sComboBox3ItIn=6
sComboBox5ItIn=0
sComboBox6ItIn=2
sComboBox7ItIn=2
sChBox1=1
sChBox2=0
sChBox3=0
sChBox4=0
sChBox6=1
sChBox12=1
sChBox13=0
sChBox14=0
sChBox15=1
sChBox16=0
sChBox17=0
sChBox18=0
sChBox19=0
sChBox20=0
sChBox21=0
sChBox22=0
N32=0
N36=0
N37=1
SG7TopRow=1
SG7_ColWidths_1=220
SG7_ColWidths_2=700
M.Name=MS Sans Serif
M.Color=0
M.Size=8
M.Bold=0
M.Italic=0
LOG_filename=
PTF_DLRB=d:\_!_prj\XAH\lc-meter-stm32-arduino\temp\DLRB
PTF_STRINGS=d:\_!_prj\XAH\lc-meter-stm32-arduino\temp\STRINGS
PTF_PROGRAMS=d:\_!_prj\XAH\lc-meter-stm32-arduino\temp\PROGRAMS
PTF_LOG=d:\_!_prj\XAH\lc-meter-stm32-arduino\temp\LOG
PTF_SAVE=d:\_!_prj\XAH\lc-meter-stm32-arduino\temp\SAVE
PTF_AUTOSAVE=d:\_!_prj\XAH\lc-meter-stm32-arduino\temp\AUTOSAVE
PTF_SendFile=
FN_TableMacros=d:\_!_prj\XAH\lc-meter-stm32-arduino\temp\MACROS\Default.mcs
NbCOMA=8
NbCOMB=8
NomCOMA=5
NomCOMB=0
VidOformSave=1
KolSimvOtstupaSave=10
SimvolOtstupaSave=9
VidOformASave=1
KolSimvOtstupaASave=40
SimvolOtstupaASave=32
VidOformLOG=1
KolSimvOtstupaLOG=40
SimvolOtstupaLOG=32
Timer3_TOcomA=100000
Timer3_TOcomB=100000
bigTimer3_TOcomA=1000000
bigTimer3_TOcomB=1000000
ColorSelect=12500735
SG1_width=707
SG2_width=5
SG3_width=5
SG4_width=693
SG5_width=5
SG6_width=5
M1_width=59
M2_width=59
M3_width=59
M4_width=59
M5_width=59
M6_width=59
Form1_Maximized=0
Form1_Left=268
Form1_Top=171
Form1_Width=1418
Form1_Height=739
[Form6]
RadioGroup1=3
RadioGroup2=0
RadioGroup3=0
RadioGroup4=3
RadioGroup5=0
RadioGroup6=0
RadioGroup7=1
RadioGroup8=0
RadioGroup9=0
RadioGroup10=2
RadioGroup11=1
RadioGroup12=0
RadioGroup13=1
RadioGroup14=0
RadioGroup17=0
LANG=1
sRadioGroup2=0
ChBox1=0
ChBox2=1
ChBox3=0
ChBox22=0
sChBox1=0
sChBox2=0
sChBox3=0
sChBox4=0
sChBox5=0
sChBox6=0
sChBox7=0
sChBox8=0
sChBox10=0
sChBox11=0
sChBox12=0
sChBox13=1
sChBox14=1
sChBox15=0
sChBox16=1
sChBox17=0
sChBox22=1
sChBox23=0
RadioButton1=0
RadioButton2=0
RadioButton3=1
sRadioButton4=1
sRadioButton5=0
sRadioButton6=0
RadioButton13=1
RadioButton14=0
RadioButton15=0
Form6Edit1Text=9600
Form6Edit2Text=9600
Form6Edit3Text=200
Form6Edit8Text=0
Form6sEdit1Text=
Form6sEdit2Text=
sComboBox1ItIn=0
SpEd1=0
SpEd2=200
sSpEd1=1
sSpEd2=1
KolStrScrolTables=3
TipScrolTables=1
[Form13]
sRadioGroup1=0
[Form5]
FN_Program=
[Form4]
SelectColor=14474460
sComboBox1ItIn=32
[Form14]
PeriodPovtora=1000
[Form15]
ChBox1=0
ChBox2=0
ChBox3=1
FN_SendFile=
sEdit1Text=0
[ARGUMENTS]
AIM00=0
AIM01=0
AIM02=0
AIM03=0
AIM04=0
AIM05=0
AIM06=0
AIM07=0
AIM10=0
AIM11=0
AIM12=0
AIM13=0
AIM14=0
AIM15=0
AIM16=0
AIM17=0
AIM20=0
AIM21=0
AIM22=0
AIM23=0
AIM24=0
AIM25=0
AIM26=0
AIM27=0
AIM30=0
AIM31=0
AIM32=0
AIM33=0
AIM34=0
AIM35=0
AIM36=0
AIM37=0
AIM40=0
AIM41=0
AIM42=0
AIM43=0
AIM44=0
AIM45=0
AIM46=0
AIM47=0
AIM50=0
AIM51=0
AIM52=0
AIM53=0
AIM54=0
AIM55=0
AIM56=0
AIM57=0
AIM60=0
AIM61=0
AIM62=0
AIM63=0
AIM64=0
AIM65=0
AIM66=0
AIM67=0
AIM70=0
AIM71=0
AIM72=0
AIM73=0
AIM74=0
AIM75=0
AIM76=0
AIM77=0
AIM80=0
AIM81=0
AIM82=0
AIM83=0
AIM84=0
AIM85=0
AIM86=0
AIM87=0
AIM90=0
AIM91=0
AIM92=0
AIM93=0
AIM94=0
AIM95=0
AIM96=0
AIM97=0
ATIP0=0
ATIP1=0
ATIP2=0
ATIP3=0
ATIP4=0
ATIP5=0
ATIP6=0
ATIP7=0
ATIP8=0
ATIP9=0
ANAME0=
ANAME1=
ANAME2=
ANAME3=
ANAME4=
ANAME5=
ANAME6=
ANAME7=
ANAME8=
ANAME9=
[Form17]
sChBox1=0
sUD1=1

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,11 @@
This directory is intended for PlatformIO Test Runner and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html

Binary file not shown.