极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 11312|回复: 0

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

[复制链接]
发表于 2015-6-3 19:45:48 | 显示全部楼层 |阅读模式
第三行 char* letters[]这一段,会使用但有点不明就里。
letters[k]是指向第k个字符串的指针,比如说letters[0]指向".-\0",letters[4]指向".\0"
letters[k],k从0到25就是一个数组,数组元素就是上面所说的指针。
如此说来的话,这个数组是不是可以定义成 char letters[26][4]呢,如果这样应该怎么写?是不是比直接用 char * letters[]要浪费存储空间?

附:字符串数组
string str1 = "hello";
char *str1 = "hello"
char str1[6] = "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[ch-'a']);
    }
    else if (ch>='A' && ch<='Z')
    {
      flashSequence(letters[ch-'A']);
    }
    else if (ch>='0' && ch<='9')
    {
      flashSequence(numbers[ch-'0']);
    }
    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[i] != NULL)
  {
    flashDotOrDash(sequence[i]);
    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);
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-7 19:30 , Processed in 0.035971 second(s), 17 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表