summaryrefslogtreecommitdiff
path: root/platforms/chibios/drivers
diff options
context:
space:
mode:
Diffstat (limited to 'platforms/chibios/drivers')
-rw-r--r--platforms/chibios/drivers/analog.c15
-rw-r--r--platforms/chibios/drivers/analog.h6
-rw-r--r--platforms/chibios/drivers/audio_dac.h126
-rw-r--r--platforms/chibios/drivers/audio_dac_additive.c337
-rw-r--r--platforms/chibios/drivers/audio_dac_basic.c249
-rw-r--r--platforms/chibios/drivers/audio_pwm.h40
-rw-r--r--platforms/chibios/drivers/audio_pwm_hardware.c148
-rw-r--r--platforms/chibios/drivers/audio_pwm_software.c166
-rw-r--r--platforms/chibios/drivers/eeprom/eeprom_stm32_L0_L1.h2
-rw-r--r--platforms/chibios/drivers/i2c_master.c103
-rw-r--r--platforms/chibios/drivers/i2c_master.h76
-rw-r--r--platforms/chibios/drivers/ps2/ps2_io.c55
-rw-r--r--platforms/chibios/drivers/serial.c85
-rw-r--r--platforms/chibios/drivers/serial_usart.c54
-rw-r--r--platforms/chibios/drivers/serial_usart.h6
-rw-r--r--platforms/chibios/drivers/spi_master.c64
-rw-r--r--platforms/chibios/drivers/spi_master.h6
-rw-r--r--platforms/chibios/drivers/uart.c30
-rw-r--r--platforms/chibios/drivers/uart.h24
-rw-r--r--platforms/chibios/drivers/usbpd_stm32g4.c4
-rw-r--r--platforms/chibios/drivers/ws2812.c41
-rw-r--r--platforms/chibios/drivers/ws2812_pwm.c80
-rw-r--r--platforms/chibios/drivers/ws2812_spi.c95
23 files changed, 1565 insertions, 247 deletions
diff --git a/platforms/chibios/drivers/analog.c b/platforms/chibios/drivers/analog.c
index 8c476fcac2..a7b7ec76d7 100644
--- a/platforms/chibios/drivers/analog.c
+++ b/platforms/chibios/drivers/analog.c
@@ -14,7 +14,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "quantum.h"
#include "analog.h"
#include <ch.h>
#include <hal.h>
@@ -38,7 +37,7 @@
// Otherwise assume V3
#if defined(STM32F0XX) || defined(STM32L0XX)
# define USE_ADCV1
-#elif defined(STM32F1XX) || defined(STM32F2XX) || defined(STM32F4XX)
+#elif defined(STM32F1XX) || defined(STM32F2XX) || defined(STM32F4XX) || defined(GD32VF103)
# define USE_ADCV2
#endif
@@ -75,7 +74,7 @@
/* User configurable ADC options */
#ifndef ADC_COUNT
-# if defined(STM32F0XX) || defined(STM32F1XX) || defined(STM32F4XX)
+# if defined(STM32F0XX) || defined(STM32F1XX) || defined(STM32F4XX) || defined(GD32VF103)
# define ADC_COUNT 1
# elif defined(STM32F3XX)
# define ADC_COUNT 4
@@ -101,9 +100,9 @@
// Options are 12, 10, 8, and 6 bit.
#ifndef ADC_RESOLUTION
-# ifdef ADC_CFGR_RES_10BITS // ADCv3, ADCv4
+# ifdef ADC_CFGR_RES_10BITS // ADCv3, ADCv4
# define ADC_RESOLUTION ADC_CFGR_RES_10BITS
-# else // ADCv1, ADCv5, or the bodge for ADCv2 above
+# else // ADCv1, ADCv5, or the bodge for ADCv2 above
# define ADC_RESOLUTION ADC_CFGR1_RES_10BIT
# endif
#endif
@@ -122,8 +121,8 @@ static ADCConversionGroup adcConversionGroup = {
.cfgr1 = ADC_CFGR1_CONT | ADC_RESOLUTION,
.smpr = ADC_SAMPLING_RATE,
#elif defined(USE_ADCV2)
-# if !defined(STM32F1XX)
- .cr2 = ADC_CR2_SWSTART, // F103 seem very unhappy with, F401 seems very unhappy without...
+# if !defined(STM32F1XX) && !defined(GD32VF103)
+ .cr2 = ADC_CR2_SWSTART, // F103 seem very unhappy with, F401 seems very unhappy without...
# endif
.smpr2 = ADC_SMPR2_SMP_AN0(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN1(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN2(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN3(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN4(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN5(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN6(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN7(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN8(ADC_SAMPLING_RATE) | ADC_SMPR2_SMP_AN9(ADC_SAMPLING_RATE),
.smpr1 = ADC_SMPR1_SMP_AN10(ADC_SAMPLING_RATE) | ADC_SMPR1_SMP_AN11(ADC_SAMPLING_RATE) | ADC_SMPR1_SMP_AN12(ADC_SAMPLING_RATE) | ADC_SMPR1_SMP_AN13(ADC_SAMPLING_RATE) | ADC_SMPR1_SMP_AN14(ADC_SAMPLING_RATE) | ADC_SMPR1_SMP_AN15(ADC_SAMPLING_RATE),
@@ -220,7 +219,7 @@ __attribute__((weak)) adc_mux pinToMux(pin_t pin) {
case F9: return TO_MUX( ADC_CHANNEL_IN7, 2 );
case F10: return TO_MUX( ADC_CHANNEL_IN8, 2 );
# endif
-#elif defined(STM32F1XX)
+#elif defined(STM32F1XX) || defined(GD32VF103)
case A0: return TO_MUX( ADC_CHANNEL_IN0, 0 );
case A1: return TO_MUX( ADC_CHANNEL_IN1, 0 );
case A2: return TO_MUX( ADC_CHANNEL_IN2, 0 );
diff --git a/platforms/chibios/drivers/analog.h b/platforms/chibios/drivers/analog.h
index e61c394265..67a7b466a5 100644
--- a/platforms/chibios/drivers/analog.h
+++ b/platforms/chibios/drivers/analog.h
@@ -17,7 +17,7 @@
#pragma once
#include <stdint.h>
-#include "quantum.h"
+#include "gpio.h"
#ifdef __cplusplus
extern "C" {
@@ -28,7 +28,9 @@ typedef struct {
uint8_t adc;
} adc_mux;
#define TO_MUX(i, a) \
- (adc_mux) { i, a }
+ (adc_mux) { \
+ i, a \
+ }
int16_t analogReadPin(pin_t pin);
int16_t analogReadPinAdc(pin_t pin, uint8_t adc);
diff --git a/platforms/chibios/drivers/audio_dac.h b/platforms/chibios/drivers/audio_dac.h
new file mode 100644
index 0000000000..07cd622ead
--- /dev/null
+++ b/platforms/chibios/drivers/audio_dac.h
@@ -0,0 +1,126 @@
+/* Copyright 2019 Jack Humbert
+ * Copyright 2020 JohSchneider
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#pragma once
+
+#ifndef A4
+# define A4 PAL_LINE(GPIOA, 4)
+#endif
+#ifndef A5
+# define A5 PAL_LINE(GPIOA, 5)
+#endif
+
+/**
+ * Size of the dac_buffer arrays. All must be the same size.
+ */
+#define AUDIO_DAC_BUFFER_SIZE 256U
+
+/**
+ * Highest value allowed sample value.
+
+ * since the DAC is limited to 12 bit, the absolute max is 0xfff = 4095U;
+ * lower values adjust the peak-voltage aka volume down.
+ * adjusting this value has only an effect on a sample-buffer whose values are
+ * are NOT pregenerated - see square-wave
+ */
+#ifndef AUDIO_DAC_SAMPLE_MAX
+# define AUDIO_DAC_SAMPLE_MAX 4095U
+#endif
+
+#if !defined(AUDIO_DAC_SAMPLE_RATE) && !defined(AUDIO_MAX_SIMULTANEOUS_TONES) && !defined(AUDIO_DAC_QUALITY_VERY_LOW) && !defined(AUDIO_DAC_QUALITY_LOW) && !defined(AUDIO_DAC_QUALITY_HIGH) && !defined(AUDIO_DAC_QUALITY_VERY_HIGH)
+# define AUDIO_DAC_QUALITY_SANE_MINIMUM
+#endif
+
+/**
+ * These presets allow you to quickly switch between quality settings for
+ * the DAC. The sample rate and maximum number of simultaneous tones roughly
+ * has an inverse relationship - slightly higher sample rates may be possible.
+ *
+ * NOTE: a high sample-rate results in a higher cpu-load, which might lead to
+ * (audible) discontinuities and/or starve other processes of cpu-time
+ * (like RGB-led back-lighting, ...)
+ */
+#ifdef AUDIO_DAC_QUALITY_VERY_LOW
+# define AUDIO_DAC_SAMPLE_RATE 11025U
+# define AUDIO_MAX_SIMULTANEOUS_TONES 8
+#endif
+
+#ifdef AUDIO_DAC_QUALITY_LOW
+# define AUDIO_DAC_SAMPLE_RATE 22050U
+# define AUDIO_MAX_SIMULTANEOUS_TONES 4
+#endif
+
+#ifdef AUDIO_DAC_QUALITY_HIGH
+# define AUDIO_DAC_SAMPLE_RATE 44100U
+# define AUDIO_MAX_SIMULTANEOUS_TONES 2
+#endif
+
+#ifdef AUDIO_DAC_QUALITY_VERY_HIGH
+# define AUDIO_DAC_SAMPLE_RATE 88200U
+# define AUDIO_MAX_SIMULTANEOUS_TONES 1
+#endif
+
+#ifdef AUDIO_DAC_QUALITY_SANE_MINIMUM
+/* a sane-minimum config: with a trade-off between cpu-load and tone-range
+ *
+ * the (currently) highest defined note is NOTE_B8 with 7902Hz; if we now
+ * aim for an even even multiple of the buffer-size, we end up with:
+ * ( roundUptoPow2(highest note / AUDIO_DAC_BUFFER_SIZE) * nyquist-rate * AUDIO_DAC_BUFFER_SIZE)
+ * 7902/256 = 30.867 * 2 * 256 ~= 16384
+ * which works out (but the 'scope shows some sampling artifacts with lower harmonics :-P)
+ */
+# define AUDIO_DAC_SAMPLE_RATE 16384U
+# define AUDIO_MAX_SIMULTANEOUS_TONES 8
+#endif
+
+/**
+ * Effective bit-rate of the DAC. 44.1khz is the standard for most audio - any
+ * lower will sacrifice perceptible audio quality. Any higher will limit the
+ * number of simultaneous tones. In most situations, a tenth (1/10) of the
+ * sample rate is where notes become unbearable.
+ */
+#ifndef AUDIO_DAC_SAMPLE_RATE
+# define AUDIO_DAC_SAMPLE_RATE 44100U
+#endif
+
+/**
+ * The number of tones that can be played simultaneously. If too high a value
+ * is used here, the keyboard will freeze and glitch-out when that many tones
+ * are being played.
+ */
+#ifndef AUDIO_MAX_SIMULTANEOUS_TONES
+# define AUDIO_MAX_SIMULTANEOUS_TONES 2
+#endif
+
+/**
+ * The default value of the DAC when not playing anything. Certain hardware
+ * setups may require a high (AUDIO_DAC_SAMPLE_MAX) or low (0) value here.
+ * Since multiple added sine waves tend to oscillate around the midpoint,
+ * and possibly never/rarely reach either 0 of MAX, 1/2 MAX can be a
+ * reasonable default value.
+ */
+#ifndef AUDIO_DAC_OFF_VALUE
+# define AUDIO_DAC_OFF_VALUE AUDIO_DAC_SAMPLE_MAX / 2
+#endif
+
+#if AUDIO_DAC_OFF_VALUE > AUDIO_DAC_SAMPLE_MAX
+# error "AUDIO_DAC: OFF_VALUE may not be larger than SAMPLE_MAX"
+#endif
+
+/**
+ *user overridable sample generation/processing
+ */
+uint16_t dac_value_generate(void);
diff --git a/platforms/chibios/drivers/audio_dac_additive.c b/platforms/chibios/drivers/audio_dac_additive.c
new file mode 100644
index 0000000000..db07c4b393
--- /dev/null
+++ b/platforms/chibios/drivers/audio_dac_additive.c
@@ -0,0 +1,337 @@
+/* Copyright 2016-2019 Jack Humbert
+ * Copyright 2020 JohSchneider
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "audio.h"
+#include <ch.h>
+#include <hal.h>
+
+/*
+ Audio Driver: DAC
+
+ which utilizes the dac unit many STM32 are equipped with, to output a modulated waveform from samples stored in the dac_buffer_* array who are passed to the hardware through DMA
+
+ it is also possible to have a custom sample-LUT by implementing/overriding 'dac_value_generate'
+
+ this driver allows for multiple simultaneous tones to be played through one single channel by doing additive wave-synthesis
+*/
+
+#if !defined(AUDIO_PIN)
+# error "Audio feature enabled, but no suitable pin selected as AUDIO_PIN - see docs/feature_audio under 'ARM (DAC additive)' for available options."
+#endif
+#if defined(AUDIO_PIN_ALT) && !defined(AUDIO_PIN_ALT_AS_NEGATIVE)
+# pragma message "Audio feature: AUDIO_PIN_ALT set, but not AUDIO_PIN_ALT_AS_NEGATIVE - pin will be left unused; audio might still work though."
+#endif
+
+#if !defined(AUDIO_PIN_ALT)
+// no ALT pin defined is valid, but the c-ifs below need some value set
+# define AUDIO_PIN_ALT PAL_NOLINE
+#endif
+
+#if !defined(AUDIO_DAC_SAMPLE_WAVEFORM_SINE) && !defined(AUDIO_DAC_SAMPLE_WAVEFORM_TRIANGLE) && !defined(AUDIO_DAC_SAMPLE_WAVEFORM_SQUARE) && !defined(AUDIO_DAC_SAMPLE_WAVEFORM_TRAPEZOID)
+# define AUDIO_DAC_SAMPLE_WAVEFORM_SINE
+#endif
+
+#ifdef AUDIO_DAC_SAMPLE_WAVEFORM_SINE
+/* one full sine wave over [0,2*pi], but shifted up one amplitude and left pi/4; for the samples to start at 0
+ */
+static const dacsample_t dac_buffer_sine[AUDIO_DAC_BUFFER_SIZE] = {
+ // 256 values, max 4095
+ 0x0, 0x1, 0x2, 0x6, 0xa, 0xf, 0x16, 0x1e, 0x27, 0x32, 0x3d, 0x4a, 0x58, 0x67, 0x78, 0x89, 0x9c, 0xb0, 0xc5, 0xdb, 0xf2, 0x10a, 0x123, 0x13e, 0x159, 0x175, 0x193, 0x1b1, 0x1d1, 0x1f1, 0x212, 0x235, 0x258, 0x27c, 0x2a0, 0x2c6, 0x2ed, 0x314, 0x33c, 0x365, 0x38e, 0x3b8, 0x3e3, 0x40e, 0x43a, 0x467, 0x494, 0x4c2, 0x4f0, 0x51f, 0x54e, 0x57d, 0x5ad, 0x5dd, 0x60e, 0x63f, 0x670, 0x6a1, 0x6d3, 0x705, 0x737, 0x769, 0x79b, 0x7cd, 0x800, 0x832, 0x864, 0x896, 0x8c8, 0x8fa, 0x92c, 0x95e, 0x98f, 0x9c0, 0x9f1, 0xa22, 0xa52, 0xa82, 0xab1, 0xae0, 0xb0f, 0xb3d, 0xb6b, 0xb98, 0xbc5, 0xbf1, 0xc1c, 0xc47, 0xc71, 0xc9a, 0xcc3, 0xceb, 0xd12, 0xd39, 0xd5f, 0xd83, 0xda7, 0xdca, 0xded, 0xe0e, 0xe2e, 0xe4e, 0xe6c, 0xe8a, 0xea6, 0xec1, 0xedc, 0xef5, 0xf0d, 0xf24, 0xf3a, 0xf4f, 0xf63, 0xf76, 0xf87, 0xf98, 0xfa7, 0xfb5, 0xfc2, 0xfcd, 0xfd8, 0xfe1, 0xfe9, 0xff0, 0xff5, 0xff9, 0xffd, 0xffe,
+ 0xfff, 0xffe, 0xffd, 0xff9, 0xff5, 0xff0, 0xfe9, 0xfe1, 0xfd8, 0xfcd, 0xfc2, 0xfb5, 0xfa7, 0xf98, 0xf87, 0xf76, 0xf63, 0xf4f, 0xf3a, 0xf24, 0xf0d, 0xef5, 0xedc, 0xec1, 0xea6, 0xe8a, 0xe6c, 0xe4e, 0xe2e, 0xe0e, 0xded, 0xdca, 0xda7, 0xd83, 0xd5f, 0xd39, 0xd12, 0xceb, 0xcc3, 0xc9a, 0xc71, 0xc47, 0xc1c, 0xbf1, 0xbc5, 0xb98, 0xb6b, 0xb3d, 0xb0f, 0xae0, 0xab1, 0xa82, 0xa52, 0xa22, 0x9f1, 0x9c0, 0x98f, 0x95e, 0x92c, 0x8fa, 0x8c8, 0x896, 0x864, 0x832, 0x800, 0x7cd, 0x79b, 0x769, 0x737, 0x705, 0x6d3, 0x6a1, 0x670, 0x63f, 0x60e, 0x5dd, 0x5ad, 0x57d, 0x54e, 0x51f, 0x4f0, 0x4c2, 0x494, 0x467, 0x43a, 0x40e, 0x3e3, 0x3b8, 0x38e, 0x365, 0x33c, 0x314, 0x2ed, 0x2c6, 0x2a0, 0x27c, 0x258, 0x235, 0x212, 0x1f1, 0x1d1, 0x1b1, 0x193, 0x175, 0x159, 0x13e, 0x123, 0x10a, 0xf2, 0xdb, 0xc5, 0xb0, 0x9c, 0x89, 0x78, 0x67, 0x58, 0x4a, 0x3d, 0x32, 0x27, 0x1e, 0x16, 0xf, 0xa, 0x6, 0x2, 0x1};
+#endif // AUDIO_DAC_SAMPLE_WAVEFORM_SINE
+#ifdef AUDIO_DAC_SAMPLE_WAVEFORM_TRIANGLE
+static const dacsample_t dac_buffer_triangle[AUDIO_DAC_BUFFER_SIZE] = {
+ // 256 values, max 4095
+ 0x0, 0x20, 0x40, 0x60, 0x80, 0xa0, 0xc0, 0xe0, 0x100, 0x120, 0x140, 0x160, 0x180, 0x1a0, 0x1c0, 0x1e0, 0x200, 0x220, 0x240, 0x260, 0x280, 0x2a0, 0x2c0, 0x2e0, 0x300, 0x320, 0x340, 0x360, 0x380, 0x3a0, 0x3c0, 0x3e0, 0x400, 0x420, 0x440, 0x460, 0x480, 0x4a0, 0x4c0, 0x4e0, 0x500, 0x520, 0x540, 0x560, 0x580, 0x5a0, 0x5c0, 0x5e0, 0x600, 0x620, 0x640, 0x660, 0x680, 0x6a0, 0x6c0, 0x6e0, 0x700, 0x720, 0x740, 0x760, 0x780, 0x7a0, 0x7c0, 0x7e0, 0x800, 0x81f, 0x83f, 0x85f, 0x87f, 0x89f, 0x8bf, 0x8df, 0x8ff, 0x91f, 0x93f, 0x95f, 0x97f, 0x99f, 0x9bf, 0x9df, 0x9ff, 0xa1f, 0xa3f, 0xa5f, 0xa7f, 0xa9f, 0xabf, 0xadf, 0xaff, 0xb1f, 0xb3f, 0xb5f, 0xb7f, 0xb9f, 0xbbf, 0xbdf, 0xbff, 0xc1f, 0xc3f, 0xc5f, 0xc7f, 0xc9f, 0xcbf, 0xcdf, 0xcff, 0xd1f, 0xd3f, 0xd5f, 0xd7f, 0xd9f, 0xdbf, 0xddf, 0xdff, 0xe1f, 0xe3f, 0xe5f, 0xe7f, 0xe9f, 0xebf, 0xedf, 0xeff, 0xf1f, 0xf3f, 0xf5f, 0xf7f, 0xf9f, 0xfbf, 0xfdf,
+ 0xfff, 0xfdf, 0xfbf, 0xf9f, 0xf7f, 0xf5f, 0xf3f, 0xf1f, 0xeff, 0xedf, 0xebf, 0xe9f, 0xe7f, 0xe5f, 0xe3f, 0xe1f, 0xdff, 0xddf, 0xdbf, 0xd9f, 0xd7f, 0xd5f, 0xd3f, 0xd1f, 0xcff, 0xcdf, 0xcbf, 0xc9f, 0xc7f, 0xc5f, 0xc3f, 0xc1f, 0xbff, 0xbdf, 0xbbf, 0xb9f, 0xb7f, 0xb5f, 0xb3f, 0xb1f, 0xaff, 0xadf, 0xabf, 0xa9f, 0xa7f, 0xa5f, 0xa3f, 0xa1f, 0x9ff, 0x9df, 0x9bf, 0x99f, 0x97f, 0x95f, 0x93f, 0x91f, 0x8ff, 0x8df, 0x8bf, 0x89f, 0x87f, 0x85f, 0x83f, 0x81f, 0x800, 0x7e0, 0x7c0, 0x7a0, 0x780, 0x760, 0x740, 0x720, 0x700, 0x6e0, 0x6c0, 0x6a0, 0x680, 0x660, 0x640, 0x620, 0x600, 0x5e0, 0x5c0, 0x5a0, 0x580, 0x560, 0x540, 0x520, 0x500, 0x4e0, 0x4c0, 0x4a0, 0x480, 0x460, 0x440, 0x420, 0x400, 0x3e0, 0x3c0, 0x3a0, 0x380, 0x360, 0x340, 0x320, 0x300, 0x2e0, 0x2c0, 0x2a0, 0x280, 0x260, 0x240, 0x220, 0x200, 0x1e0, 0x1c0, 0x1a0, 0x180, 0x160, 0x140, 0x120, 0x100, 0xe0, 0xc0, 0xa0, 0x80, 0x60, 0x40, 0x20};
+#endif // AUDIO_DAC_SAMPLE_WAVEFORM_TRIANGLE
+#ifdef AUDIO_DAC_SAMPLE_WAVEFORM_SQUARE
+static const dacsample_t dac_buffer_square[AUDIO_DAC_BUFFER_SIZE] = {
+ [0 ... AUDIO_DAC_BUFFER_SIZE / 2 - 1] = 0, // first and
+ [AUDIO_DAC_BUFFER_SIZE / 2 ... AUDIO_DAC_BUFFER_SIZE - 1] = AUDIO_DAC_SAMPLE_MAX, // second half
+};
+#endif // AUDIO_DAC_SAMPLE_WAVEFORM_SQUARE
+/*
+// four steps: 0, 1/3, 2/3 and 1
+static const dacsample_t dac_buffer_staircase[AUDIO_DAC_BUFFER_SIZE] = {
+ [0 ... AUDIO_DAC_BUFFER_SIZE/3 -1 ] = 0,
+ [AUDIO_DAC_BUFFER_SIZE / 4 ... AUDIO_DAC_BUFFER_SIZE / 2 -1 ] = AUDIO_DAC_SAMPLE_MAX / 3,
+ [AUDIO_DAC_BUFFER_SIZE / 2 ... 3 * AUDIO_DAC_BUFFER_SIZE / 4 -1 ] = 2 * AUDIO_DAC_SAMPLE_MAX / 3,
+ [3 * AUDIO_DAC_BUFFER_SIZE / 4 ... AUDIO_DAC_BUFFER_SIZE -1 ] = AUDIO_DAC_SAMPLE_MAX,
+}
+*/
+#ifdef AUDIO_DAC_SAMPLE_WAVEFORM_TRAPEZOID
+static const dacsample_t dac_buffer_trapezoid[AUDIO_DAC_BUFFER_SIZE] = {0x0, 0x1f, 0x7f, 0xdf, 0x13f, 0x19f, 0x1ff, 0x25f, 0x2bf, 0x31f, 0x37f, 0x3df, 0x43f, 0x49f, 0x4ff, 0x55f, 0x5bf, 0x61f, 0x67f, 0x6df, 0x73f, 0x79f, 0x7ff, 0x85f, 0x8bf, 0x91f, 0x97f, 0x9df, 0xa3f, 0xa9f, 0xaff, 0xb5f, 0xbbf, 0xc1f, 0xc7f, 0xcdf, 0xd3f, 0xd9f, 0xdff, 0xe5f, 0xebf, 0xf1f, 0xf7f, 0xfdf, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff, 0xfff,
+ 0xfff, 0xfdf, 0xf7f, 0xf1f, 0xebf, 0xe5f, 0xdff, 0xd9f, 0xd3f, 0xcdf, 0xc7f, 0xc1f, 0xbbf, 0xb5f, 0xaff, 0xa9f, 0xa3f, 0x9df, 0x97f, 0x91f, 0x8bf, 0x85f, 0x7ff, 0x79f, 0x73f, 0x6df, 0x67f, 0x61f, 0x5bf, 0x55f, 0x4ff, 0x49f, 0x43f, 0x3df, 0x37f, 0x31f, 0x2bf, 0x25f, 0x1ff, 0x19f, 0x13f, 0xdf, 0x7f, 0x1f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
+#endif // AUDIO_DAC_SAMPLE_WAVEFORM_TRAPEZOID
+
+static dacsample_t dac_buffer_empty[AUDIO_DAC_BUFFER_SIZE] = {AUDIO_DAC_OFF_VALUE};
+
+/* keep track of the sample position for for each frequency */
+static float dac_if[AUDIO_MAX_SIMULTANEOUS_TONES] = {0.0};
+
+static float active_tones_snapshot[AUDIO_MAX_SIMULTANEOUS_TONES] = {0, 0};
+static uint8_t active_tones_snapshot_length = 0;
+
+typedef enum {
+ OUTPUT_SHOULD_START,
+ OUTPUT_RUN_NORMALLY,
+ // path 1: wait for zero, then change/update active tones
+ OUTPUT_TONES_CHANGED,
+ OUTPUT_REACHED_ZERO_BEFORE_TONE_CHANGE,
+ // path 2: hardware should stop, wait for zero then turn output off = stop the timer
+ OUTPUT_SHOULD_STOP,
+ OUTPUT_REACHED_ZERO_BEFORE_OFF,
+ OUTPUT_OFF,
+ OUTPUT_OFF_1,
+ OUTPUT_OFF_2, // trailing off: giving the DAC two more conversion cycles until the AUDIO_DAC_OFF_VALUE reaches the output, then turn the timer off, which leaves the output at that level
+ number_of_output_states
+} output_states_t;
+output_states_t state = OUTPUT_OFF_2;
+
+/**
+ * Generation of the waveform being passed to the callback. Declared weak so users
+ * can override it with their own wave-forms/noises.
+ */
+__attribute__((weak)) uint16_t dac_value_generate(void) {
+ // DAC is running/asking for values but snapshot length is zero -> must be playing a pause
+ if (active_tones_snapshot_length == 0) {
+ return AUDIO_DAC_OFF_VALUE;
+ }
+
+ /* doing additive wave synthesis over all currently playing tones = adding up
+ * sine-wave-samples for each frequency, scaled by the number of active tones
+ */
+ uint16_t value = 0;
+ float frequency = 0.0f;
+
+ for (uint8_t i = 0; i < active_tones_snapshot_length; i++) {
+ /* Note: a user implementation does not have to rely on the active_tones_snapshot, but
+ * could directly query the active frequencies through audio_get_processed_frequency */
+ frequency = active_tones_snapshot[i];
+
+ dac_if[i] = dac_if[i] + ((frequency * AUDIO_DAC_BUFFER_SIZE) / AUDIO_DAC_SAMPLE_RATE) * 2 / 3;
+ /*Note: the 2/3 are necessary to get the correct frequencies on the
+ * DAC output (as measured with an oscilloscope), since the gpt
+ * timer runs with 3*AUDIO_DAC_SAMPLE_RATE; and the DAC callback
+ * is called twice per conversion.*/
+
+ dac_if[i] = fmod(dac_if[i], AUDIO_DAC_BUFFER_SIZE);
+
+ // Wavetable generation/lookup
+ uint16_t dac_i = (uint16_t)dac_if[i];
+
+#if defined(AUDIO_DAC_SAMPLE_WAVEFORM_SINE)
+ value += dac_buffer_sine[dac_i] / active_tones_snapshot_length;
+#elif defined(AUDIO_DAC_SAMPLE_WAVEFORM_TRIANGLE)
+ value += dac_buffer_triangle[dac_i] / active_tones_snapshot_length;
+#elif defined(AUDIO_DAC_SAMPLE_WAVEFORM_TRAPEZOID)
+ value += dac_buffer_trapezoid[dac_i] / active_tones_snapshot_length;
+#elif defined(AUDIO_DAC_SAMPLE_WAVEFORM_SQUARE)
+ value += dac_buffer_square[dac_i] / active_tones_snapshot_length;
+#endif
+ /*
+ // SINE
+ value += dac_buffer_sine[dac_i] / active_tones_snapshot_length / 3;
+ // TRIANGLE
+ value += dac_buffer_triangle[dac_i] / active_tones_snapshot_length / 3;
+ // SQUARE
+ value += dac_buffer_square[dac_i] / active_tones_snapshot_length / 3;
+ //NOTE: combination of these three wave-forms is more exemplary - and doesn't sound particularly good :-P
+ */
+
+ // STAIRS (mostly usefully as test-pattern)
+ // value_avg = dac_buffer_staircase[dac_i] / active_tones_snapshot_length;
+ }
+
+ return value;
+}
+
+/**
+ * DAC streaming callback. Does all of the main computing for playing songs.
+ *
+ * Note: chibios calls this CB twice: during the 'half buffer event', and the 'full buffer event'.
+ */
+static void dac_end(DACDriver *dacp) {
+ dacsample_t *sample_p = (dacp)->samples;
+
+ // work on the other half of the buffer
+ if (dacIsBufferComplete(dacp)) {
+ sample_p += AUDIO_DAC_BUFFER_SIZE / 2; // 'half_index'
+ }
+
+ for (uint8_t s = 0; s < AUDIO_DAC_BUFFER_SIZE / 2; s++) {
+ if (OUTPUT_OFF <= state) {
+ sample_p[s] = AUDIO_DAC_OFF_VALUE;
+ continue;
+ } else {
+ sample_p[s] = dac_value_generate();
+ }
+
+ /* zero crossing (or approach, whereas zero == DAC_OFF_VALUE, which can be configured to anything from 0 to DAC_SAMPLE_MAX)
+ * ============================*=*========================== AUDIO_DAC_SAMPLE_MAX
+ * * *
+ * * *
+ * ---------------------------------------------------------
+ * * * } AUDIO_DAC_SAMPLE_MAX/100
+ * --------------------------------------------------------- AUDIO_DAC_OFF_VALUE
+ * * * } AUDIO_DAC_SAMPLE_MAX/100
+ * ---------------------------------------------------------
+ * *
+ * * *
+ * * *
+ * =====*=*================================================= 0x0
+ */
+ if (((sample_p[s] + (AUDIO_DAC_SAMPLE_MAX / 100)) > AUDIO_DAC_OFF_VALUE) && // value approaches from below
+ (sample_p[s] < (AUDIO_DAC_OFF_VALUE + (AUDIO_DAC_SAMPLE_MAX / 100))) // or above
+ ) {
+ if ((OUTPUT_SHOULD_START == state) && (active_tones_snapshot_length > 0)) {
+ state = OUTPUT_RUN_NORMALLY;
+ } else if (OUTPUT_TONES_CHANGED == state) {
+ state = OUTPUT_REACHED_ZERO_BEFORE_TONE_CHANGE;
+ } else if (OUTPUT_SHOULD_STOP == state) {
+ state = OUTPUT_REACHED_ZERO_BEFORE_OFF;
+ }
+ }
+
+ // still 'ramping up', reset the output to OFF_VALUE until the generated values reach that value, to do a smooth handover
+ if (OUTPUT_SHOULD_START == state) {
+ sample_p[s] = AUDIO_DAC_OFF_VALUE;
+ }
+
+ if ((OUTPUT_SHOULD_START == state) || (OUTPUT_REACHED_ZERO_BEFORE_OFF == state) || (OUTPUT_REACHED_ZERO_BEFORE_TONE_CHANGE == state)) {
+ uint8_t active_tones = MIN(AUDIO_MAX_SIMULTANEOUS_TONES, audio_get_number_of_active_tones());
+ active_tones_snapshot_length = 0;
+ // update the snapshot - once, and only on occasion that something changed;
+ // -> saves cpu cycles (?)
+ for (uint8_t i = 0; i < active_tones; i++) {
+ float freq = audio_get_processed_frequency(i);
+ if (freq > 0) { // disregard 'rest' notes, with valid frequency 0.0f; which would only lower the resulting waveform volume during the additive synthesis step
+ active_tones_snapshot[active_tones_snapshot_length++] = freq;
+ }
+ }
+
+ if ((0 == active_tones_snapshot_length) && (OUTPUT_REACHED_ZERO_BEFORE_OFF == state)) {
+ state = OUTPUT_OFF;
+ }
+ if (OUTPUT_REACHED_ZERO_BEFORE_TONE_CHANGE == state) {
+ state = OUTPUT_RUN_NORMALLY;
+ }
+ }
+ }
+
+ // update audio internal state (note position, current_note, ...)
+ if (audio_update_state()) {
+ if (OUTPUT_SHOULD_STOP != state) {
+ state = OUTPUT_TONES_CHANGED;
+ }
+ }
+
+ if (OUTPUT_OFF <= state) {
+ if (OUTPUT_OFF_2 == state) {
+ // stopping timer6 = stopping the DAC at whatever value it is currently pushing to the output = AUDIO_DAC_OFF_VALUE
+ gptStopTimer(&GPTD6);
+ } else {
+ state++;
+ }
+ }
+}
+
+static void dac_error(DACDriver *dacp, dacerror_t err) {
+ (void)dacp;
+ (void)err;
+
+ chSysHalt("DAC failure. halp");
+}
+
+static const GPTConfig gpt6cfg1 = {.frequency = AUDIO_DAC_SAMPLE_RATE * 3,
+ .callback = NULL,
+ .cr2 = TIM_CR2_MMS_1, /* MMS = 010 = TRGO on Update Event. */
+ .dier = 0U};
+
+static const DACConfig dac_conf = {.init = AUDIO_DAC_OFF_VALUE, .datamode = DAC_DHRM_12BIT_RIGHT};
+
+/**
+ * @note The DAC_TRG(0) here selects the Timer 6 TRGO event, which is triggered
+ * on the rising edge after 3 APB1 clock cycles, causing our gpt6cfg1.frequency
+ * to be a third of what we expect.
+ *
+ * Here are all the values for DAC_TRG (TSEL in the ref manual)
+ * TIM15_TRGO 0b011
+ * TIM2_TRGO 0b100
+ * TIM3_TRGO 0b001
+ * TIM6_TRGO 0b000
+ * TIM7_TRGO 0b010
+ * EXTI9 0b110
+ * SWTRIG 0b111
+ */
+static const DACConversionGroup dac_conv_cfg = {.num_channels = 1U, .end_cb = dac_end, .error_cb = dac_error, .trigger = DAC_TRG(0b000)};
+
+void audio_driver_initialize() {
+ if ((AUDIO_PIN == A4) || (AUDIO_PIN_ALT == A4)) {
+ palSetLineMode(A4, PAL_MODE_INPUT_ANALOG);
+ dacStart(&DACD1, &dac_conf);
+ }
+ if ((AUDIO_PIN == A5) || (AUDIO_PIN_ALT == A5)) {
+ palSetLineMode(A5, PAL_MODE_INPUT_ANALOG);
+ dacStart(&DACD2, &dac_conf);
+ }
+
+ /* enable the output buffer, to directly drive external loads with no additional circuitry
+ *
+ * see: AN4566 Application note: Extending the DAC performance of STM32 microcontrollers
+ * Note: Buffer-Off bit -> has to be set 0 to enable the output buffer
+ * Note: enabling the output buffer imparts an additional dc-offset of a couple mV
+ *
+ * this is done here, reaching directly into the stm32 registers since chibios has not implemented BOFF handling yet
+ * (see: chibios/os/hal/ports/STM32/todo.txt '- BOFF handling in DACv1.'
+ */
+ DACD1.params->dac->CR &= ~DAC_CR_BOFF1;
+ DACD2.params->dac->CR &= ~DAC_CR_BOFF2;
+
+ if (AUDIO_PIN == A4) {
+ dacStartConversion(&DACD1, &dac_conv_cfg, dac_buffer_empty, AUDIO_DAC_BUFFER_SIZE);
+ } else if (AUDIO_PIN == A5) {
+ dacStartConversion(&DACD2, &dac_conv_cfg, dac_buffer_empty, AUDIO_DAC_BUFFER_SIZE);
+ }
+
+ // no inverted/out-of-phase waveform (yet?), only pulling AUDIO_PIN_ALT to AUDIO_DAC_OFF_VALUE
+#if defined(AUDIO_PIN_ALT_AS_NEGATIVE)
+ if (AUDIO_PIN_ALT == A4) {
+ dacPutChannelX(&DACD1, 0, AUDIO_DAC_OFF_VALUE);
+ } else if (AUDIO_PIN_ALT == A5) {
+ dacPutChannelX(&DACD2, 0, AUDIO_DAC_OFF_VALUE);
+ }
+#endif
+
+ gptStart(&GPTD6, &gpt6cfg1);
+}
+
+void audio_driver_stop(void) {
+ state = OUTPUT_SHOULD_STOP;
+}
+
+void audio_driver_start(void) {
+ gptStartContinuous(&GPTD6, 2U);
+
+ for (uint8_t i = 0; i < AUDIO_MAX_SIMULTANEOUS_TONES; i++) {
+ dac_if[i] = 0.0f;
+ active_tones_snapshot[i] = 0.0f;
+ }
+ active_tones_snapshot_length = 0;
+ state = OUTPUT_SHOULD_START;
+}
diff --git a/platforms/chibios/drivers/audio_dac_basic.c b/platforms/chibios/drivers/audio_dac_basic.c
new file mode 100644
index 0000000000..64439a1e3c
--- /dev/null
+++ b/platforms/chibios/drivers/audio_dac_basic.c
@@ -0,0 +1,249 @@
+/* Copyright 2016-2020 Jack Humbert
+ * Copyright 2020 JohSchneider
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "audio.h"
+#include "ch.h"
+#include "hal.h"
+
+/*
+ Audio Driver: DAC
+
+ which utilizes both channels of the DAC unit many STM32 are equipped with to output a modulated square-wave, from precomputed samples stored in a buffer, which is passed to the hardware through DMA
+
+ this driver can either be used to drive to separate speakers, wired to A4+Gnd and A5+Gnd, which allows two tones to be played simultaneously
+ OR
+ one speaker wired to A4+A5 with the AUDIO_PIN_ALT_AS_NEGATIVE define set - see docs/feature_audio
+
+*/
+
+#if !defined(AUDIO_PIN)
+# pragma message "Audio feature enabled, but no suitable pin selected as AUDIO_PIN - see docs/feature_audio under 'ARM (DAC basic)' for available options."
+// TODO: make this an 'error' instead; go through a breaking change, and add AUDIO_PIN A5 to all keyboards currently using AUDIO on STM32 based boards? - for now: set the define here
+# define AUDIO_PIN A5
+#endif
+// check configuration for ONE speaker, connected to both DAC pins
+#if defined(AUDIO_PIN_ALT_AS_NEGATIVE) && !defined(AUDIO_PIN_ALT)
+# error "Audio feature: AUDIO_PIN_ALT_AS_NEGATIVE set, but no pin configured as AUDIO_PIN_ALT"
+#endif
+
+#ifndef AUDIO_PIN_ALT
+// no ALT pin defined is valid, but the c-ifs below need some value set
+# define AUDIO_PIN_ALT -1
+#endif
+
+#if !defined(AUDIO_STATE_TIMER)
+# define AUDIO_STATE_TIMER GPTD8
+#endif
+
+// square-wave
+static const dacsample_t dac_buffer_1[AUDIO_DAC_BUFFER_SIZE] = {
+ // First half is max, second half is 0
+ [0 ... AUDIO_DAC_BUFFER_SIZE / 2 - 1] = AUDIO_DAC_SAMPLE_MAX,
+ [AUDIO_DAC_BUFFER_SIZE / 2 ... AUDIO_DAC_BUFFER_SIZE - 1] = 0,
+};
+
+// square-wave
+static const dacsample_t dac_buffer_2[AUDIO_DAC_BUFFER_SIZE] = {
+ // opposite of dac_buffer above
+ [0 ... AUDIO_DAC_BUFFER_SIZE / 2 - 1] = 0,
+ [AUDIO_DAC_BUFFER_SIZE / 2 ... AUDIO_DAC_BUFFER_SIZE - 1] = AUDIO_DAC_SAMPLE_MAX,
+};
+
+GPTConfig gpt6cfg1 = {.frequency = AUDIO_DAC_SAMPLE_RATE,
+ .callback = NULL,
+ .cr2 = TIM_CR2_MMS_1, /* MMS = 010 = TRGO on Update Event. */
+ .dier = 0U};
+GPTConfig gpt7cfg1 = {.frequency = AUDIO_DAC_SAMPLE_RATE,
+ .callback = NULL,
+ .cr2 = TIM_CR2_MMS_1, /* MMS = 010 = TRGO on Update Event. */
+ .dier = 0U};
+
+static void gpt_audio_state_cb(GPTDriver *gptp);
+GPTConfig gptStateUpdateCfg = {.frequency = 10,
+ .callback = gpt_audio_state_cb,
+ .cr2 = TIM_CR2_MMS_1, /* MMS = 010 = TRGO on Update Event. */
+ .dier = 0U};
+
+static const DACConfig dac_conf_ch1 = {.init = AUDIO_DAC_OFF_VALUE, .datamode = DAC_DHRM_12BIT_RIGHT};
+static const DACConfig dac_conf_ch2 = {.init = AUDIO_DAC_OFF_VALUE, .datamode = DAC_DHRM_12BIT_RIGHT};
+
+/**
+ * @note The DAC_TRG(0) here selects the Timer 6 TRGO event, which is triggered
+ * on the rising edge after 3 APB1 clock cycles, causing our gpt6cfg1.frequency
+ * to be a third of what we expect.
+ *
+ * Here are all the values for DAC_TRG (TSEL in the ref manual)
+ * TIM15_TRGO 0b011
+ * TIM2_TRGO 0b100
+ * TIM3_TRGO 0b001
+ * TIM6_TRGO 0b000
+ * TIM7_TRGO 0b010
+ * EXTI9 0b110
+ * SWTRIG 0b111
+ */
+static const DACConversionGroup dac_conv_grp_ch1 = {.num_channels = 1U, .trigger = DAC_TRG(0b000)};
+static const DACConversionGroup dac_conv_grp_ch2 = {.num_channels = 1U, .trigger = DAC_TRG(0b010)};
+
+void channel_1_start(void) {
+ gptStart(&GPTD6, &gpt6cfg1);
+ gptStartContinuous(&GPTD6, 2U);
+ palSetPadMode(GPIOA, 4, PAL_MODE_INPUT_ANALOG);
+}
+
+void channel_1_stop(void) {
+ gptStopTimer(&GPTD6);
+ palSetPadMode(GPIOA, 4, PAL_MODE_OUTPUT_PUSHPULL);
+ palSetPad(GPIOA, 4);
+}
+
+static float channel_1_frequency = 0.0f;
+void channel_1_set_frequency(float freq) {
+ channel_1_frequency = freq;
+
+ channel_1_stop();
+ if (freq <= 0.0) // a pause/rest has freq=0
+ return;
+
+ gpt6cfg1.frequency = 2 * freq * AUDIO_DAC_BUFFER_SIZE;
+ channel_1_start();
+}
+float channel_1_get_frequency(void) {
+ return channel_1_frequency;
+}
+
+void channel_2_start(void) {
+ gptStart(&GPTD7, &gpt7cfg1);
+ gptStartContinuous(&GPTD7, 2U);
+ palSetPadMode(GPIOA, 5, PAL_MODE_INPUT_ANALOG);
+}
+
+void channel_2_stop(void) {
+ gptStopTimer(&GPTD7);
+ palSetPadMode(GPIOA, 5, PAL_MODE_OUTPUT_PUSHPULL);
+ palSetPad(GPIOA, 5);
+}
+
+static float channel_2_frequency = 0.0f;
+void channel_2_set_frequency(float freq) {
+ channel_2_frequency = freq;
+
+ channel_2_stop();
+ if (freq <= 0.0) // a pause/rest has freq=0
+ return;
+
+ gpt7cfg1.frequency = 2 * freq * AUDIO_DAC_BUFFER_SIZE;
+ channel_2_start();
+}
+float channel_2_get_frequency(void) {
+ return channel_2_frequency;
+}
+
+static void gpt_audio_state_cb(GPTDriver *gptp) {
+ if (audio_update_state()) {
+#if defined(AUDIO_PIN_ALT_AS_NEGATIVE)
+ // one piezo/speaker connected to both audio pins, the generated square-waves are inverted
+ channel_1_set_frequency(audio_get_processed_frequency(0));
+ channel_2_set_frequency(audio_get_processed_frequency(0));
+
+#else // two separate audio outputs/speakers
+ // primary speaker on A4, optional secondary on A5
+ if (AUDIO_PIN == A4) {
+ channel_1_set_frequency(audio_get_processed_frequency(0));
+ if (AUDIO_PIN_ALT == A5) {
+ if (audio_get_number_of_active_tones() > 1) {
+ channel_2_set_frequency(audio_get_processed_frequency(1));
+ } else {
+ channel_2_stop();
+ }
+ }
+ }
+
+ // primary speaker on A5, optional secondary on A4
+ if (AUDIO_PIN == A5) {
+ channel_2_set_frequency(audio_get_processed_frequency(0));
+ if (AUDIO_PIN_ALT == A4) {
+ if (audio_get_number_of_active_tones() > 1) {
+ channel_1_set_frequency(audio_get_processed_frequency(1));
+ } else {
+ channel_1_stop();
+ }
+ }
+ }
+#endif
+ }
+}
+
+void audio_driver_initialize() {
+ if ((AUDIO_PIN == A4) || (AUDIO_PIN_ALT == A4)) {
+ palSetPadMode(GPIOA, 4, PAL_MODE_INPUT_ANALOG);
+ dacStart(&DACD1, &dac_conf_ch1);
+
+ // initial setup of the dac-triggering timer is still required, even
+ // though it gets reconfigured and restarted later on
+ gptStart(&GPTD6, &gpt6cfg1);
+ }
+
+ if ((AUDIO_PIN == A5) || (AUDIO_PIN_ALT == A5)) {
+ palSetPadMode(GPIOA, 5, PAL_MODE_INPUT_ANALOG);
+ dacStart(&DACD2, &dac_conf_ch2);
+
+ gptStart(&GPTD7, &gpt7cfg1);
+ }
+
+ /* enable the output buffer, to directly drive external loads with no additional circuitry
+ *
+ * see: AN4566 Application note: Extending the DAC performance of STM32 microcontrollers
+ * Note: Buffer-Off bit -> has to be set 0 to enable the output buffer
+ * Note: enabling the output buffer imparts an additional dc-offset of a couple mV
+ *
+ * this is done here, reaching directly into the stm32 registers since chibios has not implemented BOFF handling yet
+ * (see: chibios/os/hal/ports/STM32/todo.txt '- BOFF handling in DACv1.'
+ */
+ DACD1.params->dac->CR &= ~DAC_CR_BOFF1;
+ DACD2.params->dac->CR &= ~DAC_CR_BOFF2;
+
+ // start state-updater
+ gptStart(&AUDIO_STATE_TIMER, &gptStateUpdateCfg);
+}
+
+void audio_driver_stop(void) {
+ if ((AUDIO_PIN == A4) || (AUDIO_PIN_ALT == A4)) {
+ gptStopTimer(&GPTD6);
+
+ // stop the ongoing conversion and put the output in a known state
+ dacStopConversion(&DACD1);
+ dacPutChannelX(&DACD1, 0, AUDIO_DAC_OFF_VALUE);
+ }
+
+ if ((AUDIO_PIN == A5) || (AUDIO_PIN_ALT == A5)) {
+ gptStopTimer(&GPTD7);
+
+ dacStopConversion(&DACD2);
+ dacPutChannelX(&DACD2, 0, AUDIO_DAC_OFF_VALUE);
+ }
+ gptStopTimer(&AUDIO_STATE_TIMER);
+}
+
+void audio_driver_start(void) {
+ if ((AUDIO_PIN == A4) || (AUDIO_PIN_ALT == A4)) {
+ dacStartConversion(&DACD1, &dac_conv_grp_ch1, (dacsample_t *)dac_buffer_1, AUDIO_DAC_BUFFER_SIZE);
+ }
+ if ((AUDIO_PIN == A5) || (AUDIO_PIN_ALT == A5)) {
+ dacStartConversion(&DACD2, &dac_conv_grp_ch2, (dacsample_t *)dac_buffer_2, AUDIO_DAC_BUFFER_SIZE);
+ }
+ gptStartContinuous(&AUDIO_STATE_TIMER, 2U);
+}
diff --git a/platforms/chibios/drivers/audio_pwm.h b/platforms/chibios/drivers/audio_pwm.h
new file mode 100644
index 0000000000..86cab916e1
--- /dev/null
+++ b/platforms/chibios/drivers/audio_pwm.h
@@ -0,0 +1,40 @@
+/* Copyright 2020 Jack Humbert
+ * Copyright 2020 JohSchneider
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#pragma once
+
+#if !defined(AUDIO_PWM_DRIVER)
+// NOTE: Timer2 seems to be used otherwise in QMK, otherwise we could default to A5 (= TIM2_CH1, with PWMD2 and alternate-function(1))
+# define AUDIO_PWM_DRIVER PWMD1
+#endif
+
+#if !defined(AUDIO_PWM_CHANNEL)
+// NOTE: sticking to the STM data-sheet numbering: TIMxCH1 to TIMxCH4
+// default: STM32F303CC PA8+TIM1_CH1 -> 1
+# define AUDIO_PWM_CHANNEL 1
+#endif
+
+#if !defined(AUDIO_PWM_PAL_MODE)
+// pin-alternate function: see the data-sheet for which pin needs what AF to connect to TIMx_CHy
+// default: STM32F303CC PA8+TIM1_CH1 -> 6
+# define AUDIO_PWM_PAL_MODE 6
+#endif
+
+#if !defined(AUDIO_STATE_TIMER)
+// timer used to trigger updates in the audio-system, configured/enabled in chibios mcuconf.
+// Tim6 is the default for "larger" STMs, smaller ones might not have this one (enabled) and need to switch to a different one (e.g.: STM32F103 has only Tim1-Tim4)
+# define AUDIO_STATE_TIMER GPTD6
+#endif
diff --git a/platforms/chibios/drivers/audio_pwm_hardware.c b/platforms/chibios/drivers/audio_pwm_hardware.c
new file mode 100644
index 0000000000..710f397609
--- /dev/null
+++ b/platforms/chibios/drivers/audio_pwm_hardware.c
@@ -0,0 +1,148 @@
+/* Copyright 2020 Jack Humbert
+ * Copyright 2020 JohSchneider
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/*
+Audio Driver: PWM
+
+the duty-cycle is always kept at 50%, and the pwm-period is adjusted to match the frequency of a note to be played back.
+
+this driver uses the chibios-PWM system to produce a square-wave on specific output pins that are connected to the PWM hardware.
+The hardware directly toggles the pin via its alternate function. see your MCUs data-sheet for which pin can be driven by what timer - looking for TIMx_CHy and the corresponding alternate function.
+
+ */
+
+#include "audio.h"
+#include "ch.h"
+#include "hal.h"
+
+#if !defined(AUDIO_PIN)
+# error "Audio feature enabled, but no pin selected - see docs/feature_audio under the ARM PWM settings"
+#endif
+
+extern bool playing_note;
+extern bool playing_melody;
+extern uint8_t note_timbre;
+
+static PWMConfig pwmCFG = {
+ .frequency = 100000, /* PWM clock frequency */
+ // CHIBIOS-BUG? can't set the initial period to <2, or the pwm (hard or software) takes ~130ms with .frequency=500000 for a pwmChangePeriod to take effect; with no output=silence in the meantime
+ .period = 2, /* initial PWM period (in ticks) 1S (1/10kHz=0.1mS 0.1ms*10000 ticks=1S) */
+ .callback = NULL, /* no callback, the hardware directly toggles the pin */
+ .channels =
+ {
+#if AUDIO_PWM_CHANNEL == 4
+ {PWM_OUTPUT_DISABLED, NULL}, /* channel 0 -> TIMx_CH1 */
+ {PWM_OUTPUT_DISABLED, NULL}, /* channel 1 -> TIMx_CH2 */
+ {PWM_OUTPUT_DISABLED, NULL}, /* channel 2 -> TIMx_CH3 */
+ {PWM_OUTPUT_ACTIVE_HIGH, NULL} /* channel 3 -> TIMx_CH4 */
+#elif AUDIO_PWM_CHANNEL == 3
+ {PWM_OUTPUT_DISABLED, NULL},
+ {PWM_OUTPUT_DISABLED, NULL},
+ {PWM_OUTPUT_ACTIVE_HIGH, NULL}, /* TIMx_CH3 */
+ {PWM_OUTPUT_DISABLED, NULL}
+#elif AUDIO_PWM_CHANNEL == 2
+ {PWM_OUTPUT_DISABLED, NULL},
+ {PWM_OUTPUT_ACTIVE_HIGH, NULL}, /* TIMx_CH2 */
+ {PWM_OUTPUT_DISABLED, NULL},
+ {PWM_OUTPUT_DISABLED, NULL}
+#else /*fallback to CH1 */
+ {PWM_OUTPUT_ACTIVE_HIGH, NULL}, /* TIMx_CH1 */
+ {PWM_OUTPUT_DISABLED, NULL},
+ {PWM_OUTPUT_DISABLED, NULL},
+ {PWM_OUTPUT_DISABLED, NULL}
+#endif
+ },
+};
+
+static float channel_1_frequency = 0.0f;
+void channel_1_set_frequency(float freq) {
+ channel_1_frequency = freq;
+
+ if (freq <= 0.0) // a pause/rest has freq=0
+ return;
+
+ pwmcnt_t period = (pwmCFG.frequency / freq);
+ pwmChangePeriod(&AUDIO_PWM_DRIVER, period);
+ pwmEnableChannel(&AUDIO_PWM_DRIVER, AUDIO_PWM_CHANNEL - 1,
+ // adjust the duty-cycle so that the output is for 'note_timbre' duration HIGH
+ PWM_PERCENTAGE_TO_WIDTH(&AUDIO_PWM_DRIVER, (100 - note_timbre) * 100));
+}
+
+float channel_1_get_frequency(void) {
+ return channel_1_frequency;
+}
+
+void channel_1_start(void) {
+ pwmStop(&AUDIO_PWM_DRIVER);
+ pwmStart(&AUDIO_PWM_DRIVER, &pwmCFG);
+}
+
+void channel_1_stop(void) {
+ pwmStop(&AUDIO_PWM_DRIVER);
+}
+
+static void gpt_callback(GPTDriver *gptp);
+GPTConfig gptCFG = {
+ /* a whole note is one beat, which is - per definition in musical_notes.h - set to 64
+ the longest note is BREAVE_DOT=128+64=192, the shortest SIXTEENTH=4
+ the tempo (which might vary!) is in bpm (beats per minute)
+ therefore: if the timer ticks away at .frequency = (60*64)Hz,
+ and the .interval counts from 64 downwards - audio_update_state is
+ called just often enough to not miss any notes
+ */
+ .frequency = 60 * 64,
+ .callback = gpt_callback,
+};
+
+void audio_driver_initialize(void) {
+ pwmStart(&AUDIO_PWM_DRIVER, &pwmCFG);
+
+ // connect the AUDIO_PIN to the PWM hardware
+#if defined(USE_GPIOV1) // STM32F103C8
+ palSetLineMode(AUDIO_PIN, PAL_MODE_ALTERNATE_PUSHPULL);
+#else // GPIOv2 (or GPIOv3 for f4xx, which is the same/compatible at this command)
+ palSetLineMode(AUDIO_PIN, PAL_MODE_ALTERNATE(AUDIO_PWM_PAL_MODE));
+#endif
+
+ gptStart(&AUDIO_STATE_TIMER, &gptCFG);
+}
+
+void audio_driver_start(void) {
+ channel_1_stop();
+ channel_1_start();
+
+ if (playing_note || playing_melody) {
+ gptStartContinuous(&AUDIO_STATE_TIMER, 64);
+ }
+}
+
+void audio_driver_stop(void) {
+ channel_1_stop();
+ gptStopTimer(&AUDIO_STATE_TIMER);
+}
+
+/* a regular timer task, that checks the note to be currently played
+ * and updates the pwm to output that frequency
+ */
+static void gpt_callback(GPTDriver *gptp) {
+ float freq; // TODO: freq_alt
+
+ if (audio_update_state()) {
+ freq = audio_get_processed_frequency(0); // freq_alt would be index=1
+ channel_1_set_frequency(freq);
+ }
+}
diff --git a/platforms/chibios/drivers/audio_pwm_software.c b/platforms/chibios/drivers/audio_pwm_software.c
new file mode 100644
index 0000000000..e01f86ea52
--- /dev/null
+++ b/platforms/chibios/drivers/audio_pwm_software.c
@@ -0,0 +1,166 @@
+/* Copyright 2020 Jack Humbert
+ * Copyright 2020 JohSchneider
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/*
+Audio Driver: PWM
+
+the duty-cycle is always kept at 50%, and the pwm-period is adjusted to match the frequency of a note to be played back.
+
+this driver uses the chibios-PWM system to produce a square-wave on any given output pin in software
+- a pwm callback is used to set/clear the configured pin.
+
+ */
+#include "audio.h"
+#include "ch.h"
+#include "hal.h"
+
+#if !defined(AUDIO_PIN)
+# error "Audio feature enabled, but no pin selected - see docs/feature_audio under the ARM PWM settings"
+#endif
+extern bool playing_note;
+extern bool playing_melody;
+extern uint8_t note_timbre;
+
+static void pwm_audio_period_callback(PWMDriver *pwmp);
+static void pwm_audio_channel_interrupt_callback(PWMDriver *pwmp);
+
+static PWMConfig pwmCFG = {
+ .frequency = 100000, /* PWM clock frequency */
+ // CHIBIOS-BUG? can't set the initial period to <2, or the pwm (hard or software) takes ~130ms with .frequency=500000 for a pwmChangePeriod to take effect; with no output=silence in the meantime
+ .period = 2, /* initial PWM period (in ticks) 1S (1/10kHz=0.1mS 0.1ms*10000 ticks=1S) */
+ .callback = pwm_audio_period_callback,
+ .channels =
+ {
+ // software-PWM just needs another callback on any channel
+ {PWM_OUTPUT_ACTIVE_HIGH, pwm_audio_channel_interrupt_callback}, /* channel 0 -> TIMx_CH1 */
+ {PWM_OUTPUT_DISABLED, NULL}, /* channel 1 -> TIMx_CH2 */
+ {PWM_OUTPUT_DISABLED, NULL}, /* channel 2 -> TIMx_CH3 */
+ {PWM_OUTPUT_DISABLED, NULL} /* channel 3 -> TIMx_CH4 */
+ },
+};
+
+static float channel_1_frequency = 0.0f;
+void channel_1_set_frequency(float freq) {
+ channel_1_frequency = freq;
+
+ if (freq <= 0.0) // a pause/rest has freq=0
+ return;
+
+ pwmcnt_t period = (pwmCFG.frequency / freq);
+ pwmChangePeriod(&AUDIO_PWM_DRIVER, period);
+
+ pwmEnableChannel(&AUDIO_PWM_DRIVER, AUDIO_PWM_CHANNEL - 1,
+ // adjust the duty-cycle so that the output is for 'note_timbre' duration HIGH
+ PWM_PERCENTAGE_TO_WIDTH(&AUDIO_PWM_DRIVER, (100 - note_timbre) * 100));
+}
+
+float channel_1_get_frequency(void) {
+ return channel_1_frequency;
+}
+
+void channel_1_start(void) {
+ pwmStop(&AUDIO_PWM_DRIVER);
+ pwmStart(&AUDIO_PWM_DRIVER, &pwmCFG);
+
+ pwmEnablePeriodicNotification(&AUDIO_PWM_DRIVER);
+ pwmEnableChannelNotification(&AUDIO_PWM_DRIVER, AUDIO_PWM_CHANNEL - 1);
+}
+
+void channel_1_stop(void) {
+ pwmStop(&AUDIO_PWM_DRIVER);
+
+ palClearLine(AUDIO_PIN); // leave the line low, after last note was played
+
+#if defined(AUDIO_PIN_ALT) && defined(AUDIO_PIN_ALT_AS_NEGATIVE)
+ palClearLine(AUDIO_PIN_ALT); // leave the line low, after last note was played
+#endif
+}
+
+// generate a PWM signal on any pin, not necessarily the one connected to the timer
+static void pwm_audio_period_callback(PWMDriver *pwmp) {
+ (void)pwmp;
+ palClearLine(AUDIO_PIN);
+
+#if defined(AUDIO_PIN_ALT) && defined(AUDIO_PIN_ALT_AS_NEGATIVE)
+ palSetLine(AUDIO_PIN_ALT);
+#endif
+}
+static void pwm_audio_channel_interrupt_callback(PWMDriver *pwmp) {
+ (void)pwmp;
+ if (channel_1_frequency > 0) {
+ palSetLine(AUDIO_PIN); // generate a PWM signal on any pin, not necessarily the one connected to the timer
+#if defined(AUDIO_PIN_ALT) && defined(AUDIO_PIN_ALT_AS_NEGATIVE)
+ palClearLine(AUDIO_PIN_ALT);
+#endif
+ }
+}
+
+static void gpt_callback(GPTDriver *gptp);
+GPTConfig gptCFG = {
+ /* a whole note is one beat, which is - per definition in musical_notes.h - set to 64
+ the longest note is BREAVE_DOT=128+64=192, the shortest SIXTEENTH=4
+ the tempo (which might vary!) is in bpm (beats per minute)
+ therefore: if the timer ticks away at .frequency = (60*64)Hz,
+ and the .interval counts from 64 downwards - audio_update_state is
+ called just often enough to not miss anything
+ */
+ .frequency = 60 * 64,
+ .callback = gpt_callback,
+};
+
+void audio_driver_initialize(void) {
+ pwmStart(&AUDIO_PWM_DRIVER, &pwmCFG);
+
+ palSetLineMode(AUDIO_PIN, PAL_MODE_OUTPUT_PUSHPULL);
+ palClearLine(AUDIO_PIN);
+
+#if defined(AUDIO_PIN_ALT) && defined(AUDIO_PIN_ALT_AS_NEGATIVE)
+ palSetLineMode(AUDIO_PIN_ALT, PAL_MODE_OUTPUT_PUSHPULL);
+ palClearLine(AUDIO_PIN_ALT);
+#endif
+
+ pwmEnablePeriodicNotification(&AUDIO_PWM_DRIVER); // enable pwm callbacks
+ pwmEnableChannelNotification(&AUDIO_PWM_DRIVER, AUDIO_PWM_CHANNEL - 1);
+
+ gptStart(&AUDIO_STATE_TIMER, &gptCFG);
+}
+
+void audio_driver_start(void) {
+ channel_1_stop();
+ channel_1_start();
+
+ if (playing_note || playing_melody) {
+ gptStartContinuous(&AUDIO_STATE_TIMER, 64);
+ }
+}
+
+void audio_driver_stop(void) {
+ channel_1_stop();
+ gptStopTimer(&AUDIO_STATE_TIMER);
+}
+
+/* a regular timer task, that checks the note to be currently played
+ * and updates the pwm to output that frequency
+ */
+static void gpt_callback(GPTDriver *gptp) {
+ float freq; // TODO: freq_alt
+
+ if (audio_update_state()) {
+ freq = audio_get_processed_frequency(0); // freq_alt would be index=1
+ channel_1_set_frequency(freq);
+ }
+}
diff --git a/platforms/chibios/drivers/eeprom/eeprom_stm32_L0_L1.h b/platforms/chibios/drivers/eeprom/eeprom_stm32_L0_L1.h
index a35defca8b..616d7ccbee 100644
--- a/platforms/chibios/drivers/eeprom/eeprom_stm32_L0_L1.h
+++ b/platforms/chibios/drivers/eeprom/eeprom_stm32_L0_L1.h
@@ -24,7 +24,7 @@
# define STM32_ONBOARD_EEPROM_SIZE 1024
# else
# include "eeconfig.h"
-# define STM32_ONBOARD_EEPROM_SIZE (((EECONFIG_SIZE + 3) / 4) * 4) // based off eeconfig's current usage, aligned to 4-byte sizes, to deal with LTO and EEPROM page sizing
+# define STM32_ONBOARD_EEPROM_SIZE (((EECONFIG_SIZE + 3) / 4) * 4) // based off eeconfig's current usage, aligned to 4-byte sizes, to deal with LTO and EEPROM page sizing
# endif
#endif
diff --git a/platforms/chibios/drivers/i2c_master.c b/platforms/chibios/drivers/i2c_master.c
index fc4bb2ab37..21e064b1dc 100644
--- a/platforms/chibios/drivers/i2c_master.c
+++ b/platforms/chibios/drivers/i2c_master.c
@@ -27,8 +27,67 @@
#include "quantum.h"
#include "i2c_master.h"
#include <string.h>
+#include <ch.h>
#include <hal.h>
+#ifndef I2C1_SCL_PIN
+# define I2C1_SCL_PIN B6
+#endif
+#ifndef I2C1_SDA_PIN
+# define I2C1_SDA_PIN B7
+#endif
+
+#ifdef USE_I2CV1
+# ifndef I2C1_OPMODE
+# define I2C1_OPMODE OPMODE_I2C
+# endif
+# ifndef I2C1_CLOCK_SPEED
+# define I2C1_CLOCK_SPEED 100000 /* 400000 */
+# endif
+# ifndef I2C1_DUTY_CYCLE
+# define I2C1_DUTY_CYCLE STD_DUTY_CYCLE /* FAST_DUTY_CYCLE_2 */
+# endif
+#else
+// The default timing values below configures the I2C clock to 400khz assuming a 72Mhz clock
+// For more info : https://www.st.com/en/embedded-software/stsw-stm32126.html
+# ifndef I2C1_TIMINGR_PRESC
+# define I2C1_TIMINGR_PRESC 0U
+# endif
+# ifndef I2C1_TIMINGR_SCLDEL
+# define I2C1_TIMINGR_SCLDEL 7U
+# endif
+# ifndef I2C1_TIMINGR_SDADEL
+# define I2C1_TIMINGR_SDADEL 0U
+# endif
+# ifndef I2C1_TIMINGR_SCLH
+# define I2C1_TIMINGR_SCLH 38U
+# endif
+# ifndef I2C1_TIMINGR_SCLL
+# define I2C1_TIMINGR_SCLL 129U
+# endif
+#endif
+
+#ifndef I2C_DRIVER
+# define I2C_DRIVER I2CD1
+#endif
+
+#ifdef USE_GPIOV1
+# ifndef I2C1_SCL_PAL_MODE
+# define I2C1_SCL_PAL_MODE PAL_MODE_ALTERNATE_OPENDRAIN
+# endif
+# ifndef I2C1_SDA_PAL_MODE
+# define I2C1_SDA_PAL_MODE PAL_MODE_ALTERNATE_OPENDRAIN
+# endif
+#else
+// The default PAL alternate modes are used to signal that the pins are used for I2C
+# ifndef I2C1_SCL_PAL_MODE
+# define I2C1_SCL_PAL_MODE 4
+# endif
+# ifndef I2C1_SDA_PAL_MODE
+# define I2C1_SDA_PAL_MODE 4
+# endif
+#endif
+
static uint8_t i2c_address;
static const I2CConfig i2cconfig = {
@@ -38,6 +97,9 @@ static const I2CConfig i2cconfig = {
I2C1_OPMODE,
I2C1_CLOCK_SPEED,
I2C1_DUTY_CYCLE,
+#elif defined(WB32F3G71xx) || defined(WB32FQ95xx)
+ I2C1_OPMODE,
+ I2C1_CLOCK_SPEED,
#else
// This configures the I2C clock to 400khz assuming a 72Mhz clock
// For more info : https://www.st.com/en/embedded-software/stsw-stm32126.html
@@ -63,16 +125,16 @@ __attribute__((weak)) void i2c_init(void) {
is_initialised = true;
// Try releasing special pins for a short time
- palSetPadMode(I2C1_SCL_BANK, I2C1_SCL, PAL_MODE_INPUT);
- palSetPadMode(I2C1_SDA_BANK, I2C1_SDA, PAL_MODE_INPUT);
+ palSetLineMode(I2C1_SCL_PIN, PAL_MODE_INPUT);
+ palSetLineMode(I2C1_SDA_PIN, PAL_MODE_INPUT);
chThdSleepMilliseconds(10);
#if defined(USE_GPIOV1)
- palSetPadMode(I2C1_SCL_BANK, I2C1_SCL, I2C1_SCL_PAL_MODE);
- palSetPadMode(I2C1_SDA_BANK, I2C1_SDA, I2C1_SDA_PAL_MODE);
+ palSetLineMode(I2C1_SCL_PIN, I2C1_SCL_PAL_MODE);
+ palSetLineMode(I2C1_SDA_PIN, I2C1_SDA_PAL_MODE);
#else
- palSetPadMode(I2C1_SCL_BANK, I2C1_SCL, PAL_MODE_ALTERNATE(I2C1_SCL_PAL_MODE) | PAL_STM32_OTYPE_OPENDRAIN);
- palSetPadMode(I2C1_SDA_BANK, I2C1_SDA, PAL_MODE_ALTERNATE(I2C1_SDA_PAL_MODE) | PAL_STM32_OTYPE_OPENDRAIN);
+ palSetLineMode(I2C1_SCL_PIN, PAL_MODE_ALTERNATE(I2C1_SCL_PAL_MODE) | PAL_OUTPUT_TYPE_OPENDRAIN);
+ palSetLineMode(I2C1_SDA_PIN, PAL_MODE_ALTERNATE(I2C1_SDA_PAL_MODE) | PAL_OUTPUT_TYPE_OPENDRAIN);
#endif
}
}
@@ -102,7 +164,7 @@ i2c_status_t i2c_writeReg(uint8_t devaddr, uint8_t regaddr, const uint8_t* data,
i2cStart(&I2C_DRIVER, &i2cconfig);
uint8_t complete_packet[length + 1];
- for (uint8_t i = 0; i < length; i++) {
+ for (uint16_t i = 0; i < length; i++) {
complete_packet[i + 1] = data[i];
}
complete_packet[0] = regaddr;
@@ -111,6 +173,21 @@ i2c_status_t i2c_writeReg(uint8_t devaddr, uint8_t regaddr, const uint8_t* data,
return chibios_to_qmk(&status);
}
+i2c_status_t i2c_writeReg16(uint8_t devaddr, uint16_t regaddr, const uint8_t* data, uint16_t length, uint16_t timeout) {
+ i2c_address = devaddr;
+ i2cStart(&I2C_DRIVER, &i2cconfig);
+
+ uint8_t complete_packet[length + 2];
+ for (uint16_t i = 0; i < length; i++) {
+ complete_packet[i + 2] = data[i];
+ }
+ complete_packet[0] = regaddr >> 8;
+ complete_packet[1] = regaddr & 0xFF;
+
+ msg_t status = i2cMasterTransmitTimeout(&I2C_DRIVER, (i2c_address >> 1), complete_packet, length + 2, 0, 0, TIME_MS2I(timeout));
+ return chibios_to_qmk(&status);
+}
+
i2c_status_t i2c_readReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16_t length, uint16_t timeout) {
i2c_address = devaddr;
i2cStart(&I2C_DRIVER, &i2cconfig);
@@ -118,4 +195,14 @@ i2c_status_t i2c_readReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16
return chibios_to_qmk(&status);
}
-void i2c_stop(void) { i2cStop(&I2C_DRIVER); }
+i2c_status_t i2c_readReg16(uint8_t devaddr, uint16_t regaddr, uint8_t* data, uint16_t length, uint16_t timeout) {
+ i2c_address = devaddr;
+ i2cStart(&I2C_DRIVER, &i2cconfig);
+ uint8_t register_packet[2] = {regaddr >> 8, regaddr & 0xFF};
+ msg_t status = i2cMasterTransmitTimeout(&I2C_DRIVER, (i2c_address >> 1), register_packet, 2, data, length, TIME_MS2I(timeout));
+ return chibios_to_qmk(&status);
+}
+
+void i2c_stop(void) {
+ i2cStop(&I2C_DRIVER);
+}
diff --git a/platforms/chibios/drivers/i2c_master.h b/platforms/chibios/drivers/i2c_master.h
index c68109acbd..deee7ecc08 100644
--- a/platforms/chibios/drivers/i2c_master.h
+++ b/platforms/chibios/drivers/i2c_master.h
@@ -24,79 +24,7 @@
*/
#pragma once
-#include <ch.h>
-#include <hal.h>
-
-#ifdef I2C1_BANK
-# define I2C1_SCL_BANK I2C1_BANK
-# define I2C1_SDA_BANK I2C1_BANK
-#endif
-
-#ifndef I2C1_SCL_BANK
-# define I2C1_SCL_BANK GPIOB
-#endif
-
-#ifndef I2C1_SDA_BANK
-# define I2C1_SDA_BANK GPIOB
-#endif
-
-#ifndef I2C1_SCL
-# define I2C1_SCL 6
-#endif
-#ifndef I2C1_SDA
-# define I2C1_SDA 7
-#endif
-
-#ifdef USE_I2CV1
-# ifndef I2C1_OPMODE
-# define I2C1_OPMODE OPMODE_I2C
-# endif
-# ifndef I2C1_CLOCK_SPEED
-# define I2C1_CLOCK_SPEED 100000 /* 400000 */
-# endif
-# ifndef I2C1_DUTY_CYCLE
-# define I2C1_DUTY_CYCLE STD_DUTY_CYCLE /* FAST_DUTY_CYCLE_2 */
-# endif
-#else
-// The default timing values below configures the I2C clock to 400khz assuming a 72Mhz clock
-// For more info : https://www.st.com/en/embedded-software/stsw-stm32126.html
-# ifndef I2C1_TIMINGR_PRESC
-# define I2C1_TIMINGR_PRESC 0U
-# endif
-# ifndef I2C1_TIMINGR_SCLDEL
-# define I2C1_TIMINGR_SCLDEL 7U
-# endif
-# ifndef I2C1_TIMINGR_SDADEL
-# define I2C1_TIMINGR_SDADEL 0U
-# endif
-# ifndef I2C1_TIMINGR_SCLH
-# define I2C1_TIMINGR_SCLH 38U
-# endif
-# ifndef I2C1_TIMINGR_SCLL
-# define I2C1_TIMINGR_SCLL 129U
-# endif
-#endif
-
-#ifndef I2C_DRIVER
-# define I2C_DRIVER I2CD1
-#endif
-
-#ifdef USE_GPIOV1
-# ifndef I2C1_SCL_PAL_MODE
-# define I2C1_SCL_PAL_MODE PAL_MODE_STM32_ALTERNATE_OPENDRAIN
-# endif
-# ifndef I2C1_SDA_PAL_MODE
-# define I2C1_SDA_PAL_MODE PAL_MODE_STM32_ALTERNATE_OPENDRAIN
-# endif
-#else
-// The default PAL alternate modes are used to signal that the pins are used for I2C
-# ifndef I2C1_SCL_PAL_MODE
-# define I2C1_SCL_PAL_MODE 4
-# endif
-# ifndef I2C1_SDA_PAL_MODE
-# define I2C1_SDA_PAL_MODE 4
-# endif
-#endif
+#include <stdint.h>
typedef int16_t i2c_status_t;
@@ -109,5 +37,7 @@ i2c_status_t i2c_start(uint8_t address);
i2c_status_t i2c_transmit(uint8_t address, const uint8_t* data, uint16_t length, uint16_t timeout);
i2c_status_t i2c_receive(uint8_t address, uint8_t* data, uint16_t length, uint16_t timeout);
i2c_status_t i2c_writeReg(uint8_t devaddr, uint8_t regaddr, const uint8_t* data, uint16_t length, uint16_t timeout);
+i2c_status_t i2c_writeReg16(uint8_t devaddr, uint16_t regaddr, const uint8_t* data, uint16_t length, uint16_t timeout);
i2c_status_t i2c_readReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16_t length, uint16_t timeout);
+i2c_status_t i2c_readReg16(uint8_t devaddr, uint16_t regaddr, uint8_t* data, uint16_t length, uint16_t timeout);
void i2c_stop(void);
diff --git a/platforms/chibios/drivers/ps2/ps2_io.c b/platforms/chibios/drivers/ps2/ps2_io.c
new file mode 100644
index 0000000000..906d85d848
--- /dev/null
+++ b/platforms/chibios/drivers/ps2/ps2_io.c
@@ -0,0 +1,55 @@
+#include <stdbool.h>
+#include "ps2_io.h"
+
+// chibiOS headers
+#include "ch.h"
+#include "hal.h"
+
+/* Check port settings for clock and data line */
+#if !(defined(PS2_CLOCK_PIN))
+# error "PS/2 clock setting is required in config.h"
+#endif
+
+#if !(defined(PS2_DATA_PIN))
+# error "PS/2 data setting is required in config.h"
+#endif
+
+/*
+ * Clock
+ */
+void clock_init(void) {}
+
+void clock_lo(void) {
+ palSetLineMode(PS2_CLOCK_PIN, PAL_MODE_OUTPUT_OPENDRAIN);
+ palWriteLine(PS2_CLOCK_PIN, PAL_LOW);
+}
+
+void clock_hi(void) {
+ palSetLineMode(PS2_CLOCK_PIN, PAL_MODE_OUTPUT_OPENDRAIN);
+ palWriteLine(PS2_CLOCK_PIN, PAL_HIGH);
+}
+
+bool clock_in(void) {
+ palSetLineMode(PS2_CLOCK_PIN, PAL_MODE_INPUT);
+ return palReadLine(PS2_CLOCK_PIN);
+}
+
+/*
+ * Data
+ */
+void data_init(void) {}
+
+void data_lo(void) {
+ palSetLineMode(PS2_DATA_PIN, PAL_MODE_OUTPUT_OPENDRAIN);
+ palWriteLine(PS2_DATA_PIN, PAL_LOW);
+}
+
+void data_hi(void) {
+ palSetLineMode(PS2_DATA_PIN, PAL_MODE_OUTPUT_OPENDRAIN);
+ palWriteLine(PS2_DATA_PIN, PAL_HIGH);
+}
+
+bool data_in(void) {
+ palSetLineMode(PS2_DATA_PIN, PAL_MODE_INPUT);
+ return palReadLine(PS2_DATA_PIN);
+}
diff --git a/platforms/chibios/drivers/serial.c b/platforms/chibios/drivers/serial.c
index f54fbcee4e..0cff057d1d 100644
--- a/platforms/chibios/drivers/serial.c
+++ b/platforms/chibios/drivers/serial.c
@@ -5,6 +5,7 @@
#include "quantum.h"
#include "serial.h"
#include "wait.h"
+#include "synchronization_util.h"
#include <hal.h>
@@ -19,7 +20,7 @@
# error "chSysPolledDelayX method not supported on this platform"
#else
# undef wait_us
-# define wait_us(x) chSysPolledDelayX(US2RTC(STM32_SYSCLK, x))
+# define wait_us(x) chSysPolledDelayX(US2RTC(CPU_CLOCK, x))
#endif
#ifndef SELECT_SOFT_SERIAL_SPEED
@@ -50,14 +51,30 @@
# error invalid SELECT_SOFT_SERIAL_SPEED value
#endif
-inline static void serial_delay(void) { wait_us(SERIAL_DELAY); }
-inline static void serial_delay_half(void) { wait_us(SERIAL_DELAY / 2); }
-inline static void serial_delay_blip(void) { wait_us(1); }
-inline static void serial_output(void) { setPinOutput(SOFT_SERIAL_PIN); }
-inline static void serial_input(void) { setPinInputHigh(SOFT_SERIAL_PIN); }
-inline static bool serial_read_pin(void) { return !!readPin(SOFT_SERIAL_PIN); }
-inline static void serial_low(void) { writePinLow(SOFT_SERIAL_PIN); }
-inline static void serial_high(void) { writePinHigh(SOFT_SERIAL_PIN); }
+inline static void serial_delay(void) {
+ wait_us(SERIAL_DELAY);
+}
+inline static void serial_delay_half(void) {
+ wait_us(SERIAL_DELAY / 2);
+}
+inline static void serial_delay_blip(void) {
+ wait_us(1);
+}
+inline static void serial_output(void) {
+ setPinOutput(SOFT_SERIAL_PIN);
+}
+inline static void serial_input(void) {
+ setPinInputHigh(SOFT_SERIAL_PIN);
+}
+inline static bool serial_read_pin(void) {
+ return !!readPin(SOFT_SERIAL_PIN);
+}
+inline static void serial_low(void) {
+ writePinLow(SOFT_SERIAL_PIN);
+}
+inline static void serial_high(void) {
+ writePinHigh(SOFT_SERIAL_PIN);
+}
void interrupt_handler(void *arg);
@@ -70,7 +87,10 @@ static THD_FUNCTION(Thread1, arg) {
chRegSetThreadName("blinker");
while (true) {
palWaitLineTimeout(SOFT_SERIAL_PIN, TIME_INFINITE);
+
+ split_shared_memory_lock();
interrupt_handler(NULL);
+ split_shared_memory_unlock();
}
}
@@ -155,7 +175,8 @@ void interrupt_handler(void *arg) {
checksum_computed += split_trans_initiator2target_buffer(trans)[i];
}
checksum_computed ^= 7;
- uint8_t checksum_received = serial_read_byte();
+
+ serial_read_byte();
sync_send();
// wait for the sync to finish sending
@@ -179,8 +200,6 @@ void interrupt_handler(void *arg) {
// wait for the sync to finish sending
serial_delay();
- *trans->status = (checksum_computed == checksum_received) ? TRANSACTION_ACCEPTED : TRANSACTION_DATA_ERROR;
-
// end transaction
serial_input();
@@ -190,20 +209,10 @@ void interrupt_handler(void *arg) {
chSysUnlockFromISR();
}
-/////////
-// start transaction by initiator
-//
-// int soft_serial_transaction(int sstd_index)
-//
-// Returns:
-// TRANSACTION_END
-// TRANSACTION_NO_RESPONSE
-// TRANSACTION_DATA_ERROR
-// this code is very time dependent, so we need to disable interrupts
-int soft_serial_transaction(int sstd_index) {
- if (sstd_index > NUM_TOTAL_TRANSACTIONS) return TRANSACTION_TYPE_ERROR;
+static inline bool initiate_transaction(uint8_t sstd_index) {
+ if (sstd_index > NUM_TOTAL_TRANSACTIONS) return false;
+
split_transaction_desc_t *trans = &split_transaction_table[sstd_index];
- if (!trans->status) return TRANSACTION_TYPE_ERROR; // not registered
// TODO: remove extra delay between transactions
serial_delay();
@@ -226,14 +235,13 @@ int soft_serial_transaction(int sstd_index) {
// slave failed to pull the line low, assume not present
dprintf("serial::NO_RESPONSE\n");
chSysUnlock();
- return TRANSACTION_NO_RESPONSE;
+ return false;
}
- // if the slave is present syncronize with it
-
+ // if the slave is present synchronize with it
uint8_t checksum = 0;
// send data to the slave
- serial_write_byte(sstd_index); // first chunk is transaction id
+ serial_write_byte(sstd_index); // first chunk is transaction id
sync_recv();
for (int i = 0; i < trans->initiator2target_buffer_size; ++i) {
@@ -245,7 +253,7 @@ int soft_serial_transaction(int sstd_index) {
sync_recv();
serial_delay();
- serial_delay(); // read mid pulses
+ serial_delay(); // read mid pulses
// receive data from the slave
uint8_t checksum_computed = 0;
@@ -266,7 +274,7 @@ int soft_serial_transaction(int sstd_index) {
serial_high();
chSysUnlock();
- return TRANSACTION_DATA_ERROR;
+ return false;
}
// always, release the line when not in use
@@ -274,5 +282,18 @@ int soft_serial_transaction(int sstd_index) {
serial_output();
chSysUnlock();
- return TRANSACTION_END;
+ return true;
+}
+
+/////////
+// start transaction by initiator
+//
+// bool soft_serial_transaction(int sstd_index)
+//
+// this code is very time dependent, so we need to disable interrupts
+bool soft_serial_transaction(int sstd_index) {
+ split_shared_memory_lock();
+ bool result = initiate_transaction((uint8_t)sstd_index);
+ split_shared_memory_unlock();
+ return result;
}
diff --git a/platforms/chibios/drivers/serial_usart.c b/platforms/chibios/drivers/serial_usart.c
index ea4473791c..e9fa4af7a3 100644
--- a/platforms/chibios/drivers/serial_usart.c
+++ b/platforms/chibios/drivers/serial_usart.c
@@ -15,6 +15,7 @@
*/
#include "serial_usart.h"
+#include "synchronization_util.h"
#if defined(SERIAL_USART_CONFIG)
static SerialConfig serial_config = SERIAL_USART_CONFIG;
@@ -36,7 +37,7 @@ static SerialDriver* serial_driver = &SERIAL_USART_DRIVER;
static inline bool react_to_transactions(void);
static inline bool __attribute__((nonnull)) receive(uint8_t* destination, const size_t size);
static inline bool __attribute__((nonnull)) send(const uint8_t* source, const size_t size);
-static inline int initiate_transaction(uint8_t sstd_index);
+static inline bool initiate_transaction(uint8_t sstd_index);
static inline void usart_clear(void);
/**
@@ -104,9 +105,9 @@ static inline bool receive(uint8_t* destination, const size_t size) {
__attribute__((weak)) void usart_init(void) {
# if defined(MCU_STM32)
# if defined(USE_GPIOV1)
- palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_STM32_ALTERNATE_OPENDRAIN);
+ palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE_OPENDRAIN);
# else
- palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_TX_PAL_MODE) | PAL_STM32_OTYPE_OPENDRAIN);
+ palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_TX_PAL_MODE) | PAL_OUTPUT_TYPE_OPENDRAIN);
# endif
# if defined(USART_REMAP)
@@ -125,11 +126,11 @@ __attribute__((weak)) void usart_init(void) {
__attribute__((weak)) void usart_init(void) {
# if defined(MCU_STM32)
# if defined(USE_GPIOV1)
- palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_STM32_ALTERNATE_PUSHPULL);
+ palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE_PUSHPULL);
palSetLineMode(SERIAL_USART_RX_PIN, PAL_MODE_INPUT);
# else
- palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_TX_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_HIGHEST);
- palSetLineMode(SERIAL_USART_RX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_RX_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_HIGHEST);
+ palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_TX_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL | PAL_OUTPUT_SPEED_HIGHEST);
+ palSetLineMode(SERIAL_USART_RX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_RX_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL | PAL_OUTPUT_SPEED_HIGHEST);
# endif
# if defined(USART_REMAP)
@@ -173,6 +174,7 @@ static THD_FUNCTION(SlaveThread, arg) {
* Parts of failed transactions or spurious bytes could still be in it. */
usart_clear();
}
+ split_shared_memory_unlock();
}
}
@@ -200,20 +202,19 @@ static inline bool react_to_transactions(void) {
return false;
}
+ split_shared_memory_lock();
split_transaction_desc_t* trans = &split_transaction_table[sstd_index];
/* Send back the handshake which is XORed as a simple checksum,
to signal that the slave is ready to receive possible transaction buffers */
sstd_index ^= HANDSHAKE_MAGIC;
if (!send(&sstd_index, sizeof(sstd_index))) {
- *trans->status = TRANSACTION_DATA_ERROR;
return false;
}
/* Receive transaction buffer from the master. If this transaction requires it.*/
if (trans->initiator2target_buffer_size) {
if (!receive(split_trans_initiator2target_buffer(trans), trans->initiator2target_buffer_size)) {
- *trans->status = TRANSACTION_DATA_ERROR;
return false;
}
}
@@ -226,12 +227,10 @@ static inline bool react_to_transactions(void) {
/* Send transaction buffer to the master. If this transaction requires it. */
if (trans->target2initiator_buffer_size) {
if (!send(split_trans_target2initiator_buffer(trans), trans->target2initiator_buffer_size)) {
- *trans->status = TRANSACTION_DATA_ERROR;
return false;
}
}
- *trans->status = TRANSACTION_ACCEPTED;
return true;
}
@@ -242,7 +241,7 @@ void soft_serial_initiator_init(void) {
usart_master_init(&serial_driver);
#if defined(MCU_STM32) && defined(SERIAL_USART_PIN_SWAP)
- serial_config.cr2 |= USART_CR2_SWAP; // master has swapped TX/RX pins
+ serial_config.cr2 |= USART_CR2_SWAP; // master has swapped TX/RX pins
#endif
sdStart(serial_driver, &serial_config);
@@ -252,39 +251,36 @@ void soft_serial_initiator_init(void) {
* @brief Start transaction from the master half to the slave half.
*
* @param index Transaction Table index of the transaction to start.
- * @return int TRANSACTION_NO_RESPONSE in case of Timeout.
- * TRANSACTION_TYPE_ERROR in case of invalid transaction index.
- * TRANSACTION_END in case of success.
+ * @return bool Indicates success of transaction.
*/
-int soft_serial_transaction(int index) {
+bool soft_serial_transaction(int index) {
/* Clear the receive queue, to start with a clean slate.
* Parts of failed transactions or spurious bytes could still be in it. */
usart_clear();
- return initiate_transaction((uint8_t)index);
+
+ split_shared_memory_lock();
+ bool result = initiate_transaction((uint8_t)index);
+ split_shared_memory_unlock();
+
+ return result;
}
/**
* @brief Initiate transaction to slave half.
*/
-static inline int initiate_transaction(uint8_t sstd_index) {
+static inline bool initiate_transaction(uint8_t sstd_index) {
/* Sanity check that we are actually starting a valid transaction. */
if (sstd_index >= NUM_TOTAL_TRANSACTIONS) {
dprintln("USART: Illegal transaction Id.");
- return TRANSACTION_TYPE_ERROR;
+ return false;
}
split_transaction_desc_t* trans = &split_transaction_table[sstd_index];
- /* Transaction is not registered. Abort. */
- if (!trans->status) {
- dprintln("USART: Transaction not registered.");
- return TRANSACTION_TYPE_ERROR;
- }
-
/* Send transaction table index to the slave, which doubles as basic handshake token. */
if (!send(&sstd_index, sizeof(sstd_index))) {
dprintln("USART: Send Handshake failed.");
- return TRANSACTION_TYPE_ERROR;
+ return false;
}
uint8_t sstd_index_shake = 0xFF;
@@ -295,14 +291,14 @@ static inline int initiate_transaction(uint8_t sstd_index) {
*/
if (!receive(&sstd_index_shake, sizeof(sstd_index_shake)) || (sstd_index_shake != (sstd_index ^ HANDSHAKE_MAGIC))) {
dprintln("USART: Handshake failed.");
- return TRANSACTION_NO_RESPONSE;
+ return false;
}
/* Send transaction buffer to the slave. If this transaction requires it. */
if (trans->initiator2target_buffer_size) {
if (!send(split_trans_initiator2target_buffer(trans), trans->initiator2target_buffer_size)) {
dprintln("USART: Send failed.");
- return TRANSACTION_NO_RESPONSE;
+ return false;
}
}
@@ -310,9 +306,9 @@ static inline int initiate_transaction(uint8_t sstd_index) {
if (trans->target2initiator_buffer_size) {
if (!receive(split_trans_target2initiator_buffer(trans), trans->target2initiator_buffer_size)) {
dprintln("USART: Receive failed.");
- return TRANSACTION_NO_RESPONSE;
+ return false;
}
}
- return TRANSACTION_END;
+ return true;
}
diff --git a/platforms/chibios/drivers/serial_usart.h b/platforms/chibios/drivers/serial_usart.h
index 7b135b31e0..81fe9e0113 100644
--- a/platforms/chibios/drivers/serial_usart.h
+++ b/platforms/chibios/drivers/serial_usart.h
@@ -50,15 +50,15 @@
#endif
#if !defined(USART_CR1_M0)
-# define USART_CR1_M0 USART_CR1_M // some platforms (f1xx) dont have this so
+# define USART_CR1_M0 USART_CR1_M // some platforms (f1xx) dont have this so
#endif
#if !defined(SERIAL_USART_CR1)
-# define SERIAL_USART_CR1 (USART_CR1_PCE | USART_CR1_PS | USART_CR1_M0) // parity enable, odd parity, 9 bit length
+# define SERIAL_USART_CR1 (USART_CR1_PCE | USART_CR1_PS | USART_CR1_M0) // parity enable, odd parity, 9 bit length
#endif
#if !defined(SERIAL_USART_CR2)
-# define SERIAL_USART_CR2 (USART_CR2_STOP_1) // 2 stop bits
+# define SERIAL_USART_CR2 (USART_CR2_STOP_1) // 2 stop bits
#endif
#if !defined(SERIAL_USART_CR3)
diff --git a/platforms/chibios/drivers/spi_master.c b/platforms/chibios/drivers/spi_master.c
index 28ddcbb2ba..ce69e7f0ac 100644
--- a/platforms/chibios/drivers/spi_master.c
+++ b/platforms/chibios/drivers/spi_master.c
@@ -42,9 +42,9 @@ __attribute__((weak)) void spi_init(void) {
palSetPadMode(PAL_PORT(SPI_MOSI_PIN), PAL_PAD(SPI_MOSI_PIN), SPI_MOSI_PAL_MODE);
palSetPadMode(PAL_PORT(SPI_MISO_PIN), PAL_PAD(SPI_MISO_PIN), SPI_MISO_PAL_MODE);
#else
- palSetPadMode(PAL_PORT(SPI_SCK_PIN), PAL_PAD(SPI_SCK_PIN), PAL_MODE_ALTERNATE(SPI_SCK_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_HIGHEST);
- palSetPadMode(PAL_PORT(SPI_MOSI_PIN), PAL_PAD(SPI_MOSI_PIN), PAL_MODE_ALTERNATE(SPI_MOSI_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_HIGHEST);
- palSetPadMode(PAL_PORT(SPI_MISO_PIN), PAL_PAD(SPI_MISO_PIN), PAL_MODE_ALTERNATE(SPI_MISO_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_HIGHEST);
+ palSetPadMode(PAL_PORT(SPI_SCK_PIN), PAL_PAD(SPI_SCK_PIN), PAL_MODE_ALTERNATE(SPI_SCK_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL | PAL_OUTPUT_SPEED_HIGHEST);
+ palSetPadMode(PAL_PORT(SPI_MOSI_PIN), PAL_PAD(SPI_MOSI_PIN), PAL_MODE_ALTERNATE(SPI_MOSI_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL | PAL_OUTPUT_SPEED_HIGHEST);
+ palSetPadMode(PAL_PORT(SPI_MISO_PIN), PAL_PAD(SPI_MISO_PIN), PAL_MODE_ALTERNATE(SPI_MISO_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL | PAL_OUTPUT_SPEED_HIGHEST);
#endif
}
}
@@ -54,6 +54,7 @@ bool spi_start(pin_t slavePin, bool lsbFirst, uint8_t mode, uint16_t divisor) {
return false;
}
+#if !(defined(WB32F3G71xx) || defined(WB32FQ95xx))
uint16_t roundedDivisor = 2;
while (roundedDivisor < divisor) {
roundedDivisor <<= 1;
@@ -62,6 +63,7 @@ bool spi_start(pin_t slavePin, bool lsbFirst, uint8_t mode, uint16_t divisor) {
if (roundedDivisor < 2 || roundedDivisor > 256) {
return false;
}
+#endif
#if defined(K20x) || defined(KL2x)
spiConfig.tar0 = SPIx_CTARn_FMSZ(7) | SPIx_CTARn_ASC(1);
@@ -110,6 +112,62 @@ bool spi_start(pin_t slavePin, bool lsbFirst, uint8_t mode, uint16_t divisor) {
spiConfig.tar0 |= SPIx_CTARn_BR(8);
break;
}
+
+#elif defined(HT32)
+ spiConfig.cr0 = SPI_CR0_SELOEN;
+ spiConfig.cr1 = SPI_CR1_MODE | 8; // 8 bits and in master mode
+
+ if (lsbFirst) {
+ spiConfig.cr1 |= SPI_CR1_FIRSTBIT;
+ }
+
+ switch (mode) {
+ case 0:
+ spiConfig.cr1 |= SPI_CR1_FORMAT_MODE0;
+ break;
+ case 1:
+ spiConfig.cr1 |= SPI_CR1_FORMAT_MODE1;
+ break;
+ case 2:
+ spiConfig.cr1 |= SPI_CR1_FORMAT_MODE2;
+ break;
+ case 3:
+ spiConfig.cr1 |= SPI_CR1_FORMAT_MODE3;
+ break;
+ }
+
+ spiConfig.cpr = (roundedDivisor - 1) >> 1;
+
+#elif defined(WB32F3G71xx) || defined(WB32FQ95xx)
+ if (!lsbFirst) {
+ osalDbgAssert(lsbFirst != FALSE, "unsupported lsbFirst");
+ }
+
+ if (divisor < 1) {
+ return false;
+ }
+
+ spiConfig.SPI_BaudRatePrescaler = (divisor << 2);
+
+ switch (mode) {
+ case 0:
+ spiConfig.SPI_CPHA = SPI_CPHA_1Edge;
+ spiConfig.SPI_CPOL = SPI_CPOL_Low;
+ break;
+ case 1:
+ spiConfig.SPI_CPHA = SPI_CPHA_2Edge;
+ spiConfig.SPI_CPOL = SPI_CPOL_Low;
+ break;
+ case 2:
+ spiConfig.SPI_CPHA = SPI_CPHA_1Edge;
+ spiConfig.SPI_CPOL = SPI_CPOL_High;
+ break;
+ case 3:
+ spiConfig.SPI_CPHA = SPI_CPHA_2Edge;
+ spiConfig.SPI_CPOL = SPI_CPOL_High;
+ break;
+ }
+
#else
spiConfig.cr1 = 0;
diff --git a/platforms/chibios/drivers/spi_master.h b/platforms/chibios/drivers/spi_master.h
index b5a6ef1437..6a3ce481f1 100644
--- a/platforms/chibios/drivers/spi_master.h
+++ b/platforms/chibios/drivers/spi_master.h
@@ -33,7 +33,7 @@
#ifndef SPI_SCK_PAL_MODE
# if defined(USE_GPIOV1)
-# define SPI_SCK_PAL_MODE PAL_MODE_STM32_ALTERNATE_PUSHPULL
+# define SPI_SCK_PAL_MODE PAL_MODE_ALTERNATE_PUSHPULL
# else
# define SPI_SCK_PAL_MODE 5
# endif
@@ -45,7 +45,7 @@
#ifndef SPI_MOSI_PAL_MODE
# if defined(USE_GPIOV1)
-# define SPI_MOSI_PAL_MODE PAL_MODE_STM32_ALTERNATE_PUSHPULL
+# define SPI_MOSI_PAL_MODE PAL_MODE_ALTERNATE_PUSHPULL
# else
# define SPI_MOSI_PAL_MODE 5
# endif
@@ -57,7 +57,7 @@
#ifndef SPI_MISO_PAL_MODE
# if defined(USE_GPIOV1)
-# define SPI_MISO_PAL_MODE PAL_MODE_STM32_ALTERNATE_PUSHPULL
+# define SPI_MISO_PAL_MODE PAL_MODE_ALTERNATE_PUSHPULL
# else
# define SPI_MISO_PAL_MODE 5
# endif
diff --git a/platforms/chibios/drivers/uart.c b/platforms/chibios/drivers/uart.c
index 030335b342..396803f33b 100644
--- a/platforms/chibios/drivers/uart.c
+++ b/platforms/chibios/drivers/uart.c
@@ -18,7 +18,11 @@
#include "quantum.h"
+#if defined(WB32F3G71xx) || defined(WB32FQ95xx)
+static SerialConfig serialConfig = {SERIAL_DEFAULT_BITRATE, SD1_WRDLEN, SD1_STPBIT, SD1_PARITY, SD1_ATFLCT};
+#else
static SerialConfig serialConfig = {SERIAL_DEFAULT_BITRATE, SD1_CR1, SD1_CR2, SD1_CR3};
+#endif
void uart_init(uint32_t baud) {
static bool is_initialised = false;
@@ -29,22 +33,34 @@ void uart_init(uint32_t baud) {
serialConfig.speed = baud;
#if defined(USE_GPIOV1)
- palSetLineMode(SD1_TX_PIN, PAL_MODE_STM32_ALTERNATE_OPENDRAIN);
- palSetLineMode(SD1_RX_PIN, PAL_MODE_STM32_ALTERNATE_OPENDRAIN);
+ palSetLineMode(SD1_TX_PIN, PAL_MODE_ALTERNATE_OPENDRAIN);
+ palSetLineMode(SD1_RX_PIN, PAL_MODE_ALTERNATE_OPENDRAIN);
#else
- palSetLineMode(SD1_TX_PIN, PAL_MODE_ALTERNATE(SD1_TX_PAL_MODE) | PAL_STM32_OTYPE_OPENDRAIN);
- palSetLineMode(SD1_RX_PIN, PAL_MODE_ALTERNATE(SD1_RX_PAL_MODE) | PAL_STM32_OTYPE_OPENDRAIN);
+ palSetLineMode(SD1_TX_PIN, PAL_MODE_ALTERNATE(SD1_TX_PAL_MODE) | PAL_OUTPUT_TYPE_OPENDRAIN);
+ palSetLineMode(SD1_RX_PIN, PAL_MODE_ALTERNATE(SD1_RX_PAL_MODE) | PAL_OUTPUT_TYPE_OPENDRAIN);
#endif
sdStart(&SERIAL_DRIVER, &serialConfig);
}
}
-void uart_putchar(uint8_t c) { sdPut(&SERIAL_DRIVER, c); }
+void uart_write(uint8_t data) {
+ sdPut(&SERIAL_DRIVER, data);
+}
-uint8_t uart_getchar(void) {
+uint8_t uart_read(void) {
msg_t res = sdGet(&SERIAL_DRIVER);
return (uint8_t)res;
}
-bool uart_available(void) { return !sdGetWouldBlock(&SERIAL_DRIVER); }
+void uart_transmit(const uint8_t *data, uint16_t length) {
+ sdWrite(&SERIAL_DRIVER, data, length);
+}
+
+void uart_receive(uint8_t *data, uint16_t length) {
+ sdRead(&SERIAL_DRIVER, data, length);
+}
+
+bool uart_available(void) {
+ return !sdGetWouldBlock(&SERIAL_DRIVER);
+}
diff --git a/platforms/chibios/drivers/uart.h b/platforms/chibios/drivers/uart.h
index b4e20e9fd3..603d51037b 100644
--- a/platforms/chibios/drivers/uart.h
+++ b/platforms/chibios/drivers/uart.h
@@ -68,10 +68,30 @@
# define SD1_CR3 0
#endif
+#ifndef SD1_WRDLEN
+# define SD1_WRDLEN 3
+#endif
+
+#ifndef SD1_STPBIT
+# define SD1_STPBIT 0
+#endif
+
+#ifndef SD1_PARITY
+# define SD1_PARITY 0
+#endif
+
+#ifndef SD1_ATFLCT
+# define SD1_ATFLCT 0
+#endif
+
void uart_init(uint32_t baud);
-void uart_putchar(uint8_t c);
+void uart_write(uint8_t data);
+
+uint8_t uart_read(void);
+
+void uart_transmit(const uint8_t *data, uint16_t length);
-uint8_t uart_getchar(void);
+void uart_receive(uint8_t *data, uint16_t length);
bool uart_available(void);
diff --git a/platforms/chibios/drivers/usbpd_stm32g4.c b/platforms/chibios/drivers/usbpd_stm32g4.c
index f16ca8aeae..0096f22f07 100644
--- a/platforms/chibios/drivers/usbpd_stm32g4.c
+++ b/platforms/chibios/drivers/usbpd_stm32g4.c
@@ -18,7 +18,7 @@
#ifndef USBPD_UCPD1_CFG1
# define USBPD_UCPD1_CFG1 (UCPD_CFG1_PSC_UCPDCLK_0 | UCPD_CFG1_TRANSWIN_3 | UCPD_CFG1_IFRGAP_4 | UCPD_CFG1_HBITCLKDIV_4)
-#endif // USBPD_UCPD1_CFG1
+#endif // USBPD_UCPD1_CFG1
// Initialises the USBPD subsystem
__attribute__((weak)) void usbpd_init(void) {
@@ -64,7 +64,7 @@ __attribute__((weak)) usbpd_allowance_t usbpd_get_allowance(void) {
switch (vstate_max) {
case 0:
case 1:
- return USBPD_500MA; // Note that this is 500mA (i.e. max USB 2.0), not 900mA, as we're not using USB 3.1 as a sink device.
+ return USBPD_500MA; // Note that this is 500mA (i.e. max USB 2.0), not 900mA, as we're not using USB 3.1 as a sink device.
case 2:
return USBPD_1500MA;
case 3:
diff --git a/platforms/chibios/drivers/ws2812.c b/platforms/chibios/drivers/ws2812.c
index 0d12e2fb79..1b3bb59842 100644
--- a/platforms/chibios/drivers/ws2812.c
+++ b/platforms/chibios/drivers/ws2812.c
@@ -6,11 +6,11 @@
/* Adapted from https://github.com/bigjosh/SimpleNeoPixelDemo/ */
#ifndef NOP_FUDGE
-# if defined(STM32F0XX) || defined(STM32F1XX) || defined(STM32F3XX) || defined(STM32F4XX) || defined(STM32L0XX)
+# if defined(STM32F0XX) || defined(STM32F1XX) || defined(GD32VF103) || defined(STM32F3XX) || defined(STM32F4XX) || defined(STM32L0XX)
# define NOP_FUDGE 0.4
# else
# error("NOP_FUDGE configuration required")
-# define NOP_FUDGE 1 // this just pleases the compile so the above error is easier to spot
+# define NOP_FUDGE 1 // this just pleases the compile so the above error is easier to spot
# endif
#endif
@@ -22,9 +22,15 @@
# define WS2812_OUTPUT_MODE PAL_MODE_OUTPUT_OPENDRAIN
#endif
+// The reset gap can be 6000 ns, but depending on the LED strip it may have to be increased
+// to values like 600000 ns. If it is too small, the pixels will show nothing most of the time.
+#ifndef WS2812_RES
+# define WS2812_RES (1000 * WS2812_TRST_US) // Width of the low gap between bits to cause a frame to latch
+#endif
+
#define NUMBER_NOPS 6
-#define CYCLES_PER_SEC (STM32_SYSCLK / NUMBER_NOPS * NOP_FUDGE)
-#define NS_PER_SEC (1000000000L) // Note that this has to be SIGNED since we want to be able to check for negative values of derivatives
+#define CYCLES_PER_SEC (CPU_CLOCK / NUMBER_NOPS * NOP_FUDGE)
+#define NS_PER_SEC (1000000000L) // Note that this has to be SIGNED since we want to be able to check for negative values of derivatives
#define NS_PER_CYCLE (NS_PER_SEC / CYCLES_PER_SEC)
#define NS_TO_CYCLES(n) ((n) / NS_PER_CYCLE)
@@ -40,19 +46,6 @@
} \
} while (0)
-// These are the timing constraints taken mostly from the WS2812 datasheets
-// These are chosen to be conservative and avoid problems rather than for maximum throughput
-
-#define T1H 900 // Width of a 1 bit in ns
-#define T1L (1250 - T1H) // Width of a 1 bit in ns
-
-#define T0H 350 // Width of a 0 bit in ns
-#define T0L (1250 - T0H) // Width of a 0 bit in ns
-
-// The reset gap can be 6000 ns, but depending on the LED strip it may have to be increased
-// to values like 600000 ns. If it is too small, the pixels will show nothing most of the time.
-#define RES (1000 * WS2812_TRST_US) // Width of the low gap between bits to cause a frame to latch
-
void sendByte(uint8_t byte) {
// WS2812 protocol wants most significant bits first
for (unsigned char bit = 0; bit < 8; bit++) {
@@ -61,20 +54,22 @@ void sendByte(uint8_t byte) {
if (is_one) {
// 1
writePinHigh(RGB_DI_PIN);
- wait_ns(T1H);
+ wait_ns(WS2812_T1H);
writePinLow(RGB_DI_PIN);
- wait_ns(T1L);
+ wait_ns(WS2812_T1L);
} else {
// 0
writePinHigh(RGB_DI_PIN);
- wait_ns(T0H);
+ wait_ns(WS2812_T0H);
writePinLow(RGB_DI_PIN);
- wait_ns(T0L);
+ wait_ns(WS2812_T0L);
}
}
}
-void ws2812_init(void) { palSetLineMode(RGB_DI_PIN, WS2812_OUTPUT_MODE); }
+void ws2812_init(void) {
+ palSetLineMode(RGB_DI_PIN, WS2812_OUTPUT_MODE);
+}
// Setleds for standard RGB
void ws2812_setleds(LED_TYPE *ledarray, uint16_t leds) {
@@ -108,7 +103,7 @@ void ws2812_setleds(LED_TYPE *ledarray, uint16_t leds) {
#endif
}
- wait_ns(RES);
+ wait_ns(WS2812_RES);
chSysUnlock();
}
diff --git a/platforms/chibios/drivers/ws2812_pwm.c b/platforms/chibios/drivers/ws2812_pwm.c
index e6af55b6b3..57187676d7 100644
--- a/platforms/chibios/drivers/ws2812_pwm.c
+++ b/platforms/chibios/drivers/ws2812_pwm.c
@@ -5,23 +5,25 @@
/* Adapted from https://github.com/joewa/WS2812-LED-Driver_ChibiOS/ */
#ifdef RGBW
-# error "RGBW not supported"
+# define WS2812_CHANNELS 4
+#else
+# define WS2812_CHANNELS 3
#endif
#ifndef WS2812_PWM_DRIVER
-# define WS2812_PWM_DRIVER PWMD2 // TIMx
+# define WS2812_PWM_DRIVER PWMD2 // TIMx
#endif
#ifndef WS2812_PWM_CHANNEL
-# define WS2812_PWM_CHANNEL 2 // Channel
+# define WS2812_PWM_CHANNEL 2 // Channel
#endif
#ifndef WS2812_PWM_PAL_MODE
-# define WS2812_PWM_PAL_MODE 2 // DI Pin's alternate function value
+# define WS2812_PWM_PAL_MODE 2 // DI Pin's alternate function value
#endif
#ifndef WS2812_DMA_STREAM
-# define WS2812_DMA_STREAM STM32_DMA1_STREAM2 // DMA Stream for TIMx_UP
+# define WS2812_DMA_STREAM STM32_DMA1_STREAM2 // DMA Stream for TIMx_UP
#endif
#ifndef WS2812_DMA_CHANNEL
-# define WS2812_DMA_CHANNEL 2 // DMA Channel for TIMx_UP
+# define WS2812_DMA_CHANNEL 2 // DMA Channel for TIMx_UP
#endif
#if (STM32_DMA_SUPPORTS_DMAMUX == TRUE) && !defined(WS2812_DMAMUX_ID)
# error "please consult your MCU's datasheet and specify in your config.h: #define WS2812_DMAMUX_ID STM32_DMAMUX1_TIM?_UP"
@@ -40,26 +42,26 @@
// Default Push Pull
#ifndef WS2812_EXTERNAL_PULLUP
# if defined(USE_GPIOV1)
-# define WS2812_OUTPUT_MODE PAL_MODE_STM32_ALTERNATE_PUSHPULL
+# define WS2812_OUTPUT_MODE PAL_MODE_ALTERNATE_PUSHPULL
# else
-# define WS2812_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_PWM_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_HIGHEST | PAL_STM32_PUPDR_FLOATING
+# define WS2812_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_PWM_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL | PAL_OUTPUT_SPEED_HIGHEST | PAL_PUPDR_FLOATING
# endif
#else
# if defined(USE_GPIOV1)
-# define WS2812_OUTPUT_MODE PAL_MODE_STM32_ALTERNATE_OPENDRAIN
+# define WS2812_OUTPUT_MODE PAL_MODE_ALTERNATE_OPENDRAIN
# else
-# define WS2812_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_PWM_PAL_MODE) | PAL_STM32_OTYPE_OPENDRAIN | PAL_STM32_OSPEED_HIGHEST | PAL_STM32_PUPDR_FLOATING
+# define WS2812_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_PWM_PAL_MODE) | PAL_OUTPUT_TYPE_OPENDRAIN | PAL_OUTPUT_SPEED_HIGHEST | PAL_PUPDR_FLOATING
# endif
#endif
#ifndef WS2812_PWM_TARGET_PERIOD
//# define WS2812_PWM_TARGET_PERIOD 800000 // Original code is 800k...?
-# define WS2812_PWM_TARGET_PERIOD 80000 // TODO: work out why 10x less on f303/f4x1
+# define WS2812_PWM_TARGET_PERIOD 80000 // TODO: work out why 10x less on f303/f4x1
#endif
/* --- PRIVATE CONSTANTS ---------------------------------------------------- */
-#define WS2812_PWM_FREQUENCY (STM32_SYSCLK / 2) /**< Clock frequency of PWM, must be valid with respect to system clock! */
+#define WS2812_PWM_FREQUENCY (CPU_CLOCK / 2) /**< Clock frequency of PWM, must be valid with respect to system clock! */
#define WS2812_PWM_PERIOD (WS2812_PWM_FREQUENCY / WS2812_PWM_TARGET_PERIOD) /**< Clock period in ticks. 1 / 800kHz = 1.25 uS (as per datasheet) */
/**
@@ -68,8 +70,9 @@
* The reset period for each frame is defined in WS2812_TRST_US.
* Calculate the number of zeroes to add at the end assuming 1.25 uS/bit:
*/
-#define WS2812_RESET_BIT_N (1000 * WS2812_TRST_US / 1250)
-#define WS2812_COLOR_BIT_N (RGBLED_NUM * 24) /**< Number of data bits */
+#define WS2812_COLOR_BITS (WS2812_CHANNELS * 8)
+#define WS2812_RESET_BIT_N (1000 * WS2812_TRST_US / WS2812_TIMING)
+#define WS2812_COLOR_BIT_N (RGBLED_NUM * WS2812_COLOR_BITS) /**< Number of data bits */
#define WS2812_BIT_N (WS2812_COLOR_BIT_N + WS2812_RESET_BIT_N) /**< Total number of bits in a frame */
/**
@@ -114,7 +117,7 @@
*
* @return The bit index
*/
-#define WS2812_BIT(led, byte, bit) (24 * (led) + 8 * (byte) + (7 - (bit)))
+#define WS2812_BIT(led, byte, bit) (WS2812_COLOR_BITS * (led) + 8 * (byte) + (7 - (bit)))
#if (WS2812_BYTE_ORDER == WS2812_BYTE_ORDER_GRB)
/**
@@ -228,6 +231,20 @@
# define WS2812_BLUE_BIT(led, bit) WS2812_BIT((led), 0, (bit))
#endif
+#ifdef RGBW
+/**
+ * @brief Determine the index in @ref ws2812_frame_buffer "the frame buffer" of a given white bit
+ *
+ * @note The white byte is the last byte in the color packet
+ *
+ * @param[in] led: The led index [0, @ref WS2812_LED_N)
+ * @param[in] bit: The bit index [0, 7]
+ *
+ * @return The bit index
+ */
+# define WS2812_WHITE_BIT(led, bit) WS2812_BIT((led), 3, (bit))
+#endif
+
/* --- PRIVATE VARIABLES ---------------------------------------------------- */
static uint32_t ws2812_frame_buffer[WS2812_BIT_N + 1]; /**< Buffer for a frame */
@@ -242,8 +259,10 @@ write/read to/from the other buffer).
void ws2812_init(void) {
// Initialize led frame buffer
uint32_t i;
- for (i = 0; i < WS2812_COLOR_BIT_N; i++) ws2812_frame_buffer[i] = WS2812_DUTYCYCLE_0; // All color bits are zero duty cycle
- for (i = 0; i < WS2812_RESET_BIT_N; i++) ws2812_frame_buffer[i + WS2812_COLOR_BIT_N] = 0; // All reset bits are zero
+ for (i = 0; i < WS2812_COLOR_BIT_N; i++)
+ ws2812_frame_buffer[i] = WS2812_DUTYCYCLE_0; // All color bits are zero duty cycle
+ for (i = 0; i < WS2812_RESET_BIT_N; i++)
+ ws2812_frame_buffer[i + WS2812_COLOR_BIT_N] = 0; // All reset bits are zero
palSetLineMode(RGB_DI_PIN, WS2812_OUTPUT_MODE);
@@ -251,22 +270,22 @@ void ws2812_init(void) {
//#pragma GCC diagnostic ignored "-Woverride-init" // Turn off override-init warning for this struct. We use the overriding ability to set a "default" channel config
static const PWMConfig ws2812_pwm_config = {
.frequency = WS2812_PWM_FREQUENCY,
- .period = WS2812_PWM_PERIOD, // Mit dieser Periode wird UDE-Event erzeugt und ein neuer Wert (Länge WS2812_BIT_N) vom DMA ins CCR geschrieben
+ .period = WS2812_PWM_PERIOD, // Mit dieser Periode wird UDE-Event erzeugt und ein neuer Wert (Länge WS2812_BIT_N) vom DMA ins CCR geschrieben
.callback = NULL,
.channels =
{
- [0 ... 3] = {.mode = PWM_OUTPUT_DISABLED, .callback = NULL}, // Channels default to disabled
- [WS2812_PWM_CHANNEL - 1] = {.mode = WS2812_PWM_OUTPUT_MODE, .callback = NULL}, // Turn on the channel we care about
+ [0 ... 3] = {.mode = PWM_OUTPUT_DISABLED, .callback = NULL}, // Channels default to disabled
+ [WS2812_PWM_CHANNEL - 1] = {.mode = WS2812_PWM_OUTPUT_MODE, .callback = NULL}, // Turn on the channel we care about
},
.cr2 = 0,
- .dier = TIM_DIER_UDE, // DMA on update event for next period
+ .dier = TIM_DIER_UDE, // DMA on update event for next period
};
//#pragma GCC diagnostic pop // Restore command-line warning options
// Configure DMA
// dmaInit(); // Joe added this
dmaStreamAlloc(WS2812_DMA_STREAM - STM32_DMA_STREAM(0), 10, NULL, NULL);
- dmaStreamSetPeripheral(WS2812_DMA_STREAM, &(WS2812_PWM_DRIVER.tim->CCR[WS2812_PWM_CHANNEL - 1])); // Ziel ist der An-Zeit im Cap-Comp-Register
+ dmaStreamSetPeripheral(WS2812_DMA_STREAM, &(WS2812_PWM_DRIVER.tim->CCR[WS2812_PWM_CHANNEL - 1])); // Ziel ist der An-Zeit im Cap-Comp-Register
dmaStreamSetMemory0(WS2812_DMA_STREAM, ws2812_frame_buffer);
dmaStreamSetTransactionSize(WS2812_DMA_STREAM, WS2812_BIT_N);
dmaStreamSetMode(WS2812_DMA_STREAM, STM32_DMA_CR_CHSEL(WS2812_DMA_CHANNEL) | STM32_DMA_CR_DIR_M2P | STM32_DMA_CR_PSIZE_WORD | STM32_DMA_CR_MSIZE_WORD | STM32_DMA_CR_MINC | STM32_DMA_CR_CIRC | STM32_DMA_CR_PL(3));
@@ -285,7 +304,7 @@ void ws2812_init(void) {
// ChibiOS driver code, so we don't have to do anything special to the timer. If we did, we'd have to start the timer,
// disable counting, enable the channel, and then make whatever configuration changes we need.
pwmStart(&WS2812_PWM_DRIVER, &ws2812_pwm_config);
- pwmEnableChannel(&WS2812_PWM_DRIVER, WS2812_PWM_CHANNEL - 1, 0); // Initial period is 0; output will be low until first duty cycle is DMA'd in
+ pwmEnableChannel(&WS2812_PWM_DRIVER, WS2812_PWM_CHANNEL - 1, 0); // Initial period is 0; output will be low until first duty cycle is DMA'd in
}
void ws2812_write_led(uint16_t led_number, uint8_t r, uint8_t g, uint8_t b) {
@@ -296,6 +315,17 @@ void ws2812_write_led(uint16_t led_number, uint8_t r, uint8_t g, uint8_t b) {
ws2812_frame_buffer[WS2812_BLUE_BIT(led_number, bit)] = ((b >> bit) & 0x01) ? WS2812_DUTYCYCLE_1 : WS2812_DUTYCYCLE_0;
}
}
+void ws2812_write_led_rgbw(uint16_t led_number, uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
+ // Write color to frame buffer
+ for (uint8_t bit = 0; bit < 8; bit++) {
+ ws2812_frame_buffer[WS2812_RED_BIT(led_number, bit)] = ((r >> bit) & 0x01) ? WS2812_DUTYCYCLE_1 : WS2812_DUTYCYCLE_0;
+ ws2812_frame_buffer[WS2812_GREEN_BIT(led_number, bit)] = ((g >> bit) & 0x01) ? WS2812_DUTYCYCLE_1 : WS2812_DUTYCYCLE_0;
+ ws2812_frame_buffer[WS2812_BLUE_BIT(led_number, bit)] = ((b >> bit) & 0x01) ? WS2812_DUTYCYCLE_1 : WS2812_DUTYCYCLE_0;
+#ifdef RGBW
+ ws2812_frame_buffer[WS2812_WHITE_BIT(led_number, bit)] = ((w >> bit) & 0x01) ? WS2812_DUTYCYCLE_1 : WS2812_DUTYCYCLE_0;
+#endif
+ }
+}
// Setleds for standard RGB
void ws2812_setleds(LED_TYPE* ledarray, uint16_t leds) {
@@ -306,6 +336,10 @@ void ws2812_setleds(LED_TYPE* ledarray, uint16_t leds) {
}
for (uint16_t i = 0; i < leds; i++) {
+#ifdef RGBW
+ ws2812_write_led_rgbw(i, ledarray[i].r, ledarray[i].g, ledarray[i].b, ledarray[i].w);
+#else
ws2812_write_led(i, ledarray[i].r, ledarray[i].g, ledarray[i].b);
+#endif
}
}
diff --git a/platforms/chibios/drivers/ws2812_spi.c b/platforms/chibios/drivers/ws2812_spi.c
index fe14b478ab..01d8148875 100644
--- a/platforms/chibios/drivers/ws2812_spi.c
+++ b/platforms/chibios/drivers/ws2812_spi.c
@@ -3,10 +3,6 @@
/* Adapted from https://github.com/gamazeps/ws2812b-chibios-SPIDMA/ */
-#ifdef RGBW
-# error "RGBW not supported"
-#endif
-
// Define the spi your LEDs are plugged to here
#ifndef WS2812_SPI
# define WS2812_SPI SPID1
@@ -24,15 +20,15 @@
// Default Push Pull
#ifndef WS2812_EXTERNAL_PULLUP
# if defined(USE_GPIOV1)
-# define WS2812_MOSI_OUTPUT_MODE PAL_MODE_STM32_ALTERNATE_PUSHPULL
+# define WS2812_MOSI_OUTPUT_MODE PAL_MODE_ALTERNATE_PUSHPULL
# else
-# define WS2812_MOSI_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_SPI_MOSI_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL
+# define WS2812_MOSI_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_SPI_MOSI_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL
# endif
#else
# if defined(USE_GPIOV1)
-# define WS2812_MOSI_OUTPUT_MODE PAL_MODE_STM32_ALTERNATE_OPENDRAIN
+# define WS2812_MOSI_OUTPUT_MODE PAL_MODE_ALTERNATE_OPENDRAIN
# else
-# define WS2812_MOSI_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_SPI_MOSI_PAL_MODE) | PAL_STM32_OTYPE_OPENDRAIN
+# define WS2812_MOSI_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_SPI_MOSI_PAL_MODE) | PAL_OUTPUT_TYPE_OPENDRAIN
# endif
#endif
@@ -46,7 +42,7 @@
# define WS2812_SPI_DIVISOR_CR1_BR_X (SPI_CR1_BR_0)
#elif WS2812_SPI_DIVISOR == 8
# define WS2812_SPI_DIVISOR_CR1_BR_X (SPI_CR1_BR_1)
-#elif WS2812_SPI_DIVISOR == 16 // same as default
+#elif WS2812_SPI_DIVISOR == 16 // same as default
# define WS2812_SPI_DIVISOR_CR1_BR_X (SPI_CR1_BR_1 | SPI_CR1_BR_0)
#elif WS2812_SPI_DIVISOR == 32
# define WS2812_SPI_DIVISOR_CR1_BR_X (SPI_CR1_BR_2)
@@ -57,27 +53,31 @@
#elif WS2812_SPI_DIVISOR == 256
# define WS2812_SPI_DIVISOR_CR1_BR_X (SPI_CR1_BR_2 | SPI_CR1_BR_1 | SPI_CR1_BR_0)
#else
-# define WS2812_SPI_DIVISOR_CR1_BR_X (SPI_CR1_BR_1 | SPI_CR1_BR_0) // default
+# define WS2812_SPI_DIVISOR_CR1_BR_X (SPI_CR1_BR_1 | SPI_CR1_BR_0) // default
#endif
// Use SPI circular buffer
#ifdef WS2812_SPI_USE_CIRCULAR_BUFFER
-# define WS2812_SPI_BUFFER_MODE 1 // circular buffer
+# define WS2812_SPI_BUFFER_MODE 1 // circular buffer
#else
-# define WS2812_SPI_BUFFER_MODE 0 // normal buffer
+# define WS2812_SPI_BUFFER_MODE 0 // normal buffer
#endif
#if defined(USE_GPIOV1)
-# define WS2812_SCK_OUTPUT_MODE PAL_MODE_STM32_ALTERNATE_PUSHPULL
+# define WS2812_SCK_OUTPUT_MODE PAL_MODE_ALTERNATE_PUSHPULL
#else
-# define WS2812_SCK_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_SPI_SCK_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL
+# define WS2812_SCK_OUTPUT_MODE PAL_MODE_ALTERNATE(WS2812_SPI_SCK_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL
#endif
#define BYTES_FOR_LED_BYTE 4
-#define NB_COLORS 3
-#define BYTES_FOR_LED (BYTES_FOR_LED_BYTE * NB_COLORS)
+#ifdef RGBW
+# define WS2812_CHANNELS 4
+#else
+# define WS2812_CHANNELS 3
+#endif
+#define BYTES_FOR_LED (BYTES_FOR_LED_BYTE * WS2812_CHANNELS)
#define DATA_SIZE (BYTES_FOR_LED * RGBLED_NUM)
-#define RESET_SIZE (1000 * WS2812_TRST_US / (2 * 1250))
+#define RESET_SIZE (1000 * WS2812_TRST_US / (2 * WS2812_TIMING))
#define PREAMBLE_SIZE 4
static uint8_t txbuf[PREAMBLE_SIZE + DATA_SIZE + RESET_SIZE] = {0};
@@ -104,17 +104,30 @@ static void set_led_color_rgb(LED_TYPE color, int pos) {
uint8_t* tx_start = &txbuf[PREAMBLE_SIZE];
#if (WS2812_BYTE_ORDER == WS2812_BYTE_ORDER_GRB)
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + j] = get_protocol_eq(color.g, j);
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE + j] = get_protocol_eq(color.r, j);
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE * 2 + j] = get_protocol_eq(color.b, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + j] = get_protocol_eq(color.g, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE + j] = get_protocol_eq(color.r, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE * 2 + j] = get_protocol_eq(color.b, j);
#elif (WS2812_BYTE_ORDER == WS2812_BYTE_ORDER_RGB)
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + j] = get_protocol_eq(color.r, j);
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE + j] = get_protocol_eq(color.g, j);
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE * 2 + j] = get_protocol_eq(color.b, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + j] = get_protocol_eq(color.r, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE + j] = get_protocol_eq(color.g, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE * 2 + j] = get_protocol_eq(color.b, j);
#elif (WS2812_BYTE_ORDER == WS2812_BYTE_ORDER_BGR)
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + j] = get_protocol_eq(color.b, j);
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE + j] = get_protocol_eq(color.g, j);
- for (int j = 0; j < 4; j++) tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE * 2 + j] = get_protocol_eq(color.r, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + j] = get_protocol_eq(color.b, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE + j] = get_protocol_eq(color.g, j);
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE * 2 + j] = get_protocol_eq(color.r, j);
+#endif
+#ifdef RGBW
+ for (int j = 0; j < 4; j++)
+ tx_start[BYTES_FOR_LED * pos + BYTES_FOR_LED_BYTE * 4 + j] = get_protocol_eq(color.w, j);
#endif
}
@@ -123,10 +136,36 @@ void ws2812_init(void) {
#ifdef WS2812_SPI_SCK_PIN
palSetLineMode(WS2812_SPI_SCK_PIN, WS2812_SCK_OUTPUT_MODE);
-#endif // WS2812_SPI_SCK_PIN
+#endif // WS2812_SPI_SCK_PIN
// TODO: more dynamic baudrate
- static const SPIConfig spicfg = {WS2812_SPI_BUFFER_MODE, NULL, PAL_PORT(RGB_DI_PIN), PAL_PAD(RGB_DI_PIN), WS2812_SPI_DIVISOR_CR1_BR_X};
+ static const SPIConfig spicfg = {
+#ifndef HAL_LLD_SELECT_SPI_V2
+// HAL_SPI_V1
+# if SPI_SUPPORTS_CIRCULAR == TRUE
+ WS2812_SPI_BUFFER_MODE,
+# endif
+ NULL, // end_cb
+ PAL_PORT(RGB_DI_PIN),
+ PAL_PAD(RGB_DI_PIN),
+ WS2812_SPI_DIVISOR_CR1_BR_X,
+ 0
+#else
+ // HAL_SPI_V2
+# if SPI_SUPPORTS_CIRCULAR == TRUE
+ WS2812_SPI_BUFFER_MODE,
+# endif
+# if SPI_SUPPORTS_SLAVE_MODE == TRUE
+ false,
+# endif
+ NULL, // data_cb
+ NULL, // error_cb
+ PAL_PORT(RGB_DI_PIN),
+ PAL_PAD(RGB_DI_PIN),
+ WS2812_SPI_DIVISOR_CR1_BR_X,
+ 0
+#endif
+ };
spiAcquireBus(&WS2812_SPI); /* Acquire ownership of the bus. */
spiStart(&WS2812_SPI, &spicfg); /* Setup transfer parameters. */