MATLAB Answers

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

23 views (last 30 days)
Alan Martínez
Alan Martínez on 10 Oct 2019
Answered: Arun Kumar on 15 Oct 2019
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.

Answers (1)

Arun Kumar
Arun Kumar on 15 Oct 2019
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!

Community Treasure Hunt

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

Start Hunting!

Translated by