pumpitup 发表于 2015-6-3 19:45:48

发一个教科书莫尔斯电码程序献丑。附数组问题一枚。

第三行 char* letters[]这一段,会使用但有点不明就里。
letters是指向第k个字符串的指针,比如说letters指向".-\0",letters指向".\0"
letters,k从0到25就是一个数组,数组元素就是上面所说的指针。
如此说来的话,这个数组是不是可以定义成 char letters呢,如果这样应该怎么写?是不是比直接用 char * letters[]要浪费存储空间?

附:字符串数组
string str1 = "hello";
char *str1 = "hello"
char str1 = "hello";
以上都正确?



const int ledPin = 2;
const int buzzPin = 3;
char* letters[]={
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", //ABCDEFG
"....", "..", ".---", "-.-", ".-..", "--", "-.", //HIJKLMN
"---", ".--.", "--.-", ".-.", "...", "-", //OPQRST
"..-", "...-", ".--", "-..-", "-.--", "--.." //UVWXYZ
};
char* numbers[]={
"-----",".----","..---","...--","....-", //01234
".....","-....","--...","---..","----." //56789
};
int dotDelay = 50;

void setup()
{
pinMode(ledPin,OUTPUT);
pinMode(buzzPin,OUTPUT);
Serial.begin(9600);
}

void loop()
{
char ch;
if (Serial.available())
{
    ch = Serial.read();
    if (ch>='a' && ch<='z')
    {
      flashSequence(letters);
    }
    else if (ch>='A' && ch<='Z')
    {
      flashSequence(letters);
    }
    else if (ch>='0' && ch<='9')
    {
      flashSequence(numbers);
    }
    else if (ch == ' ')
    {
      delay(dotDelay * 4);
    }
    else if (ch == '+')
    {
      dotDelay+=10;
      Serial.print("dotDelay is");
      Serial.println(dotDelay);
    }
    else if (ch == '-')
    {
      dotDelay-=10;
      dotDelay = (dotDelay>0)?dotDelay:10;
      Serial.print("dotDelay is");
      Serial.println(dotDelay);
    }
}
}
   
void flashSequence(char* sequence)
{
int i = 0;
while (sequence != NULL)
{
    flashDotOrDash(sequence);
    i++;
}
delay(dotDelay * 3);
}
   
void flashDotOrDash(char dotOrDash)
{
digitalWrite(ledPin,HIGH);
digitalWrite(buzzPin,HIGH);
if (dotOrDash == '.')
{
    delay(dotDelay);
}
else
{
    delay(dotDelay * 3);
}
digitalWrite(ledPin,LOW);
digitalWrite(buzzPin,LOW);
delay(dotDelay);
}
页: [1]
查看完整版本: 发一个教科书莫尔斯电码程序献丑。附数组问题一枚。