I have tried this other way to send voltages from 0 to 5, sending integers from 0 to 255.
matlab:
%Creates a serial connection
serialPort=serial('COM4','BaudRate',9600);
%Informs about errors
warning('off','MATLAB:serial:fscanf:unsuccessfulRead');
%Opens the serial port
fopen(serialPort);
option=input('Introduce the voltage value between 0 and 5 volts or esc to exit: ','s');
while strcmp(option,'esc')==0
voltage=str2double(option);
while (voltage<0)||(voltage>5)||isnan(voltage)&& (strcmp(option,'esc')==0)
disp('Value non-valid, introduce a value from 0 to 5');
disp('Press any key to continue.');
pause
clc
option=input('Introduce the voltage value between 0 and 5 volts or esc to exit: ','s');
voltage=str2double(option);
end
if strcmp(option,'esc')==0
volt_mapped=map2(voltage,0,5,0,255);
disp(['voltage = ' num2str(volt_mapped)]);
fwrite(serialPort,volt_mapped,'int8');
disp('Press any key to continue');
pause
clc
option=input('Introduce the voltage value between 0 and 5 volts or esc to exit: ','s');
end
end
%Closes the serial port
fclose(serialPort);
clear serialPort
clear all
arduino:
int incomingByte = 0; // para el byte leido
int portNum;
void setup() {
Serial.begin(9600); // abre el puerto serie a 9600 bps
portNum=6;
analogWrite(portNum,0);
}
void loop() {
// envia datos solamente cuando recibe datos
if (Serial.available() > 0) {
// lee el byte entrante:
incomingByte = Serial.read();
analogWrite(portNum,incomingByte);
}
}
But when I introduce a value of 5 in matlab the voltage at the port in arduino is 2.56. Why? When i introduce 1 or 2 the output corresponds with these values.