From dcadf16e1c345c92f913effa9236cc13001c49e7 Mon Sep 17 00:00:00 2001 From: Andy Killorin Date: Thu, 10 Jul 2025 07:53:05 -0500 Subject: [PATCH] spin motors currently the timer is not in independent mode, may need to drop to bits --- src/main.rs | 78 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 69 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 7a6a7ba..a97a013 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,27 +1,87 @@ #![no_std] #![no_main] +use arduino_hal::hal::port::*; +use arduino_hal::port::mode::*; +use embedded_hal::digital::OutputPin; use panic_halt as _; +fn shift_out(data_pin: &mut Pin, clock_pin: &mut Pin, data: &u8) { + for i in 0..8 { + let n = data & (1 << i); + + if n == 0 { + data_pin.set_low(); + } else { + data_pin.set_high(); + } + + clock_pin.set_high(); + clock_pin.set_low(); + } +} + +fn update_shift_register( + data_pin: &mut Pin, + latch_pin: &mut Pin, + clock_pin: &mut Pin, + data: &u8, +) { + latch_pin.set_low(); + + shift_out(data_pin, clock_pin, data); + + latch_pin.set_high(); +} + #[arduino_hal::entry] fn main() -> ! { let dp = arduino_hal::Peripherals::take().unwrap(); let pins = arduino_hal::pins!(dp); - /* - * For examples (and inspiration), head to - * - * https://github.com/Rahix/avr-hal/tree/main/examples - * - * NOTE: Not all examples were ported to all boards! There is a good chance though, that code - * for a different board can be adapted for yours. The Arduino Uno currently has the most - * examples available. - */ + // shift register + let mut data_pin = pins.d8.into_output(); + let mut clock_pin = pins.d4.into_output(); + let mut enable_pin = pins.d7.into_output(); + let mut latch_pin = pins.d12.into_output(); + + enable_pin.set_low(); // enable outputs + + let _ = pins.d3.into_output(); // right + let _ = pins.d11.into_output(); // left + + // TCCR2A |= _BV(COM2A1) | _BV(WGM20) | _BV(WGM21); // fast PWM, turn on oc2a + // TCCR2B = freq & 0x7; + // OCR2A = 0; + let tc2 = dp.TC2; + tc2.tccr2a.write(|w| { w + .wgm2().pwm_fast() + .com2a().match_set() + .com2b().match_set() + }); + tc2.tccr2b.write(|w| w.cs2().prescale_8().foc2b().clear_bit().foc2a().clear_bit().wgm22().clear_bit()); + tc2.ocr2a.write(|w| w.bits(2)); + tc2.ocr2b.write(|w| w.bits(2)); let mut led = pins.d13.into_output(); loop { + let mut shift_register = 0; + const LEFT_FWD: u8 = 1 << 5; // 1a + const LEFT_REV: u8 = 1 << 4; // 1b + const RIGHT_FWD: u8 = 1 << 3; // 2b + const RIGHT_REV: u8 = 1 << 6; // 2a + led.toggle(); + + shift_register |= LEFT_FWD | RIGHT_FWD; + + // /255 + tc2.ocr2a.write(|w| w.bits(1)); // right + tc2.ocr2b.write(|w| w.bits(1)); // left + + update_shift_register(&mut data_pin, &mut latch_pin, &mut clock_pin, &shift_register); + arduino_hal::delay_ms(1000); } }