Files
RepaJouets/CircuitCarreraCommande/arduinoNano_PWM/arduinoNano_PWM.ino

71 lines
2.7 KiB
C++

// PWM using Timer2 on digital outputs D3 & D11
const int pwmPin1 = 11; // OC2B, D11 = Pin 15 sur le 328P, pilote Q1
const int pwmPin2 = 3; // OC2A, D3 = Pin 1 sur le 328P, pilote Q3
const int led3 = 1; // D1 aussi utilisée par le port série
const int led4 = 0; // D0 aussi utilisée par le port série
void setup() {
pinMode(pwmPin1, OUTPUT);
pinMode(pwmPin2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(A0, INPUT); //J2 Manette Gauche, Pin 23 sur le 328P
pinMode(A1, INPUT); //J4 Manette Millieu, Pin 24 sur le 328P
pinMode(A2, INPUT); //Courant Q3, Pin 25 sur le 328P
pinMode(A3, INPUT); //Courant Q1, Pin 26 sur le 328P
// ----- Timer2 Fast PWM (8-bit), no prescaler -----
TCCR2A = _BV(WGM20) | _BV(WGM21) | _BV(COM2A1) | _BV(COM2B1);
//TCCR2B = _BV(CS20); // No prescaler → 62.5 kHz
//TCCR2B = _BV(CS21); // Prescaler 8 → 7.81 kHz
TCCR2B = _BV(CS21) | _BV(CS20); // Prescaler 32 → 1.95 kHz
//TCCR2B = _BV(CS22); // Prescaler 64 → 976 Hz
ADCSRA = (1 << ADEN) | (1 << ADPS2); // Set ADC prescaler to 16 (1MHz ADC clock), 13 cycles to read a value so a readout takes 13 uS
}
uint8_t currentTCNT2 = 0;
uint8_t currentOCR2A = 0;
uint8_t currentOCR2B = 0;
void loop() {
//int adc0 = analogRead(analogPin1);
ADMUX = (1 << REFS0) | (0 & 0x0F); // Set ADC reference to AVcc and channel to ADC channel 0, example REFS0 = 1 → 0100 0000 | Channel 3 → 0000 0011 | ADMUX → 0100 0011
delayMicroseconds(2);
ADCSRA |= (1 << ADSC); // Start ADC conversion
while (ADCSRA & (1 << ADSC))
; //wait or the ADC conversion to finish
int adc0 = ADC;
if (adc0 <= 100) {
adc0 = 0;
// Disable PWM output for OC2B
TCCR2A &= ~_BV(COM2B1);
OCR2B = 0; // Optional: also set OCR2B to 0 for consistency;
} else {
// Enable PWM output for OC2B
TCCR2A |= _BV(COM2B1);
uint8_t mappedPWMvalue = map(adc0, 0, 1023, 0, 255);
OCR2B = mappedPWMvalue; // D11, J2 Manette Gauche, Pin 15 sur le 328P, pilote Q3
}
ADMUX = (1 << REFS0) | (1 & 0x0F); // Set ADC reference to AVcc and channel to ADC channel 0, example REFS0 = 1 → 0100 0000 | Channel 3 → 0000 0011 | ADMUX → 0100 0011
delayMicroseconds(2);
ADCSRA |= (1 << ADSC); // Start ADC conversion
while (ADCSRA & (1 << ADSC))
; //wait or the ADC conversion to finish
int adc1 = ADC;
if (adc1 <= 100) {
adc1 = 0;
// Disable PWM output for OC2A
TCCR2A &= ~_BV(COM2A1);
OCR2A = 0; // Optional: also set OCR2A to 0 for consistency
} else {
// Enable PWM output for OC2A
TCCR2A |= _BV(COM2A1);
uint8_t mappedPWMvalue = map(adc1, 0, 1023, 0, 255);
OCR2A = mappedPWMvalue; // D3, J4 Manette Millieu Pin 1 sur le 328P, pilote Q1
}
}