Нужна помощь с использованием светодиодной матрицы с кнопками

Я создаю небольшой проект, который использует пару светодиодных матриц 8x8 (управляемых MAX7219), пару сервоприводов SG90, ультразвуковой датчик HC-SR04, ЖК-дисплей 16x2 (драйвер Hitachi HD44780), несколько кнопок и все это управляется с помощью Arduino Uno. Все компоненты питаются через другой порт USB на моем ПК.

Когда я попытался интегрировать все компоненты, я заметил, что светодиодная матрица вообще не загорается. Я решил объединить несколько базовых примеров кода, чтобы проверить их взаимодействие друг с другом, где я заметил, что использование pinMode для объявления моих пинов для кнопок приведет к тому, что светодиодная матрица перестанет работать. Удаление раздела с использованием // снова заставит светодиодную матрицу(ы) работать.

Есть ли у кого-нибудь опыт решения этой проблемы и может ли он объяснить мне, что является причиной этого конфликта? Я пробовал просмотреть документацию LedControl на странице arduino, но так и не смог понять, что является причиной этой проблемы.

/*

test build for debug

log:

LED Matrix : test code added, no issues
LCD Display: test code added, no issues
Sensor: test code added, serial clashed with LED Matrix. Working with disabled serial, Main build still not resolved.
Servo: test code added, no issues
Buttons: test code added, LED Matrix no longer light up. issue appears to be at the (pinMode) section when declaring buttons as inputs.


*/

//buttons

#include <Button.h>


const int positiveButtonPin = A1;
 int positiveButtonState = LOW;

const int negativeButtonPin = A2;
 int negativeButtonState = LOW;


// servo library setup
#include <Servo.h>
Servo servo1;
Servo servo2;


// lcd setup
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 10, d5 = 9, d6 = 8, d7 = 7;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//led matrix library setup
#include "LedControl.h"
LedControl lc=LedControl(2,1,0,2);  // Pins: DIN,CLK,CS, # of Display connected
unsigned long delayTime=200;  // Delay between Frames

// sensor setup
const int trigPin = 6;
const int echoPin = 5;
long duration;
int distance;


// led matrix arrays (test with 2 formats)

byte invader1a[] = {0x7C,0x7C,0x60,0x7C,0x7C,0x60,0x7C,0x7C};

byte invader1b[] = {0x78,0x7C,0x66,0x66,0x66,0x66,0x7C,0x78};

byte invader2a[] =
{
  B00100100, // First frame of invader #2
  B00100100,
  B01111110,
  B11011011,
  B11111111,
  B11111111,
  B10100101,
  B00100100
};

byte invader2b[] =
{
  B00100100, // Second frame of invader #2
  B10100101,
  B11111111,
  B11011011,
  B11111111,
  B01111110,
  B00100100,
  B01000010
};



void setup() {
  // put your setup code here, to run once:


//button setup
{
//  pinMode(positiveButtonState, INPUT);                    //         <----------------- THIS CAUSES ISSUE WITH LED MATRIX
//  pinMode(negativeButtonState, INPUT);
}

// servo setup
  servo1.attach(4);
  servo2.attach(3);



//sensor serial test code       
// sensor setup
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
//  Serial.begin(9600);                                         //     <----------------- THIS CAUSES ISSUE WITH LED MATRIX, DISABLED

    //led matrix setup
  lc.shutdown(0,false);  // Wake up displays
  lc.shutdown(1,false);
  lc.setIntensity(0,2);  // Set intensity levels
  lc.setIntensity(1,2);
  lc.clearDisplay(0);  // Clear Displays
  lc.clearDisplay(1);


    //lcd hello world code
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");


}


//  Creating array strings

void sinvader1a()
{
  for (int i = 0; i < 8; i++)  
  {
    lc.setRow(0,i,invader1a[i]);
  }
}

void sinvader1b()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0,i,invader1b[i]);
  }
}

void sinvader2a()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(1,i,invader2a[i]);
  }
}

void sinvader2b()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(1,i,invader2b[i]);
  }
}



void loop() {
  // put your main code here, to run repeatedly:

//servo test code
    // servo attach
    servo1.attach(4);
    servo2.attach(3);


     servo1.write (120);  // change angle here below. adjust until it looks like it's looking at user
  servo2.write (90);
  delay(250);
  servo1.write (90);
  servo2.write (120);
  delay(250);
// servo detach to reduce noise
servo1.detach();
servo2.detach();


// led matrix test code
    sinvader1a();
    delay(delayTime);
    sinvader2a();
    delay(delayTime);

    sinvader1b();
    delay(delayTime);
    sinvader2b();
    delay(delayTime);

    //lcd hello world code 
    // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);

//sensor test code
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;


// no longer useful due to disabled serial
/*
if (distance<1000){
Serial.print("Distance: ");
Serial.println(distance);}
else {}
*/

}

, 👍0


1 ответ


1

Похоже, вы пытаетесь использовать аппаратный UART для связи с MAX7221 или MAX7219:

LedControl lc=LedControl(2,1,0,2);

И для общения, возможно, с последовательным монитором SDK:

Serial.begin(9600);

В процессоре Atmel, используемом в Arduino Uno, есть только 1 UART. Рассмотрите возможность использования более крупного Arduino/процессора, где на процессоре больше UART. Имейте в виду, что может потребоваться переписать библиотеку для использования альтернативного оборудования на более крупных процессорах.

Кроме того, в вашем коде есть ошибка, и она заставляет вас думать об этом неправильно:

Строки:

pinMode(positiveButtonState, INPUT);
pinMode(negativeButtonState, INPUT);

...мешают работе светодиодной матрицы, поскольку они меняют пин ноль с приема UART на прием GPIO. Вероятно, вы хотели ввести:

pinMode(positiveButtonPin, INPUT);
pinMode(negativeButtonPin, INPUT);
,