Hello...
I write code that can control pwm pin with Matlab program with serial communication.
This is arduino IDE code
/******************************************************************************/
/* PWMH0 641 Hz */
/******************************************************************************/
int incomingByte = 0;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
PMC->PMC_PCER1 |= PMC_PCER1_PID36; // PWM power ON
PIOC->PIO_PDR |= PIO_PDR_P3; // Set PWM pin to a peripheral
PIOC->PIO_ABSR |= PIO_PC3B_PWMH0; // Set PWM pin peripheral type B for PWMH0 (Arduino pin 35)
// PIOC->PIO_ABSR |= PIO_PC3B_TIOA0;
PWM->PWM_CLK = PWM_CLK_PREB(0) | PWM_CLK_DIVB(2); // select Frequency for clock B: Mck/2 = 42 MHz
PWM->PWM_CH_NUM[0].PWM_CMR = PWM_CMR_CPRE_CLKB; // The period is left aligned, clock source as CLKB on channel 0
PWM->PWM_CH_NUM[0].PWM_CPRD = 65535; // Set the PWM frequency 42 MHz/PWM_CPRD = 641 Hz
PWM->PWM_CH_NUM[0].PWM_CDTY = 32768; // Set the PWM duty cycle = (CPRD/CDTY) * 100 %
PWM->PWM_IER1 = PWM_IER1_CHID0; // Interrupt on PWM Channel 0 counter
NVIC_EnableIRQ(PWM_IRQn); // Enable interrupt
PWM->PWM_ENA = PWM_ENA_CHID0; // Enable PWM channel 0
}
void loop() {
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
Serial.print("I received: ");
Serial.println(incomingByte);
if (incomingByte==48){
PWM->PWM_CH_NUM[0].PWM_CDTY = 1;
}
// say what you got:
}
}
void PWM_Handler() {
static uint32_t Count;
PWM->PWM_ISR1; // Clear status register
if (Count++ == 641)
{
PIOB->PIO_ODSR ^= PIO_ODSR_P27;
Count = 0;
}
}
And Matlab code
delete(instrfindall);
% a = arduino('COM7','Due');
arduinoCom = serial('COM7','BaudRate',115200);
fopen(arduinoCom);
arduinoCom.BytesAvailable
fwrite(arduinoCom, '0')
fwrite(arduinoCom, '48')
fprintf(arduinoCom,'%s\n','0');
fprintf(arduinoCom,'%f\n','48');
fprintf(arduinoCom,'%f\n','0');
fprintf(arduinoCom,'%s\n','48');
pause(30)
And fprintf is
https://kr.mathworks.com/help/matlab/ref/serial.fprintf.html
So when I run Matlab code, then nothing happen.
When I just run Arduino IDE's serial window and type number "0", then I received: 48 and then
pwm is become 3.2V (when not type, it record 1.6V cause of arduino due and duty cycle 50% and 3.2V is duty cycle 100%).
I record it with multimeter.
However in Matlab, I type lot of things that can see in Matlab code.
I type number 0 and number 48 but nothing happened and recorded just 1.6V .
Does there way to solve it?