aboutsummaryrefslogtreecommitdiff
path: root/examples/stm32l0
diff options
context:
space:
mode:
authormichel <[email protected]>2024-08-07 21:58:49 +0200
committermichel <[email protected]>2024-11-29 17:58:33 +0100
commit721c6820d4a6e3bbf2546997205a32975e6bad8b (patch)
treef725e1f66b0b7f40a3b663f355c2b1d5d389af06 /examples/stm32l0
parent1a1d5c4689a8b6c57ebb74e99fdea8df39adb037 (diff)
STM32-TSC: enable discriminating between pins within same TSC group and improve TSC library in general
Diffstat (limited to 'examples/stm32l0')
-rw-r--r--examples/stm32l0/.cargo/config.toml2
-rw-r--r--examples/stm32l0/Cargo.toml2
-rw-r--r--examples/stm32l0/README.md24
-rw-r--r--examples/stm32l0/src/bin/async-tsc.rs122
-rw-r--r--examples/stm32l0/src/bin/blocking-tsc.rs116
-rw-r--r--examples/stm32l0/src/bin/tsc_async.rs116
-rw-r--r--examples/stm32l0/src/bin/tsc_blocking.rs142
-rw-r--r--examples/stm32l0/src/bin/tsc_multipin.rs233
8 files changed, 517 insertions, 240 deletions
diff --git a/examples/stm32l0/.cargo/config.toml b/examples/stm32l0/.cargo/config.toml
index b050334b2..fed9cf9ce 100644
--- a/examples/stm32l0/.cargo/config.toml
+++ b/examples/stm32l0/.cargo/config.toml
@@ -1,6 +1,6 @@
1[target.'cfg(all(target_arch = "arm", target_os = "none"))'] 1[target.'cfg(all(target_arch = "arm", target_os = "none"))']
2# replace your chip as listed in `probe-rs chip list` 2# replace your chip as listed in `probe-rs chip list`
3runner = "probe-rs run --chip STM32L053R8Tx" 3runner = "probe-rs run --chip STM32L073RZTx"
4 4
5[build] 5[build]
6target = "thumbv6m-none-eabi" 6target = "thumbv6m-none-eabi"
diff --git a/examples/stm32l0/Cargo.toml b/examples/stm32l0/Cargo.toml
index 95e215b6f..9d234804a 100644
--- a/examples/stm32l0/Cargo.toml
+++ b/examples/stm32l0/Cargo.toml
@@ -6,7 +6,7 @@ license = "MIT OR Apache-2.0"
6 6
7[dependencies] 7[dependencies]
8# Change stm32l072cz to your chip name, if necessary. 8# Change stm32l072cz to your chip name, if necessary.
9embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32l072cz", "unstable-pac", "time-driver-any", "exti", "memory-x"] } 9embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32l073rz", "unstable-pac", "time-driver-any", "exti", "memory-x"] }
10embassy-sync = { version = "0.6.1", path = "../../embassy-sync", features = ["defmt"] } 10embassy-sync = { version = "0.6.1", path = "../../embassy-sync", features = ["defmt"] }
11embassy-executor = { version = "0.6.3", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } 11embassy-executor = { version = "0.6.3", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] }
12embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } 12embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }
diff --git a/examples/stm32l0/README.md b/examples/stm32l0/README.md
new file mode 100644
index 000000000..82d222027
--- /dev/null
+++ b/examples/stm32l0/README.md
@@ -0,0 +1,24 @@
1# Examples for STM32L0 family
2Run individual examples with
3```
4cargo run --bin <module-name>
5```
6for example
7```
8cargo run --bin blinky
9```
10
11## Checklist before running examples
12You might need to adjust `.cargo/config.toml`, `Cargo.toml` and possibly update pin numbers or peripherals to match the specific MCU or board you are using.
13
14* [ ] Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for L073RZ it should be `probe-rs run --chip STM32L073RZTx`. (use `probe-rs chip list` to find your chip)
15* [ ] Update Cargo.toml to have the correct `embassy-stm32` feature. For example for L073RZ it should be `stm32l073rz`. Look in the `Cargo.toml` file of the `embassy-stm32` project to find the correct feature flag for your chip.
16* [ ] If your board has a special clock or power configuration, make sure that it is set up appropriately.
17* [ ] If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic
18
19If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:
20
21* Which example you are trying to run
22* Which chip and board you are using
23
24Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org
diff --git a/examples/stm32l0/src/bin/async-tsc.rs b/examples/stm32l0/src/bin/async-tsc.rs
deleted file mode 100644
index c40b86af9..000000000
--- a/examples/stm32l0/src/bin/async-tsc.rs
+++ /dev/null
@@ -1,122 +0,0 @@
1// Example of async TSC (Touch Sensing Controller) that lights an LED when touch is detected.
2//
3// Suggested physical setup on STM32L073RZ Nucleo board:
4// - Connect a 1000pF capacitor between pin A0 and GND. This is your sampling capacitor.
5// - Connect one end of a 1K resistor to pin A1 and leave the other end loose.
6// The loose end will act as touch sensor which will register your touch.
7//
8// Troubleshooting the setup:
9// - If no touch seems to be registered, then try to disconnect the sampling capacitor from GND momentarily,
10// now the led should light up. Next try using a different value for the sampling capacitor.
11// Also experiment with increasing the values for `ct_pulse_high_length`, `ct_pulse_low_length`, `pulse_generator_prescaler`, `max_count_value` and `discharge_delay`.
12//
13// All configuration values and sampling capacitor value have been determined experimentally.
14// Suitable configuration and discharge delay values are highly dependent on the value of the sample capacitor. For example, a shorter discharge delay can be used with smaller capacitor values.
15//
16#![no_std]
17#![no_main]
18
19use defmt::*;
20use embassy_stm32::bind_interrupts;
21use embassy_stm32::gpio::{Level, Output, Speed};
22use embassy_stm32::tsc::{self, *};
23use embassy_time::Timer;
24use {defmt_rtt as _, panic_probe as _};
25
26bind_interrupts!(struct Irqs {
27 TSC => InterruptHandler<embassy_stm32::peripherals::TSC>;
28});
29
30#[cortex_m_rt::exception]
31unsafe fn HardFault(_: &cortex_m_rt::ExceptionFrame) -> ! {
32 cortex_m::peripheral::SCB::sys_reset();
33}
34
35/// This example is written for the nucleo-stm32l073rz, with a stm32l073rz chip.
36///
37/// Make sure you check/update the following (whether you use the L073RZ or another board):
38///
39/// * [ ] Update .cargo/config.toml with the correct `probe-rs run --chip STM32L073RZTx`chip name.
40/// * [ ] Update Cargo.toml to have the correct `embassy-stm32` feature, for L073RZ it should be `stm32l073rz`.
41/// * [ ] If your board has a special clock or power configuration, make sure that it is
42/// set up appropriately.
43/// * [ ] If your board has different pin mapping, update any pin numbers or peripherals
44/// to match your schematic
45///
46/// If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:
47///
48/// * Which example you are trying to run
49/// * Which chip and board you are using
50///
51/// Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org
52#[embassy_executor::main]
53async fn main(_spawner: embassy_executor::Spawner) {
54 let device_config = embassy_stm32::Config::default();
55 let context = embassy_stm32::init(device_config);
56
57 let config = tsc::Config {
58 ct_pulse_high_length: ChargeTransferPulseCycle::_4,
59 ct_pulse_low_length: ChargeTransferPulseCycle::_4,
60 spread_spectrum: false,
61 spread_spectrum_deviation: SSDeviation::new(2).unwrap(),
62 spread_spectrum_prescaler: false,
63 pulse_generator_prescaler: PGPrescalerDivider::_16,
64 max_count_value: MaxCount::_255,
65 io_default_mode: false,
66 synchro_pin_polarity: false,
67 acquisition_mode: false,
68 max_count_interrupt: false,
69 channel_ios: TscIOPin::Group1Io1.into(),
70 shield_ios: 0, // no shield
71 sampling_ios: TscIOPin::Group1Io2.into(),
72 };
73
74 let mut g1: PinGroup<embassy_stm32::peripherals::TSC, G1> = PinGroup::new();
75 g1.set_io1(context.PA0, PinType::Sample);
76 g1.set_io2(context.PA1, PinType::Channel);
77
78 let mut touch_controller = tsc::Tsc::new_async(
79 context.TSC,
80 Some(g1),
81 None,
82 None,
83 None,
84 None,
85 None,
86 None,
87 None,
88 config,
89 Irqs,
90 );
91
92 // Check if TSC is ready
93 if touch_controller.get_state() != State::Ready {
94 info!("TSC not ready!");
95 loop {} // Halt execution
96 }
97 info!("TSC initialized successfully");
98
99 // LED2 on the STM32L073RZ nucleo-board (PA5)
100 let mut led = Output::new(context.PA5, Level::High, Speed::Low);
101
102 // smaller sample capacitor discharge faster and can be used with shorter delay.
103 let discharge_delay = 5; // ms
104
105 info!("Starting touch_controller interface");
106 loop {
107 touch_controller.start();
108 touch_controller.pend_for_acquisition().await;
109 touch_controller.discharge_io(true);
110 Timer::after_millis(discharge_delay).await;
111
112 let grp1_status = touch_controller.group_get_status(Group::One);
113 match grp1_status {
114 GroupStatus::Complete => {
115 let group_one_val = touch_controller.group_get_value(Group::One);
116 info!("{}", group_one_val);
117 led.set_high();
118 }
119 GroupStatus::Ongoing => led.set_low(),
120 }
121 }
122}
diff --git a/examples/stm32l0/src/bin/blocking-tsc.rs b/examples/stm32l0/src/bin/blocking-tsc.rs
deleted file mode 100644
index 7e4f40946..000000000
--- a/examples/stm32l0/src/bin/blocking-tsc.rs
+++ /dev/null
@@ -1,116 +0,0 @@
1// Example of polling TSC (Touch Sensing Controller) that lights an LED when touch is detected.
2//
3// Suggested physical setup on STM32L073RZ Nucleo board:
4// - Connect a 1000pF capacitor between pin A0 and GND. This is your sampling capacitor.
5// - Connect one end of a 1K resistor to pin A1 and leave the other end loose.
6// The loose end will act as touch sensor which will register your touch.
7//
8// Troubleshooting the setup:
9// - If no touch seems to be registered, then try to disconnect the sampling capacitor from GND momentarily,
10// now the led should light up. Next try using a different value for the sampling capacitor.
11// Also experiment with increasing the values for `ct_pulse_high_length`, `ct_pulse_low_length`, `pulse_generator_prescaler`, `max_count_value` and `discharge_delay`.
12//
13// All configuration values and sampling capacitor value have been determined experimentally.
14// Suitable configuration and discharge delay values are highly dependent on the value of the sample capacitor. For example, a shorter discharge delay can be used with smaller capacitor values.
15//
16#![no_std]
17#![no_main]
18
19use defmt::*;
20use embassy_stm32::gpio::{Level, Output, Speed};
21use embassy_stm32::tsc::{self, *};
22use embassy_time::Timer;
23use {defmt_rtt as _, panic_probe as _};
24
25/// This example is written for the nucleo-stm32l073rz, with a stm32l073rz chip.
26///
27/// Make sure you check/update the following (whether you use the L073RZ or another board):
28///
29/// * [ ] Update .cargo/config.toml with the correct `probe-rs run --chip STM32L073RZTx`chip name.
30/// * [ ] Update Cargo.toml to have the correct `embassy-stm32` feature, for L073RZ it should be `stm32l073rz`.
31/// * [ ] If your board has a special clock or power configuration, make sure that it is
32/// set up appropriately.
33/// * [ ] If your board has different pin mapping, update any pin numbers or peripherals
34/// to match your schematic
35///
36/// If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:
37///
38/// * Which example you are trying to run
39/// * Which chip and board you are using
40///
41/// Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org
42#[embassy_executor::main]
43async fn main(_spawner: embassy_executor::Spawner) {
44 let device_config = embassy_stm32::Config::default();
45 let context = embassy_stm32::init(device_config);
46
47 let tsc_conf = Config {
48 ct_pulse_high_length: ChargeTransferPulseCycle::_4,
49 ct_pulse_low_length: ChargeTransferPulseCycle::_4,
50 spread_spectrum: false,
51 spread_spectrum_deviation: SSDeviation::new(2).unwrap(),
52 spread_spectrum_prescaler: false,
53 pulse_generator_prescaler: PGPrescalerDivider::_16,
54 max_count_value: MaxCount::_255,
55 io_default_mode: false,
56 synchro_pin_polarity: false,
57 acquisition_mode: false,
58 max_count_interrupt: false,
59 channel_ios: TscIOPin::Group1Io1.into(),
60 shield_ios: 0, // no shield
61 sampling_ios: TscIOPin::Group1Io2.into(),
62 };
63
64 let mut g1: PinGroup<embassy_stm32::peripherals::TSC, G1> = PinGroup::new();
65 g1.set_io1(context.PA0, PinType::Sample);
66 g1.set_io2(context.PA1, PinType::Channel);
67
68 let mut touch_controller = tsc::Tsc::new_blocking(
69 context.TSC,
70 Some(g1),
71 None,
72 None,
73 None,
74 None,
75 None,
76 None,
77 None,
78 tsc_conf,
79 );
80
81 // Check if TSC is ready
82 if touch_controller.get_state() != State::Ready {
83 info!("TSC not ready!");
84 loop {} // Halt execution
85 }
86 info!("TSC initialized successfully");
87
88 // LED2 on the STM32L073RZ nucleo-board (PA5)
89 let mut led = Output::new(context.PA5, Level::High, Speed::Low);
90
91 // smaller sample capacitor discharge faster and can be used with shorter delay.
92 let discharge_delay = 5; // ms
93
94 // the interval at which the loop polls for new touch sensor values
95 let polling_interval = 100; // ms
96
97 info!("polling for touch");
98 loop {
99 touch_controller.start();
100 touch_controller.poll_for_acquisition();
101 touch_controller.discharge_io(true);
102 Timer::after_millis(discharge_delay).await;
103
104 let grp1_status = touch_controller.group_get_status(Group::One);
105 match grp1_status {
106 GroupStatus::Complete => {
107 let group_one_val = touch_controller.group_get_value(Group::One);
108 info!("{}", group_one_val);
109 led.set_high();
110 }
111 GroupStatus::Ongoing => led.set_low(),
112 }
113
114 Timer::after_millis(polling_interval).await;
115 }
116}
diff --git a/examples/stm32l0/src/bin/tsc_async.rs b/examples/stm32l0/src/bin/tsc_async.rs
new file mode 100644
index 000000000..cebe9712f
--- /dev/null
+++ b/examples/stm32l0/src/bin/tsc_async.rs
@@ -0,0 +1,116 @@
1// Example of async TSC (Touch Sensing Controller) that lights an LED when touch is detected.
2//
3// This example demonstrates:
4// 1. Configuring a single TSC channel pin
5// 2. Using the blocking TSC interface with polling
6// 3. Waiting for acquisition completion using `poll_for_acquisition`
7// 4. Reading touch values and controlling an LED based on the results
8//
9// Suggested physical setup on STM32L073RZ Nucleo board:
10// - Connect a 1000pF capacitor between pin PA0 and GND. This is your sampling capacitor.
11// - Connect one end of a 1K resistor to pin PA1 and leave the other end loose.
12// The loose end will act as the touch sensor which will register your touch.
13//
14// The example uses two pins from Group 1 of the TSC on the STM32L073RZ Nucleo board:
15// - PA0 as the sampling capacitor, TSC group 1 IO1 (label A0)
16// - PA1 as the channel pin, TSC group 1 IO2 (label A1)
17//
18// The program continuously reads the touch sensor value:
19// - It starts acquisition, waits for completion using `poll_for_acquisition`, and reads the value.
20// - The LED is turned on when touch is detected (sensor value < 25).
21// - Touch values are logged to the console.
22//
23// Troubleshooting:
24// - If touch is not detected, try adjusting the SENSOR_THRESHOLD value.
25// - Experiment with different values for ct_pulse_high_length, ct_pulse_low_length,
26// pulse_generator_prescaler, max_count_value, and discharge_delay to optimize sensitivity.
27//
28// Note: Configuration values and sampling capacitor value have been determined experimentally.
29// Optimal values may vary based on your specific hardware setup.
30// Pins have been chosen for their convenient locations on the STM32L073RZ board. Refer to the
31// official relevant STM32 datasheets and nucleo-board user manuals to find suitable
32// alternative pins.
33//
34// Beware for STM32L073RZ nucleo-board, that PA2 and PA3 is used for the uart connection to
35// the programmer chip. If you try to use these two pins for TSC, you will get strange
36// readings, unless you somehow reconfigure/re-wire your nucleo-board.
37// No errors or warnings will be emitted, they will just silently not work as expected.
38// (see nucleo user manual UM1724, Rev 14, page 25)
39
40#![no_std]
41#![no_main]
42
43use defmt::*;
44use embassy_stm32::gpio::{Level, Output, Speed};
45use embassy_stm32::tsc::{self, *};
46use embassy_stm32::{bind_interrupts, peripherals};
47use embassy_time::Timer;
48use {defmt_rtt as _, panic_probe as _};
49
50bind_interrupts!(struct Irqs {
51 TSC => InterruptHandler<embassy_stm32::peripherals::TSC>;
52});
53const SENSOR_THRESHOLD: u16 = 25; // Adjust this value based on your setup
54
55#[embassy_executor::main]
56async fn main(_spawner: embassy_executor::Spawner) {
57 let device_config = embassy_stm32::Config::default();
58 let context = embassy_stm32::init(device_config);
59
60 let mut pin_group: PinGroupWithRoles<peripherals::TSC, G1> = PinGroupWithRoles::default();
61 pin_group.set_io1::<tsc_pin_roles::Sample>(context.PA0);
62 let sensor = pin_group.set_io2::<tsc_pin_roles::Channel>(context.PA1);
63
64 let tsc_conf = Config {
65 ct_pulse_high_length: ChargeTransferPulseCycle::_4,
66 ct_pulse_low_length: ChargeTransferPulseCycle::_4,
67 spread_spectrum: false,
68 spread_spectrum_deviation: SSDeviation::new(2).unwrap(),
69 spread_spectrum_prescaler: false,
70 pulse_generator_prescaler: PGPrescalerDivider::_16,
71 max_count_value: MaxCount::_255,
72 io_default_mode: false,
73 synchro_pin_polarity: false,
74 acquisition_mode: false,
75 max_count_interrupt: false,
76 };
77
78 let pin_groups: PinGroups<peripherals::TSC> = PinGroups {
79 g1: Some(pin_group.pin_group),
80 ..Default::default()
81 };
82
83 let mut touch_controller = tsc::Tsc::new_async(context.TSC, pin_groups, tsc_conf, Irqs).unwrap();
84
85 // Check if TSC is ready
86 if touch_controller.get_state() != State::Ready {
87 info!("TSC not ready!");
88 return;
89 }
90 info!("TSC initialized successfully");
91
92 // LED2 on the STM32L073RZ nucleo-board (PA5)
93 let mut led = Output::new(context.PA5, Level::Low, Speed::Low);
94
95 let discharge_delay = 5; // ms
96
97 info!("Starting touch_controller interface");
98 loop {
99 touch_controller.set_active_channels_mask(sensor.pin.into());
100 touch_controller.start();
101 touch_controller.pend_for_acquisition().await;
102 touch_controller.discharge_io(true);
103 Timer::after_millis(discharge_delay).await;
104
105 let group_val = touch_controller.group_get_value(sensor.pin.group());
106 info!("Touch value: {}", group_val);
107
108 if group_val < SENSOR_THRESHOLD {
109 led.set_high();
110 } else {
111 led.set_low();
112 }
113
114 Timer::after_millis(100).await;
115 }
116}
diff --git a/examples/stm32l0/src/bin/tsc_blocking.rs b/examples/stm32l0/src/bin/tsc_blocking.rs
new file mode 100644
index 000000000..65203925c
--- /dev/null
+++ b/examples/stm32l0/src/bin/tsc_blocking.rs
@@ -0,0 +1,142 @@
1// Example of blocking TSC (Touch Sensing Controller) that lights an LED when touch is detected.
2//
3// This example demonstrates:
4// 1. Configuring a single TSC channel pin
5// 2. Using the blocking TSC interface with polling
6// 3. Waiting for acquisition completion using `poll_for_acquisition`
7// 4. Reading touch values and controlling an LED based on the results
8//
9// Suggested physical setup on STM32L073RZ Nucleo board:
10// - Connect a 1000pF capacitor between pin PA0 and GND. This is your sampling capacitor.
11// - Connect one end of a 1K resistor to pin PA1 and leave the other end loose.
12// The loose end will act as the touch sensor which will register your touch.
13//
14// The example uses two pins from Group 1 of the TSC on the STM32L073RZ Nucleo board:
15// - PA0 as the sampling capacitor, TSC group 1 IO1 (label A0)
16// - PA1 as the channel pin, TSC group 1 IO2 (label A1)
17//
18// The program continuously reads the touch sensor value:
19// - It starts acquisition, waits for completion using `poll_for_acquisition`, and reads the value.
20// - The LED is turned on when touch is detected (sensor value < 25).
21// - Touch values are logged to the console.
22//
23// Troubleshooting:
24// - If touch is not detected, try adjusting the SENSOR_THRESHOLD value.
25// - Experiment with different values for ct_pulse_high_length, ct_pulse_low_length,
26// pulse_generator_prescaler, max_count_value, and discharge_delay to optimize sensitivity.
27//
28// Note: Configuration values and sampling capacitor value have been determined experimentally.
29// Optimal values may vary based on your specific hardware setup.
30// Pins have been chosen for their convenient locations on the STM32L073RZ board. Refer to the
31// official relevant STM32 datasheets and nucleo-board user manuals to find suitable
32// alternative pins.
33//
34// Beware for STM32L073RZ nucleo-board, that PA2 and PA3 is used for the uart connection to
35// the programmer chip. If you try to use these two pins for TSC, you will get strange
36// readings, unless you somehow reconfigure/re-wire your nucleo-board.
37// No errors or warnings will be emitted, they will just silently not work as expected.
38// (see nucleo user manual UM1724, Rev 14, page 25)
39
40#![no_std]
41#![no_main]
42
43use defmt::*;
44use embassy_stm32::gpio::{Level, Output, Speed};
45use embassy_stm32::tsc::{self, *};
46use embassy_stm32::{mode, peripherals};
47use embassy_time::Timer;
48use {defmt_rtt as _, panic_probe as _};
49
50const SENSOR_THRESHOLD: u16 = 25; // Adjust this value based on your setup
51
52#[embassy_executor::main]
53async fn main(_spawner: embassy_executor::Spawner) {
54 let device_config = embassy_stm32::Config::default();
55 let context = embassy_stm32::init(device_config);
56
57 let tsc_conf = Config {
58 ct_pulse_high_length: ChargeTransferPulseCycle::_4,
59 ct_pulse_low_length: ChargeTransferPulseCycle::_4,
60 spread_spectrum: false,
61 spread_spectrum_deviation: SSDeviation::new(2).unwrap(),
62 spread_spectrum_prescaler: false,
63 pulse_generator_prescaler: PGPrescalerDivider::_16,
64 max_count_value: MaxCount::_255,
65 io_default_mode: false,
66 synchro_pin_polarity: false,
67 acquisition_mode: false,
68 max_count_interrupt: false,
69 };
70
71 let mut g1: PinGroupWithRoles<peripherals::TSC, G1> = PinGroupWithRoles::default();
72 g1.set_io1::<tsc_pin_roles::Sample>(context.PA0);
73 let tsc_sensor = g1.set_io2::<tsc_pin_roles::Channel>(context.PA1);
74
75 let pin_groups: PinGroups<peripherals::TSC> = PinGroups {
76 g1: Some(g1.pin_group),
77 ..Default::default()
78 };
79
80 let mut touch_controller = tsc::Tsc::new_blocking(context.TSC, pin_groups, tsc_conf).unwrap();
81
82 // Check if TSC is ready
83 if touch_controller.get_state() != State::Ready {
84 crate::panic!("TSC not ready!");
85 }
86 info!("TSC initialized successfully");
87
88 // LED2 on the STM32L073RZ nucleo-board (PA5)
89 let mut led = Output::new(context.PA5, Level::High, Speed::Low);
90
91 // smaller sample capacitor discharge faster and can be used with shorter delay.
92 let discharge_delay = 5; // ms
93
94 // the interval at which the loop polls for new touch sensor values
95 let polling_interval = 100; // ms
96
97 info!("polling for touch");
98 loop {
99 touch_controller.set_active_channels_mask(tsc_sensor.pin.into());
100 touch_controller.start();
101 touch_controller.poll_for_acquisition();
102 touch_controller.discharge_io(true);
103 Timer::after_millis(discharge_delay).await;
104
105 match read_touch_value(&mut touch_controller, tsc_sensor.pin).await {
106 Some(v) => {
107 info!("sensor value {}", v);
108 if v < SENSOR_THRESHOLD {
109 led.set_high();
110 } else {
111 led.set_low();
112 }
113 }
114 None => led.set_low(),
115 }
116
117 Timer::after_millis(polling_interval).await;
118 }
119}
120
121const MAX_GROUP_STATUS_READ_ATTEMPTS: usize = 10;
122
123// attempt to read group status and delay when still ongoing
124async fn read_touch_value(
125 touch_controller: &mut tsc::Tsc<'_, peripherals::TSC, mode::Blocking>,
126 sensor_pin: TscIOPin,
127) -> Option<u16> {
128 for _ in 0..MAX_GROUP_STATUS_READ_ATTEMPTS {
129 match touch_controller.group_get_status(sensor_pin.group()) {
130 GroupStatus::Complete => {
131 return Some(touch_controller.group_get_value(sensor_pin.group()));
132 }
133 GroupStatus::Ongoing => {
134 // if you end up here a lot, then you prob need to increase discharge_delay
135 // or consider changing the code to adjust the discharge_delay dynamically
136 info!("Acquisition still ongoing");
137 Timer::after_millis(1).await;
138 }
139 }
140 }
141 None
142}
diff --git a/examples/stm32l0/src/bin/tsc_multipin.rs b/examples/stm32l0/src/bin/tsc_multipin.rs
new file mode 100644
index 000000000..6170d0799
--- /dev/null
+++ b/examples/stm32l0/src/bin/tsc_multipin.rs
@@ -0,0 +1,233 @@
1// Example of TSC (Touch Sensing Controller) using multiple pins from the same tsc-group.
2//
3// What is special about using multiple TSC pins as sensor channels from the same TSC group,
4// is that only one TSC pin for each TSC group can be acquired and read at the time.
5// To control which channel pins are acquired and read, we must write a mask before initiating an
6// acquisition. To help manage and abstract all this business away, we can organize our channel
7// pins into acquisition banks. Each acquisition bank can contain exactly one channel pin per TSC
8// group and it will contain the relevant mask.
9//
10// This example demonstrates how to:
11// 1. Configure multiple channel pins within a single TSC group
12// 2. Use the set_active_channels method to switch between different channels
13// 3. Read and interpret touch values from multiple channels in the same group
14//
15// Suggested physical setup on STM32L073RZ Nucleo board:
16// - Connect a 1000pF capacitor between pin PA0 (label A0) and GND. This is the sampling capacitor for TSC
17// group 1.
18// - Connect one end of a 1K resistor to pin PA1 (label A1) and leave the other end loose.
19// The loose end will act as a touch sensor.
20//
21// - Connect a 1000pF capacitor between pin PB3 (label D3) and GND. This is the sampling capacitor for TSC
22// group 5.
23// - Connect one end of another 1K resistor to pin PB4 and leave the other end loose.
24// The loose end will act as a touch sensor.
25// - Connect one end of another 1K resistor to pin PB6 and leave the other end loose.
26// The loose end will act as a touch sensor.
27//
28// The example uses pins from two TSC groups.
29// - PA0 as sampling capacitor, TSC group 1 IO1 (label A0)
30// - PA1 as channel, TSC group 1 IO2 (label A1)
31// - PB3 as sampling capacitor, TSC group 5 IO1 (label D3)
32// - PB4 as channel, TSC group 5 IO2 (label D3)
33// - PB6 as channel, TSC group 5 IO3 (label D5)
34//
35// The pins have been chosen to make it easy to simply add capacitors directly onto the board and
36// connect one leg to GND, and to easily add resistors to the board with no special connectors,
37// breadboards, special wires or soldering required. All you need is the capacitors and resistors.
38//
39// The program reads the designated channel pins and adjusts the LED blinking
40// pattern based on which sensor(s) are touched:
41// - No touch: LED off
42// - one sensor touched: Slow blinking
43// - two sensors touched: Fast blinking
44// - three sensors touched: LED constantly on
45//
46// Troubleshooting:
47// - If touch is not detected, try adjusting the SENSOR_THRESHOLD value.
48// - Experiment with different values for ct_pulse_high_length, ct_pulse_low_length,
49// pulse_generator_prescaler, max_count_value, and discharge_delay to optimize sensitivity.
50//
51// Note: Configuration values and sampling capacitor value have been determined experimentally.
52// Optimal values may vary based on your specific hardware setup.
53// Pins have been chosen for their convenient locations on the STM32L073RZ board. Refer to the
54// official relevant STM32 datasheets and nucleo-board user manuals to find suitable
55// alternative pins.
56//
57// Beware for STM32L073RZ nucleo-board, that PA2 and PA3 is used for the uart connection to
58// the programmer chip. If you try to use these two pins for TSC, you will get strange
59// readings, unless you somehow reconfigure/re-wire your nucleo-board.
60// No errors or warnings will be emitted, they will just silently not work as expected.
61// (see nucleo user manual UM1724, Rev 14, page 25)
62
63#![no_std]
64#![no_main]
65
66use defmt::*;
67use embassy_stm32::gpio::{Level, Output, Speed};
68use embassy_stm32::tsc::{self, *};
69use embassy_stm32::{bind_interrupts, mode, peripherals};
70use embassy_time::Timer;
71use {defmt_rtt as _, panic_probe as _};
72
73bind_interrupts!(struct Irqs {
74 TSC => InterruptHandler<embassy_stm32::peripherals::TSC>;
75});
76
77const MAX_GROUP_STATUS_READ_ATTEMPTS: usize = 10;
78
79async fn read_touch_values(
80 touch_controller: &mut tsc::Tsc<'_, peripherals::TSC, mode::Async>,
81 tsc_acquisition_bank: &TscAcquisitionBank,
82) -> Option<TscAcquisitionBankReadings> {
83 for _ in 0..MAX_GROUP_STATUS_READ_ATTEMPTS {
84 let status = touch_controller.get_acquisition_bank_status(tsc_acquisition_bank);
85 if status.all_complete() {
86 let r = touch_controller.get_acquisition_bank_values(tsc_acquisition_bank);
87 return Some(r);
88 } else {
89 info!("Acquisition still ongoing");
90 Timer::after_millis(1).await;
91 }
92 }
93 info!("Acquisition failed after {} attempts", MAX_GROUP_STATUS_READ_ATTEMPTS);
94 None
95}
96
97const SENSOR_THRESHOLD: u16 = 35;
98
99async fn acquire_sensors(
100 touch_controller: &mut Tsc<'static, peripherals::TSC, mode::Async>,
101 tsc_acquisition_bank: &TscAcquisitionBank,
102) {
103 touch_controller.set_active_channels_mask(tsc_acquisition_bank.mask());
104 touch_controller.start();
105 touch_controller.pend_for_acquisition().await;
106 touch_controller.discharge_io(true);
107 let discharge_delay = 5; // ms
108 Timer::after_millis(discharge_delay).await;
109}
110
111#[embassy_executor::main]
112async fn main(_spawner: embassy_executor::Spawner) {
113 let device_config = embassy_stm32::Config::default();
114 let context = embassy_stm32::init(device_config);
115
116 // ---------- initial configuration of TSC ----------
117 let mut pin_group1: PinGroupWithRoles<peripherals::TSC, G1> = PinGroupWithRoles::default();
118 pin_group1.set_io1::<tsc_pin_roles::Sample>(context.PA0);
119 let tsc_sensor0 = pin_group1.set_io2(context.PA1);
120
121 let mut pin_group5: PinGroupWithRoles<peripherals::TSC, G5> = PinGroupWithRoles::default();
122 pin_group5.set_io1::<tsc_pin_roles::Sample>(context.PB3);
123 let tsc_sensor1 = pin_group5.set_io2(context.PB4);
124 let tsc_sensor2 = pin_group5.set_io3(context.PB6);
125
126 let config = tsc::Config {
127 ct_pulse_high_length: ChargeTransferPulseCycle::_16,
128 ct_pulse_low_length: ChargeTransferPulseCycle::_16,
129 spread_spectrum: false,
130 spread_spectrum_deviation: SSDeviation::new(2).unwrap(),
131 spread_spectrum_prescaler: false,
132 pulse_generator_prescaler: PGPrescalerDivider::_16,
133 max_count_value: MaxCount::_255,
134 io_default_mode: false,
135 synchro_pin_polarity: false,
136 acquisition_mode: false,
137 max_count_interrupt: false,
138 };
139
140 let pin_groups: PinGroups<peripherals::TSC> = PinGroups {
141 g1: Some(pin_group1.pin_group),
142 g5: Some(pin_group5.pin_group),
143 ..Default::default()
144 };
145
146 let mut touch_controller = tsc::Tsc::new_async(context.TSC, pin_groups, config, Irqs).unwrap();
147
148 // ---------- setting up acquisition banks ----------
149 // sensor0 and sensor1 in this example belong to different TSC-groups,
150 // therefore we can acquire and read them both in one go.
151 let bank1 = touch_controller.create_acquisition_bank(TscAcquisitionBankPins {
152 g1_pin: Some(tsc_sensor0),
153 g5_pin: Some(tsc_sensor1),
154 ..Default::default()
155 });
156 // `sensor1` and `sensor2` belongs to the same TSC-group, therefore we must make sure to
157 // acquire them one at the time. Therefore, we organize them into different acquisition banks.
158 let bank2 = touch_controller.create_acquisition_bank(TscAcquisitionBankPins {
159 g5_pin: Some(tsc_sensor2),
160 ..Default::default()
161 });
162
163 // Check if TSC is ready
164 if touch_controller.get_state() != State::Ready {
165 crate::panic!("TSC not ready!");
166 }
167
168 info!("TSC initialized successfully");
169
170 // LED2 on the STM32L073RZ nucleo-board (PA5)
171 let mut led = Output::new(context.PA5, Level::High, Speed::Low);
172
173 let mut led_state = false;
174
175 loop {
176 acquire_sensors(&mut touch_controller, &bank1).await;
177 let readings1: TscAcquisitionBankReadings = read_touch_values(&mut touch_controller, &bank1)
178 .await
179 .expect("should be able to read values for bank 1");
180 acquire_sensors(&mut touch_controller, &bank2).await;
181 let readings2: TscAcquisitionBankReadings = read_touch_values(&mut touch_controller, &bank2)
182 .await
183 .expect("should be able to read values for bank 2");
184
185 let mut touched_sensors_count = 0;
186 for reading in readings1.iter() {
187 info!("{}", reading);
188 if reading.sensor_value < SENSOR_THRESHOLD {
189 touched_sensors_count += 1;
190 }
191 }
192 for reading in readings2.iter() {
193 info!("{}", reading);
194 if reading.sensor_value < SENSOR_THRESHOLD {
195 touched_sensors_count += 1;
196 }
197 }
198
199 match touched_sensors_count {
200 0 => {
201 // No sensors touched, turn off the LED
202 led.set_low();
203 led_state = false;
204 }
205 1 => {
206 // One sensor touched, blink slowly
207 led_state = !led_state;
208 if led_state {
209 led.set_high();
210 } else {
211 led.set_low();
212 }
213 Timer::after_millis(200).await;
214 }
215 2 => {
216 // Two sensors touched, blink faster
217 led_state = !led_state;
218 if led_state {
219 led.set_high();
220 } else {
221 led.set_low();
222 }
223 Timer::after_millis(50).await;
224 }
225 3 => {
226 // All three sensors touched, LED constantly on
227 led.set_high();
228 led_state = true;
229 }
230 _ => crate::unreachable!(), // This case should never occur with 3 sensors
231 }
232 }
233}