อยากทราบวิธีการสั่งเอาต์พุตแบบ array ครับโดยที่ไม่ต้องมากำหนด pinmode ทีละตัว
เช่น อยากให้ขา 5-8 เป็นเอาตืพุตแล้วคอยรับคำสั่งเปิดจากคีย์บอร์ด
เข้าถึง Registor แบบตรงๆ ไม่ต้องผ่านตัวแปลภาษาเครื่อง (pinMode ,xx,INPUT,OUTPUT) ทำงานได้เร็วกว่าด้วยครับ
byte segments[] = {
B01111110, B00110000, B01101101, B01111001, B00110011, B01011011, B01011111, B01110000, B01111111, B01111011};
void setup()
{
DDRB = B00000000; // set PORTB (digital 13~8) to inputs
DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}
void disp(int z)
{
PORTD = segments[z];
}
void loop()
{
disp(PINB);
delay(100);
}
ตามนั้นครับ
อีกวิธี ลองทำตามตัวอย่างนี้ แนะนำโดยเว็บ www.arduino.cc
แล้วศึกษาการใช้งาน Array
ในตัวอย่างประกาศตัวแปร ledPins เป็น Array สำหรับเก็บขาที่ต้องการควบคุม
ใช้คำสั่ง for เพื่อเซตขา ledPins แต่ละค่าให้เป็นโหมด OUTPUT
ต้องการควบคุมขาไหนก็สั่งผ่าน Array เช่น digitalWrite(ledPins[0],HIGH);
// โคดตัวอย่าง
ขอบคุณมากครับ ขอถามอีกนะครับ
จากโค้ดตัวอย่างผมแก้ให้กลายเป็นรับค่าจากคีย์บอร์ดแล้วมันติดปัญหาอยู่ที่ว่าผมอยากให้มันติดในตำแหน่งที่ผมพิมไปเช่นผมพิมพ์1ไปก็จะติดดวงที่1 พิม2ไปก้อจะติดดวงที่2 แต่ที่นี้มันไม่ได้ตามนี้ช่วยดูให้หน่อยครับ
int ledPins[]={5,6,7,8} ; // an array of pin numbers to which LEDs are attached
int pinCount ; // the number of pins (i.e. the length of the array)
void setup(){
Serial.begin(9600);
// the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output:
for(int thisPin=0;thisPin<pinCount;thisPin++){
pinMode(ledPins[thisPin],OUTPUT);
}
}
void loop(){
while (Serial.available() > 0)
{
pinCount=Serial.parseInt();
Serial.println(pinCount);
// loop from the lowest pin to the highest:
for(int thisPin=0;thisPin<pinCount;thisPin=pinCount)
{
// turn the pin on:
digitalWrite(ledPins[thisPin],HIGH);
}
}
}
ใกล้จะได้แล้ว ลองอีกนิดใช้คำสั่ง if เช็คตามเงื่อนไขก็ทำได้แล้วครับ