Komunikasi SPI Menggunakan Arduino
1. Prosedur [Kembali]
- Rangkai semua komponen
- Buat program di aplikasi arduino IDE
- Setelah selesai masukkan program ke arduino
- Jalankan program pada simulasi dan cobakan sesuai kondisi
//Master
#include
<SPI.h>
int dip[] = {2, 3, 4, 5, 6, 7, 8, 9};
int dipvalue[] = {};
int dipCount = 0; // Variable to count active dip switches
void setup() {
Serial.begin(9600);
for (int i = 0; i < 8; i++) {
pinMode(dip[i], INPUT_PULLUP);
}
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV8);
digitalWrite(SS, HIGH);
}
void loop() {
byte Mastersend = 0;
for (int i = 0; i < 8; i++) {
dipvalue[i] =
digitalRead(dip[i]);
if (dipvalue[i] == LOW) {
dipCount++; // Increment dip switch
count if active
}
}
if (dipCount == 1) {
Mastersend = 1; // Set Mastersend to
1 if only one dip switch is active
} else if (dipCount == 4) {
Mastersend = 4; // Set Mastersend to
4 if four dip switches are active
}
dipCount = 0; // Reset dip switch count
for next iteration
digitalWrite(SS, LOW);
SPI.transfer(Mastersend);
delay(100);
}
//Slave
#include
<SPI.h>
#define a 9
#define b 8
#define c 7
#define d 6
#define e 5
#define f 4
#define g 3
#define dp 2
#define D1 1
#define D2 0
const int segmentPins[] = {a, b, c, d, e, f, g}; // Koneksi digit 1 ke pin 1,
digit 2 ke pin 0
volatile boolean received = false;
volatile byte Slavereceived;
void setup() {
pinMode(D1, OUTPUT);
pinMode(D2, OUTPUT);
Serial.begin(9600);
for (int i = 0; i < 7; i++) {
pinMode(segmentPins[i],
OUTPUT);
}
SPCR |= _BV(SPE);
SPI.attachInterrupt();
}
ISR(SPI_STC_vect) {
Slavereceived = SPDR;
received = true;
}
void displayCharacter(int digit, int digitPosition) {
byte patterns[10][7] = {
{0, 0, 0, 0, 0, 0, 1}, // 0
{1, 0, 0, 1, 1, 1, 1}, // 1
{0, 0, 1, 0, 0, 1, 0}, // 2
{0, 0, 0, 0, 1, 1, 0}, // 3
{1, 0, 0, 1, 1, 0, 0}, // 4
{0, 1, 0, 0, 1, 0, 0}, // 5
{0, 1, 0, 0, 0, 0, 0}, // 6
{0, 0, 0, 1, 1, 1, 1}, // 7
{0, 0, 0, 0, 0, 0, 0}, // 8
{0, 0, 0, 0, 1, 0, 0} // 9
};
// Write the pattern to the segment
pins
for (int i = 0; i < 7; i++) {
digitalWrite(segmentPins[i],
patterns[digit][i]);
}
// Aktifkan digit yang sesuai
if (digitPosition == D1) {
digitalWrite(D1, HIGH);
digitalWrite(D2, LOW);
} else if (digitPosition == D2) {
digitalWrite(D1, LOW);
digitalWrite(D2, HIGH);
}
delay(5); // Delay kecil untuk
memastikan penampilan stabil
}
void loop() {
if (received) {
if (Slavereceived == 1) {
displayCharacter(8, D1); //
Menampilkan angka 1 hanya pada digit 1
displayCharacter(0, D2); // Matikan
digit 2
} else if (Slavereceived == 4)
{
displayCharacter(4, D1); //
Menampilkan angka 4 pada kedua digit
displayCharacter(4, D2);
}
delay(100);
received = false;
}
}
Tidak ada komentar:
Posting Komentar