How can I read the button state of a joystick (ARD-358) using Arduino with Simulink?

34 次查看(过去 30 天)
I'm using Arduino MEGA 2560 with Simulink through the Simulink Support Package for Arduino Hardware and a joystick ARD-358
I have a problem when reading the state of the button of my joystick with the block Digital Input in Simulink. It does not read the digital signal, I always get the same value (0) wether I'm pressing the button or not.
This does not happen when using the following code in Arduino (the software).
int buttonPin = 53;
int buttonState = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
buttonState = digitalRead(buttonPin);
Serial.print(" | Button: ");
Serial.println(buttonState);
delay(100);
}
With this code I do get an accurate lecture, so we can rule out hardware damage.
The only difference I see between the Simulink diagram and the Arduino code is the section void setup, in which the pinMode is defined. In the Command Window in MATLAB I can use a similar command, configurePin, but I do not know how to use it in simulink.
I'd very much appreciate your help.

回答(1 个)

Arun Kumar
Arun Kumar 2019-10-15
Hi,
The only difference between your arduino sketch and the generated code is the the pin configuration. With arduino sketch, the pin is configured as INPUT_PULLUP which will enable the internal pullup of this pin. But with Simulink, the default behaviour of input pin is floating. I am guessing this is the reason for the observed behaviour.
Workaround:
1. External pullup resistor: You can connect an external pullup resistor to the input pin. Refer this wiki page for more details https://en.wikipedia.org/wiki/Pull-up_resistor
2. Modify Source file: Alternatively you can modify the Simulink source file to enable input pullup by default. For that do the following:
  • In MATLAB command line type:
edit(fullfile(codertarget.arduinobase.internal.getSpPkgRootDir,'..','arduinobase','src','MW_arduino_digitalio.cpp'))
  • MW_arduino_digitalio file will open the the editor. In this file change the line pinMode(pin, INPUT) to pinMode(pin, INPUT_PULLUP) inside the function digitalIOSetup
Hope this helps.
Cheers!

类别

Help CenterFile Exchange 中查找有关 MATLAB Support Package for Arduino Hardware 的更多信息

产品


版本

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by