Go Down

Topic: char and string variables for Morse Code sketch (Read 8630 times) previous topic - next topic


I'm trying to adapt Chris Weatherford's morse code sketch so that I can use the serial to input text for translation, rather than having to type it into the code and then reupload it.
original here: https://www.instructables.com/id/Arduino-Morse-Code/

In the original this is used to define the text for translating into morse
Code: [Select]
char stringToMorseCode[] = "Arduino Morse Code Project";

I thought I'd try read from the serial and store in a variable, then do something like this:

Code: [Select]

String reply; //define variable reply
int i;            //define variable i
int a;           // define variable a

void setup(){
Serial.begin(9600);                          //start serial
Serial.println("Write something: ");   //request text
while(Serial.available()==0){}         //wait for answer
String reply = Serial.readString();    //store answer as variable reply
a = reply.length();                          //measure string length
char stringToMorseCode[a] = reply; //use string reply for translating

The following error is returned.
" Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

In function 'void setup()':

11: error: array must be initialized with a brace-enclosed initializer

char stringToMorseCode[a] = reply; //use string reply for translating"

I have no idea what a brace-enclosed initializer is and googling has just led me further down the rabbit hole. Please can someone pull me out?

Why can't I replace a string "anything" with a string variable? If someone can see the problem, or see a simple way of replacing "" with a variable, I'd be extremely grateful. I've read what I can about the char() function and I just can't seem to get the hang of it, apparently.


Code: [Select]
char stringToMorseCode[a] = reply; //use string reply for translating

It's not really clear to me what you are trying to do here.
If you want a variable called stringToMorseCode, you don't want to be defining it here, a few light-metres before it goes out of scope.


Give this a try:

Code: [Select]

// from within your setup()
   char myMessage[100];
   int bytesRead;

   while(Serial.available()) {
      bytesRead = Serial.readBytesUntil('\n', myMessage, sizeof(myMessage) - 1);
      myMessage[bytesRead] =  '\0';    // Make it a string
      PlayTheString(myMessage);        // Use the input

This code reads what is typed into the Serial monitor until the Enter key is pressed. It will only accept up to 99 characters, reserving one byte for the null. Next we add the null to the array to make it a C string. (Note lowercase 's' in "string". I'm not a big fan of String objects.) Then you call whatever function you have written that "plays" the string in Morse. By passing the string to your decoder function, it uses the data before it goes out of scope, as AWOL mentioned.

Go Up