14 Replies - 37158 Views - Last Post: 07 August 2009 - 04:06 AM Rate Topic: -----

#1 Dandy1903  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 06-April 08

Sending ctrl-z through serial

Post icon  Posted 10 April 2008 - 07:02 AM

Hi all,

I'm writing a very simple program which uses AT commands to send a SMS via a GSM modem on my com port. I've managed to successfully communicate with the modem through my program (thanks for the "serial Port Comms in c#" tutorial :^: ) But one line is stumping me.
When you issue the command to write a text in HyperTerminal you get a '>' prompt in which you type your message and then press 'ctrl-z' to return to the command prompt. How do I do this in my program?
Any suggestions are much appreciated or anu pointers in the right direction will do nicely.
Here is a bit of my code to help understanding.....maybe!!!

Thanks

 
private void button1_Click(object sender, EventArgs e)
        {
            //Firstly set the modem to text mode
            serialPort1.Write("at+cmgf=1\r\n");
            //Now enter message writing mode to send an sms to the number below
            serialPort1.Write("at+cmgw=\"+447878xxxxxx\"\r\n");
            //Now send the contents of the message
            serialPort1.Write("Test message from coded program");  [b]At the end of this line I need ctrl-z[/b]
            //Now send the message stored at position 2
            serialPort1.Write("at+cmss=2\r\n");
        }


This post has been edited by PsychoCoder: 10 April 2008 - 07:10 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Sending ctrl-z through serial

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1641
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Sending ctrl-z through serial

Posted 10 April 2008 - 07:12 AM

Have a look at the SendKeys Class. This will allow you to simulate key presses, such as what you're looking for. Hope that helps :)
Was This Post Helpful? 0
  • +
  • -

#3 Dandy1903  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 06-April 08

Re: Sending ctrl-z through serial

Posted 13 April 2008 - 03:05 PM

View PostPsychoCoder, on 10 Apr, 2008 - 07:12 AM, said:

Have a look at the SendKeys Class. This will allow you to simulate key presses, such as what you're looking for. Hope that helps :)

OK so sendkeys does seem to describe exactly what I want to do. I've managed to put the correct code as far as syntax is concerned into my program and it builds ok. Unfortunately it doesn't appear to do anything and my next command tags itself onto the end of the message as I've not escaped from the message writing yet.
I suspect I need to somehow tell it that the sendkeys command is meant for the serial port, can I do this? I read I think that it is only for the "active application" so is this stopping me? I've also tried putting the sendkeys command on the end of the message line but it still appears to do nothing.
Whilst I wait for any advice I'm going to look at the char command as I seem to have noted the ascii code for shift-z as 26 so maybe I can use that to send it.
Thanks again folks.

[code]
private void button1_Click(object sender, EventArgs e)
{
//Firstly set the modem to text mode
serialPort1.Write("at+cmgf=1\r\n");
//Now enter message writing mode to send an sms to the number below
serialPort1.Write("at+cmgw=\"+447878409893\"\r\n");
//Now send the contents of the message
serialPort1.Write("Test message from coded program");
SendKeys.Send("^(z)");
//Now send the message stored at position 2
serialPort1.Write("at+cmss=4\r\n");
}
Was This Post Helpful? 0
  • +
  • -

#4 egnuke  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 10-August 08

Re: Sending ctrl-z through serial

Posted 11 August 2008 - 12:47 AM

I'm doing the same project in C#
I can use hyperterminal to send AT commands to the mobile to send sms.
but when i tried doing it through C#, it didn't work.
I tried your code and didn't work too.

Unfortunately, my PC has a single serial port, so i couldn't redirect the output to hyperterminal for debugging.

Is it possible to send me your source code or help me figure out what's wrong with mine ?

I used the default values for the serial port component (9600 BaudRate, 8 DataBits (tried 7 too), etc...)

View PostDandy1903, on 13 Apr, 2008 - 03:05 PM, said:

OK so sendkeys does seem to describe exactly what I want to do. I've managed to put the correct code as far as syntax is concerned into my program and it builds ok. Unfortunately it doesn't appear to do anything and my next command tags itself onto the end of the message as I've not escaped from the message writing yet.
I suspect I need to somehow tell it that the sendkeys command is meant for the serial port, can I do this? I read I think that it is only for the "active application" so is this stopping me? I've also tried putting the sendkeys command on the end of the message line but it still appears to do nothing.
Whilst I wait for any advice I'm going to look at the char command as I seem to have noted the ascii code for shift-z as 26 so maybe I can use that to send it.
Thanks again folks.

[code]
private void button1_Click(object sender, EventArgs e)
{
//Firstly set the modem to text mode
serialPort1.Write("at+cmgf=1\r\n");
//Now enter message writing mode to send an sms to the number below
serialPort1.Write("at+cmgw=\"+447878409893\"\r\n");
//Now send the contents of the message
serialPort1.Write("Test message from coded program");
SendKeys.Send("^(z)");
//Now send the message stored at position 2
serialPort1.Write("at+cmss=4\r\n");
}

Was This Post Helpful? 0
  • +
  • -

#5 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Sending ctrl-z through serial

Posted 11 August 2008 - 07:25 PM

View PostDandy1903, on 13 Apr, 2008 - 03:05 PM, said:

View PostPsychoCoder, on 10 Apr, 2008 - 07:12 AM, said:

Have a look at the SendKeys Class. This will allow you to simulate key presses, such as what you're looking for. Hope that helps :)

OK so sendkeys does seem to describe exactly what I want to do. I've managed to put the correct code as far as syntax is concerned into my program and it builds ok. Unfortunately it doesn't appear to do anything and my next command tags itself onto the end of the message as I've not escaped from the message writing yet.
I suspect I need to somehow tell it that the sendkeys command is meant for the serial port, can I do this? I read I think that it is only for the "active application" so is this stopping me? I've also tried putting the sendkeys command on the end of the message line but it still appears to do nothing.
Whilst I wait for any advice I'm going to look at the char command as I seem to have noted the ascii code for shift-z as 26 so maybe I can use that to send it.
Thanks again folks.

private void button1_Click(object sender, EventArgs e)
        {
            //Firstly set the modem to text mode
            serialPort1.Write("at+cmgf=1\r\n");
            //Now enter message writing mode to send an sms to the number below
            serialPort1.Write("at+cmgw=\"+447878409893\"\r\n");
            //Now send the contents of the message
            serialPort1.Write("Test message from coded program");
            SendKeys.Send("^(z)");
            //Now send the message stored at position 2
            serialPort1.Write("at+cmss=4\r\n");
        }



The String objects store Unicode characters so we need to add a Unicode ^Z to the string being written.
To do this add a Unicode escape sequence character, in this case \u001F, to the string. The serialport
class defaults to ASCII encoding so hopefully will convert the string correctly. :)

//Now send the contents of the message
serialPort1.Write("Test message from coded program\u001F");



You could instead create a string with just the ^Z in it and concatenate the strings:

string controlZ = "\u001F";

//Now send the contents of the message
serialPort1.Write("Test message from coded program" + controlZ);



HTH,

Jeff

This post has been edited by n8wxs: 11 August 2008 - 09:12 PM

Was This Post Helpful? 0
  • +
  • -

#6 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Sending ctrl-z through serial

Posted 11 August 2008 - 08:35 PM

Discovered the "edit" button.

Nevermind.

:)

This post has been edited by n8wxs: 11 August 2008 - 08:53 PM

Was This Post Helpful? 0
  • +
  • -

#7 egnuke  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 10-August 08

Re: Sending ctrl-z through serial

Posted 12 August 2008 - 03:03 AM

Thanks for the help. I didn't know about the \u001F.

but my code still doesn't work :(

if(!serialPort1.IsOpen)
            {
                serialPort1.Open();
            }

            //set the modem to text mode
            serialPort1.Write("at+cmgf=1\r\n");
            //Now enter message writing mode to send an sms to the number below
            serialPort1.Write("at+cmgs=\"**PhoneNumber**\"\r\n");
            //Now send the contents of the message
            serialPort1.Write("Test message from coded program\u001F");

when i write that directly in heyperterminal, the sms is sent, but when i use the above C# code, it doesn't.
also, i tried to read the return from serial port, but it doesn't return anything
char[] RecievedBytes = new char[1];
serialPort1.Read(RecievedBytes, 0, 1);

here is a screenshot of my SerialPort1 properties:
Posted Image

and here is a screenshot of the hyperterminal settings that work:
Posted Image

I also tried using SerialPort1.WriteLine() instead of sending \r\n but it didn't make any difference.

View Postn8wxs, on 11 Aug, 2008 - 07:25 PM, said:

The String objects store Unicode characters so we need to add a Unicode ^Z to the string being written.
To do this add a Unicode escape sequence character, in this case \u001F, to the string. The serialport
class defaults to ASCII encoding so hopefully will convert the string correctly. :)

//Now send the contents of the message
serialPort1.Write("Test message from coded program\u001F");



You could instead create a string with just the ^Z in it and concatenate the strings:

string controlZ = "\u001F";

//Now send the contents of the message
serialPort1.Write("Test message from coded program" + controlZ);



HTH,

Jeff

Was This Post Helpful? 0
  • +
  • -

#8 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Sending ctrl-z through serial

Posted 12 August 2008 - 06:17 PM

View PostDandy1903, on 10 Apr, 2008 - 07:02 AM, said:

Hi all,

I'm writing a very simple program which uses AT commands to send a SMS via a GSM modem on my com port. I've managed to successfully communicate with the modem through my program (thanks for the "serial Port Comms in c#" tutorial :^: ) But one line is stumping me.
When you issue the command to write a text in HyperTerminal you get a '>' prompt in which you type your message and then press 'ctrl-z' to return to the command prompt. How do I do this in my program?
Any suggestions are much appreciated or anu pointers in the right direction will do nicely.
Here is a bit of my code to help understanding.....maybe!!!

Thanks

 
private void button1_Click(object sender, EventArgs e)
        {
            //Firstly set the modem to text mode
            serialPort1.Write("at+cmgf=1\r\n");
            //Now enter message writing mode to send an sms to the number below
            serialPort1.Write("at+cmgw=\"+447878xxxxxx\"\r\n");
            //Now send the contents of the message
            serialPort1.Write("Test message from coded program");  [b]At the end of this line I need ctrl-z[/b]
            //Now send the message stored at position 2
            serialPort1.Write("at+cmss=2\r\n");
        }



I read your description above to say the modem is prompting (>) for the text to send. It
requires the ^Z to terminate the text entry mode.

Your modified button1_click() method, with the embedded ^Z, is probably working
correctly. But, the modem is not ready to receive your text input because you are
not waiting for its ">" prompt before transmitting the text string. The modem is
interpreting the characters in the text as commands/data since it is still in command
mode and has not completed the switch to text entry mode. Any illegal command will
abort the setup you have already provided.

Using hyperterm, you are self-synchronizing because you are waiting for the ">"
prompt. B)

You need to add receive methods and synchronize sending your text message with the
modem.

Jeff
Was This Post Helpful? 0
  • +
  • -

#9 egnuke  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 10-August 08

Re: Sending ctrl-z through serial

Posted 12 August 2008 - 10:37 PM

View Postn8wxs, on 12 Aug, 2008 - 06:17 PM, said:

I read your description above to say the modem is prompting (>) for the text to send. It
requires the ^Z to terminate the text entry mode.

Your modified button1_click() method, with the embedded ^Z, is probably working
correctly. But, the modem is not ready to receive your text input because you are
not waiting for its ">" prompt before transmitting the text string. The modem is
interpreting the characters in the text as commands/data since it is still in command
mode and has not completed the switch to text entry mode. Any illegal command will
abort the setup you have already provided.

Using hyperterm, you are self-synchronizing because you are waiting for the ">"
prompt. B)

You need to add receive methods and synchronize sending your text message with the
modem.

Jeff


Actually, i have a thread listening to the serial port all the time but it never received anything (it should receive OK or ERROR if the commands are correct. AT modems don't reply if the command is not recognized)
void SerialPortListen()
        {
            char[] RecievedChars = new char[1];
            serialPort1.Read(RecievedChars, 0, 1);
            textBox1.Text += RecievedChars.ToString();
            SerialPortThread = new Thread(threadst);
        }


I also tried inserting the above code right after the first SerialPort1.Write() call, but it waited forever for the read.
Was This Post Helpful? 0
  • +
  • -

#10 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Sending ctrl-z through serial

Posted 13 August 2008 - 04:01 PM

Quote

Actually, i have a thread listening to the serial port all the time but it never received anything


You need to fix this first.
Was This Post Helpful? 0
  • +
  • -

#11 alcidesppn  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 30-September 08

Re: Sending ctrl-z through serial

Posted 30 September 2008 - 04:25 PM

View Postn8wxs, on 13 Aug, 2008 - 04:01 PM, said:

Quote

Actually, i have a thread listening to the serial port all the time but it never received anything


You need to fix this first.

I´m Brazilian and I´m not good in english. I´m writing my program using C++ Builder 6 to use AT commands to send a SMS via a GSM modem too.
I can read the modem but I have the same problem when I try to send a message. The modem returns the ">" but I couldn't write and send the message yet.
This is my program:

"//---------------------------------------------------------------------------
#include <vcl.h>
#include <vcl\registry.hpp> //Para TRegistry.
#include<mmsystem.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
#define LEN_BUFFER  100  //Tamanho do Buffer.
//---------------------------------------------------------------------------
//Variáveis e objetos Globais
//---------------------------------------------------------------------------
TForm1 *Form1;
TMultLinha *MultLinha;
//Variáveis da API
HANDLE hCom;
DCB dcb;
COMMTIMEOUTS CommTimeouts;
//---------------------------
bool GLBEnviaDados = false;     //Para habilitar/desabilitar o envio de dados pela serial.
String StrComandos;             //Armazena a string de comando lida da Serial.
String teste2;
char teste[LEN_BUFFER];
char BufferRecebe[LEN_BUFFER];  //Buffer temporário para trabalhar direto com ReadFile().
char AuxProtocoloRX[LEN_BUFFER]="0000000000";
bool GLB_Conectado = false; //Indica se a porta já está aberta.
//-------------------------
AnsiString StrMens;
int tama;
String ProtocoloRX, ControleMsg;
String Data, Hora, Origem, Destino, Mensagem, numero;
bool ChegouMsg=false, x=false,Modem=false;
int count=0,FSelPos;
int i=0;
bool a=true;

//--------------------------------------------------------------------------
//Declaração das funções
bool LeDados(char* EntradaDados, unsigned int TamBuffer,unsigned long& TotalLidos);
bool EscreveDados(char* outputData,const unsigned int sizeBuffer,unsigned long& length);
bool AbrirPorta(char *NomePorta);
void MostraNomesCom(void); //Mostra os nomes das portas "COM" instaladas no sistema num ComboBox.
bool ConfiguraControle(void);
bool ConfiguraTimeOuts(void);
void AvisoSonoro(String);
AnsiString __fastcall DataHora(void);
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
    ComboBoxPorta->ItemIndex = 0; //Seleciona a porta COM1. 1=COM2; 2=COM3;
    dcb.BaudRate = CBR_9600;      //bps (Velocidade).
    dcb.ByteSize = 8;             //8 Bits de dados.
    dcb.Parity = NOPARITY;        //Sem paridade.
    dcb.StopBits = ONESTOPBIT;    //1 stop bit.
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{
   memset( BufferRecebe, 0, LEN_BUFFER);  //Limpa o buffer.
   MostraNomesCom(); //Mostra os nomes das portas "COM" num FilterComboBox.
   MultLinha = new TMultLinha(true); //Aloca memória para o objeto.
   MultLinha->Priority = tpHigher; //Define a prioridade.
   Memo3->Lines->LoadFromFile("Mensagem recebida.txt");
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
   MultLinha->Terminate();
   MultLinha = NULL;
   delete MultLinha;
   if( GLB_Conectado )
     CloseHandle(hCom);
   Memo3->Lines->Add("");
   Memo3->Lines->Add("Ultimo acesso ao arquivo:  " + TDateTime::CurrentDateTime().DateString() + " as " + TDateTime::CurrentDateTime().TimeString());
   Memo3->Lines->SaveToFile("Mensagem recebida.txt");
}
//---------------------------------------------------------------------------
__fastcall TMultLinha::TMultLinha(bool CreateSuspended) : TThread(CreateSuspended)
{
}
//--------------------------------------------------------------------------
//Mostra os nomes das portas "COM" instaladas no sistema num ComboBox.
//--------------------------------------------------------------------------
void  MostraNomesCom(void)
{
    TRegistry *Registro = new TRegistry; //Cria e aloca espaço na memória para o objeto.
    TStringList *Lista = new TStringList; //Cria e aloca espaço na memória para o objeto.

    Registro->RootKey = HKEY_LOCAL_MACHINE; //Define chave raiz.
    Registro->OpenKey("HARDWARE\\DEVICEMAP\\SERIALCOMM", false); //Abre a chave.
    //Obtém uma string contendo todos os nomes de valores associados com a chave atual.
    Registro->GetValueNames(Lista);
    //Count é a quantidade de portas existentes.
    for(int indice=0; indice <= Lista->Count-1; indice++)
       //Pega nos nomes das portas.
       Form1->ComboBoxPorta->Items->Add(Registro->ReadString( Lista->Strings[indice] ));

     //Adciona os nomes das porta no ComboBox1.
     if (Form1->ComboBoxPorta->Items->Count > 0)
        Form1->ComboBoxPorta->ItemIndex = 0; //Exibir o primeino nome da porta.
    Lista->Free();
    Registro->CloseKey();
    Registro->Free(); //Libera memória alocada anteriormente pelo objeto Registro.
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SpeedAbrirPortaClick(TObject *Sender)
{
   bool Sucesso;
   if(AbrirPorta(ComboBoxPorta->Text.c_str()) == true)
   {
      GLB_Conectado = true;
      Sucesso = ConfiguraControle();
      Sucesso = ConfiguraTimeOuts();

      if(Sucesso == false)
      {
          GLB_Conectado = false;
          CloseHandle(hCom);
          //FormAviso->ShowModal();
      }else{
          SpeedAbrirPorta->Enabled = false;
          SpeedFecharPorta->Enabled = true;
          ComboBoxPorta->Enabled = false;
          MultLinha->Resume(); //Inicia processo.
          Modem = true;
      }
   }else{
      GLB_Conectado = false;
      //FormAviso->ShowModal();
   }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SpeedFecharPortaClick(TObject *Sender)
{
   SpeedFecharPorta->Enabled = false;
   SpeedAbrirPorta->Enabled = true;
   ComboBoxPorta->Enabled = true;
   GLB_Conectado = false;
   CloseHandle(hCom);
}
//--------------------------------------------------------------------------
bool EscreveDados(char* outputData,const unsigned int sizeBuffer,unsigned long& length)
{
    if(WriteFile(hCom, outputData, sizeBuffer, &length,NULL) == 0)
    {
      return false;
    }
    return true;
}
//--------------------------------------------------------------------------
//Mostra string de forma sincronizada.
void __fastcall TMultLinha::MostraString(void)
{
        //AnsiString StrApresentacao = "Sistema Remoto de Mensagem SMS\n\n";
        //AnsiString StrOrigem = "Mensagem Recebida de: ";
        //AnsiString StrData = "\nData: ";
        //AnsiString StrHora = "\nHora: ";
        //AnsiString StrMensagem = "\nMensagem:\n";
        //Form1->Memo1->SetSelTextBuf(StrComandos.c_str());

        if(ControleMsg == "+CMT:")
        {
                //MessageBeep(0);
                AvisoSonoro("OK");
                //ShowMessage(StrApresentacao + StrOrigem + Origem + StrData + Data + StrHora + Hora + StrMensagem);
                //WinExec("calc.exe", SW_SHOW);
        }
}
//--------------------------------------------------------------------------
//FUNÇÃO PRINCIPAL
//--------------------------------------------------------------------------
void __fastcall TMultLinha::Execute()
{
    unsigned int cont=0;
    DWORD BytesEscritos;  //Para armazenar a quantidade de dados escritos.
    DWORD BytesLidos;     //Para armazenar a quantidade de dados lidos.

    FreeOnTerminate = true; //O objeto é destruído automaticamente quando a Thead terminar.

    while(!Terminated) //loop infinito. Vida do programa.
    {
      if(GLB_Conectado == true) //Se está conectado.
      {
        if(ReadFile( hCom, BufferRecebe, LEN_BUFFER, &BytesLidos, NULL) != 0 )
        {
            cont = 0;
            if(BytesLidos > 0) //Se algum caracter foi lido.
            {
              BufferRecebe[BytesLidos] = '\0';  //Finaliza string.
              StrComandos += BufferRecebe; //Vai guardando o que recebeu na variável StrComandos.
              Form1->Memo1->Lines->Add(StrComandos);


              while(cont < BytesLidos)
              {
                 if(BufferRecebe[cont] != '\r' && BufferRecebe[cont] != '\n'){
                        teste[i] = BufferRecebe[cont];
                        teste2 = teste[i];
                        Form1->Memo3->Lines->Add(teste2);
                 }

                 i++;
                  //Verifica se é o final da string. Quaisquer um dos caracteres '\n' ou '\0' finaliza a string.
                  if(BufferRecebe[cont] == '\0' || BufferRecebe[cont] == '\n')
                  {
                        strcpy(AuxProtocoloRX,StrComandos.c_str());
                        AuxProtocoloRX[StrComandos.Length()-2] = '\0';
                        ProtocoloRX = AuxProtocoloRX;
                        StrComandos = "\0";
                        BufferRecebe[cont] = '\0';
                  }
                  /*
                  if(BufferRecebe[cont] == '\n' || BufferRecebe[cont] == '\0') //Finalizador de string.
                  {
                     strcpy(AuxProtocoloRX,StrComandos.c_str());
                     AuxProtocoloRX[StrComandos.Length()-2] = '\0';
                     ProtocoloRX = AuxProtocoloRX;
                     //Form1->Memo1->Lines->Add(ProtocoloRX);
                     if(StrComandos.SubString(3,5) == "+CMT:"){

                        //ControleMsg = StrComandos.SubString(3,5); //Informação que verifica se chegou mensagem: +CMT:
                        //Data = StrComandos.SubString(25,8);
                        //Hora = StrComandos.SubString(34,8);
                        //Origem = StrComandos.SubString(10,11);
                        //Form1->Memo3->Lines->Add(ControleMsg+Data+Hora+Origem);
                        }
                     Synchronize(MostraString); //Mostra string de forma sincronizada.


                  }
                  */
                  cont++;
              }
              count=0;
            }
         }
         if(Modem == true) {
                Modem = false;[b]
                StrMens = "AT&K0\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
                StrMens = "AT\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
                StrMens = "AT\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
                /*StrMens = "ATE0\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);*/
                StrMens = "AT+CMGF=1\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
                StrMens = "AT+CNMI=,2\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
         }

         if(GLBEnviaDados == true)
         {
            GLBEnviaDados = false;

            if(Form1->RadioButton1->Checked == true) {
                if(Form1->Memo2->Lines->Count > 0){
                        StrMens = Form1->Memo2->Text;
                        StrMens += "\r\n";
                        Form1->Memo2->Clear();
                        Form1->Memo2->SetFocus();
                        tama = StrMens.Length();
                        EscreveDados(StrMens.c_str(), tama, BytesEscritos);}}

            if(Form1->RadioButton2->Checked == true && x==true) {
                x=false;

                if(Form1->RadioButton2->Checked == true)
                        numero = Form1->Edit1->Text;
                StrMens = "AT+CMGS=\"81105794\",129\n\r";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Sleep(1500);
                Form1->Label5->Caption = StrMens;
                StrMens = Form1->Memo2->Text;
                StrMens += "";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Sleep(1500);[/b]
                }
         }
     }else{
        Sleep(1); //Necessário para não travar processo.
     }
   }
}
//--------------------------------------------------------------------------
//DEFINE TIMEOUTs
bool ConfiguraTimeOuts(void)
{
   if( GetCommTimeouts(hCom, &CommTimeouts) == 0 )
   {
      return false;
   }
   CommTimeouts.ReadIntervalTimeout = 2;
   CommTimeouts.ReadTotalTimeoutMultiplier = 0;
   CommTimeouts.ReadTotalTimeoutConstant = 2;
   CommTimeouts.WriteTotalTimeoutMultiplier = 5;
   CommTimeouts.WriteTotalTimeoutConstant = 5;

   if( SetCommTimeouts(hCom, &CommTimeouts) == 0 )
   {
      return false;
   }
   return true;
}
//--------------------------------------------------------------------------
//CONFIGURA PORTA SERIAL.
bool ConfiguraControle(void)
{
   if(!GetCommState(hCom, &dcb))
   {
      return false;
   }
   dcb.BaudRate = CBR_9600;
   dcb.ByteSize = 8;
   dcb.Parity = NOPARITY;
   dcb.StopBits = ONESTOPBIT;

   if( SetCommState(hCom, &dcb) == 0 )
   {
      return false;
   }
   return true;
}
//--------------------------------------------------------------------------
//Abre a Porta Serial COMx
bool AbrirPorta(char *NomePorta)
{
   hCom = CreateFile(
             NomePorta,
             GENERIC_READ | GENERIC_WRITE,
             0, // dispositivos comm abertos com acesso exclusivo
             NULL, // sem atributos de segurança
             OPEN_EXISTING, // deve usar OPEN_EXISTING
             0, //Entrada e saída sem ovelap.
             NULL // hTemplate deve ser NULL para comm
          );
   if(hCom == INVALID_HANDLE_VALUE)
   {
      return false;
   }
   return true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
        Close();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
        Memo1->Clear();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
    GLBEnviaDados = true;
    x=true;
}
//---------------------------------------------------------------------------
void AvisoSonoro(String var)
{
        if(var == "ERROR")
                sndPlaySound("error.wav",SND_ASYNC);
        if(var == "OK")
                sndPlaySound("ok.wav",SND_ASYNC);
}
void __fastcall TForm1::Memo2KeyPress(TObject *Sender, char &Key)
{
        //Form1->KeyPress(0x23);
        /*
        if(Key = 0x23)
        {
                if(Form1->Memo2->Lines->Count > 0) {
                GLBEnviaDados = true;
                Memo2->SetFocus(); }
        }
        */

}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormActivate(TObject *Sender)
{
        //ShowWindow(Application->Handle, SW_HIDE);
        //WindowState = 1;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
        Memo2->Clear();        
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RadioButton2Click(TObject *Sender)
{
        Form1->Edit1->Enabled = true;
        Edit1->Text = "";
        Edit1->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::RadioButton1Click(TObject *Sender)
{
        Form1->Edit1->Enabled = false;
        Edit1->Text = "";
        Memo2->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::RadioButton3Click(TObject *Sender)
{
       Form1->Edit1->Enabled = true;
       Edit1->Text = "9090";
       Edit1->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button8Click(TObject *Sender)
{
        Memo3->Clear();        
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button7Click(TObject *Sender)
{
        Memo3->ReadOnly = false;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button9Click(TObject *Sender)
{
        Memo3->Lines->Add("Mensagem recebida");
        Memo3->Lines->SaveToFile("Mensagem recebida.txt");
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button10Click(TObject *Sender)
{
     Memo3->Lines->SaveToFile("Mensagem recebida.txt");

}
//---------------------------------------------------------------------------
void __fastcall TForm1::Salvarcomo1Click(TObject *Sender)
{
        if(SaveDialog1->Execute())
        {
                Memo3->Lines->SaveToFile(SaveDialog1->FileName);
        }
        else
                MessageBeep(0);        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button6Click(TObject *Sender)
{
     FSelPos = 0;
     FindDialog1->Execute();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button11Click(TObject *Sender)
{
        TPrinter *Prntr = Printer();

        if(PrintDialog1->Execute())
        {
        TRect r = Rect(200, 200, Prntr->PageWidth - 200, Prntr->PageHeight- 200);
        Prntr->BeginDoc();
        //Graphics::TBitmap *BMP = new Graphics::TBitmap();
        //BMP->LoadFromFile("logo.bmp");
        //Printer()->Canvas->Draw(100,50,BMP);        //(coluna,linha)
        Printer()->Canvas->Font->Size = 12;
        Printer()->Canvas->Font->Name = "MS Sans Serif";
        Printer()->Canvas->Font->Color = clBlack;
        Printer()->Canvas->Font->Style = Printer()->Canvas->Font->Style << fsBold;
        //Printer()->Canvas->TextOut(450, 100, "RELATÓRIO (Informações de Sistemas)");

        for(int i = 0; i < Memo3->Lines->Count; i++)
        {
                Printer()->Canvas->Font->Size = 8;
                Printer()->Canvas->Font->Name = "MS Sans Serif";
                Printer()->Canvas->Font->Color = clBlack;
                Printer()->Canvas->Font->Style = Printer()->Canvas->Font->Style;
                Prntr->Canvas->TextOut(135, 300 + (i *
                Prntr->Canvas->TextHeight(Memo3->Lines->Strings[i])),
                Memo3->Lines->Strings[i]);
        }

        //Prntr->Canvas->Brush->Color = clBlack;
        Prntr->Canvas->FrameRect®;
        Prntr->EndDoc();
        }

}
//---------------------------------------------------------------------------
AnsiString __fastcall DataHora(void)
{
  return(TDateTime::CurrentDateTime().DateString()+" às "+TDateTime::CurrentDateTime().TimeString());
}
void __fastcall TForm1::Salvar1Click(TObject *Sender)
{
        Memo3->Lines->SaveToFile("Mensagem recebida.txt");
}
//---------------------------------------------------------------------------
"

Was This Post Helpful? 0
  • +
  • -

#12 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1382
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Re: Sending ctrl-z through serial

Posted 30 September 2008 - 04:40 PM

1) You'd be best off creating a new thread, this thread is ages old.

2) Please :code: in future.
Was This Post Helpful? 0
  • +
  • -

#13 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Sending ctrl-z through serial

Posted 30 September 2008 - 09:44 PM

View Postalcidesppn, on 30 Sep, 2008 - 04:25 PM, said:

I´m Brazilian and I´m not good in english. I´m writing my program using C++ Builder 6 to use AT commands to send a SMS via a GSM modem too.
I can read the modem but I have the same problem when I try to send a message. The modem returns the ">" but I couldn't write and send the message yet.
This is my program:

"//---------------------------------------------------------------------------
#include <vcl.h>
#include <vcl\registry.hpp> //Para TRegistry.
#include<mmsystem.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
#define LEN_BUFFER  100  //Tamanho do Buffer.
//---------------------------------------------------------------------------
//Variáveis e objetos Globais
//---------------------------------------------------------------------------
TForm1 *Form1;
TMultLinha *MultLinha;
//Variáveis da API
HANDLE hCom;
DCB dcb;
COMMTIMEOUTS CommTimeouts;
//---------------------------
bool GLBEnviaDados = false;     //Para habilitar/desabilitar o envio de dados pela serial.
String StrComandos;             //Armazena a string de comando lida da Serial.
String teste2;
char teste[LEN_BUFFER];
char BufferRecebe[LEN_BUFFER];  //Buffer temporário para trabalhar direto com ReadFile().
char AuxProtocoloRX[LEN_BUFFER]="0000000000";
bool GLB_Conectado = false; //Indica se a porta já está aberta.
//-------------------------
AnsiString StrMens;
int tama;
String ProtocoloRX, ControleMsg;
String Data, Hora, Origem, Destino, Mensagem, numero;
bool ChegouMsg=false, x=false,Modem=false;
int count=0,FSelPos;
int i=0;
bool a=true;

//--------------------------------------------------------------------------
//Declaração das funções
bool LeDados(char* EntradaDados, unsigned int TamBuffer,unsigned long& TotalLidos);
bool EscreveDados(char* outputData,const unsigned int sizeBuffer,unsigned long& length);
bool AbrirPorta(char *NomePorta);
void MostraNomesCom(void); //Mostra os nomes das portas "COM" instaladas no sistema num ComboBox.
bool ConfiguraControle(void);
bool ConfiguraTimeOuts(void);
void AvisoSonoro(String);
AnsiString __fastcall DataHora(void);
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
    ComboBoxPorta->ItemIndex = 0; //Seleciona a porta COM1. 1=COM2; 2=COM3;
    dcb.BaudRate = CBR_9600;      //bps (Velocidade).
    dcb.ByteSize = 8;             //8 Bits de dados.
    dcb.Parity = NOPARITY;        //Sem paridade.
    dcb.StopBits = ONESTOPBIT;    //1 stop bit.
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{
   memset( BufferRecebe, 0, LEN_BUFFER);  //Limpa o buffer.
   MostraNomesCom(); //Mostra os nomes das portas "COM" num FilterComboBox.
   MultLinha = new TMultLinha(true); //Aloca memória para o objeto.
   MultLinha->Priority = tpHigher; //Define a prioridade.
   Memo3->Lines->LoadFromFile("Mensagem recebida.txt");
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
   MultLinha->Terminate();
   MultLinha = NULL;
   delete MultLinha;
   if( GLB_Conectado )
     CloseHandle(hCom);
   Memo3->Lines->Add("");
   Memo3->Lines->Add("Ultimo acesso ao arquivo:  " + TDateTime::CurrentDateTime().DateString() + " as " + TDateTime::CurrentDateTime().TimeString());
   Memo3->Lines->SaveToFile("Mensagem recebida.txt");
}
//---------------------------------------------------------------------------
__fastcall TMultLinha::TMultLinha(bool CreateSuspended) : TThread(CreateSuspended)
{
}
//--------------------------------------------------------------------------
//Mostra os nomes das portas "COM" instaladas no sistema num ComboBox.
//--------------------------------------------------------------------------
void  MostraNomesCom(void)
{
    TRegistry *Registro = new TRegistry; //Cria e aloca espaço na memória para o objeto.
    TStringList *Lista = new TStringList; //Cria e aloca espaço na memória para o objeto.

    Registro->RootKey = HKEY_LOCAL_MACHINE; //Define chave raiz.
    Registro->OpenKey("HARDWARE\\DEVICEMAP\\SERIALCOMM", false); //Abre a chave.
    //Obtém uma string contendo todos os nomes de valores associados com a chave atual.
    Registro->GetValueNames(Lista);
    //Count é a quantidade de portas existentes.
    for(int indice=0; indice <= Lista->Count-1; indice++)
       //Pega nos nomes das portas.
       Form1->ComboBoxPorta->Items->Add(Registro->ReadString( Lista->Strings[indice] ));

     //Adciona os nomes das porta no ComboBox1.
     if (Form1->ComboBoxPorta->Items->Count > 0)
        Form1->ComboBoxPorta->ItemIndex = 0; //Exibir o primeino nome da porta.
    Lista->Free();
    Registro->CloseKey();
    Registro->Free(); //Libera memória alocada anteriormente pelo objeto Registro.
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SpeedAbrirPortaClick(TObject *Sender)
{
   bool Sucesso;
   if(AbrirPorta(ComboBoxPorta->Text.c_str()) == true)
   {
      GLB_Conectado = true;
      Sucesso = ConfiguraControle();
      Sucesso = ConfiguraTimeOuts();

      if(Sucesso == false)
      {
          GLB_Conectado = false;
          CloseHandle(hCom);
          //FormAviso->ShowModal();
      }else{
          SpeedAbrirPorta->Enabled = false;
          SpeedFecharPorta->Enabled = true;
          ComboBoxPorta->Enabled = false;
          MultLinha->Resume(); //Inicia processo.
          Modem = true;
      }
   }else{
      GLB_Conectado = false;
      //FormAviso->ShowModal();
   }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SpeedFecharPortaClick(TObject *Sender)
{
   SpeedFecharPorta->Enabled = false;
   SpeedAbrirPorta->Enabled = true;
   ComboBoxPorta->Enabled = true;
   GLB_Conectado = false;
   CloseHandle(hCom);
}
//--------------------------------------------------------------------------
bool EscreveDados(char* outputData,const unsigned int sizeBuffer,unsigned long& length)
{
    if(WriteFile(hCom, outputData, sizeBuffer, &length,NULL) == 0)
    {
      return false;
    }
    return true;
}
//--------------------------------------------------------------------------
//Mostra string de forma sincronizada.
void __fastcall TMultLinha::MostraString(void)
{
        //AnsiString StrApresentacao = "Sistema Remoto de Mensagem SMS\n\n";
        //AnsiString StrOrigem = "Mensagem Recebida de: ";
        //AnsiString StrData = "\nData: ";
        //AnsiString StrHora = "\nHora: ";
        //AnsiString StrMensagem = "\nMensagem:\n";
        //Form1->Memo1->SetSelTextBuf(StrComandos.c_str());

        if(ControleMsg == "+CMT:")
        {
                //MessageBeep(0);
                AvisoSonoro("OK");
                //ShowMessage(StrApresentacao + StrOrigem + Origem + StrData + Data + StrHora + Hora + StrMensagem);
                //WinExec("calc.exe", SW_SHOW);
        }
}
//--------------------------------------------------------------------------
//FUNÇÃO PRINCIPAL
//--------------------------------------------------------------------------
void __fastcall TMultLinha::Execute()
{
    unsigned int cont=0;
    DWORD BytesEscritos;  //Para armazenar a quantidade de dados escritos.
    DWORD BytesLidos;     //Para armazenar a quantidade de dados lidos.

    FreeOnTerminate = true; //O objeto é destruído automaticamente quando a Thead terminar.

    while(!Terminated) //loop infinito. Vida do programa.
    {
      if(GLB_Conectado == true) //Se está conectado.
      {
        if(ReadFile( hCom, BufferRecebe, LEN_BUFFER, &BytesLidos, NULL) != 0 )
        {
            cont = 0;
            if(BytesLidos > 0) //Se algum caracter foi lido.
            {
              BufferRecebe[BytesLidos] = '\0';  //Finaliza string.
              StrComandos += BufferRecebe; //Vai guardando o que recebeu na variável StrComandos.
              Form1->Memo1->Lines->Add(StrComandos);


              while(cont < BytesLidos)
              {
                 if(BufferRecebe[cont] != '\r' && BufferRecebe[cont] != '\n'){
                        teste[i] = BufferRecebe[cont];
                        teste2 = teste[i];
                        Form1->Memo3->Lines->Add(teste2);
                 }

                 i++;
                  //Verifica se é o final da string. Quaisquer um dos caracteres '\n' ou '\0' finaliza a string.
                  if(BufferRecebe[cont] == '\0' || BufferRecebe[cont] == '\n')
                  {
                        strcpy(AuxProtocoloRX,StrComandos.c_str());
                        AuxProtocoloRX[StrComandos.Length()-2] = '\0';
                        ProtocoloRX = AuxProtocoloRX;
                        StrComandos = "\0";
                        BufferRecebe[cont] = '\0';
                  }
                  /*
                  if(BufferRecebe[cont] == '\n' || BufferRecebe[cont] == '\0') //Finalizador de string.
                  {
                     strcpy(AuxProtocoloRX,StrComandos.c_str());
                     AuxProtocoloRX[StrComandos.Length()-2] = '\0';
                     ProtocoloRX = AuxProtocoloRX;
                     //Form1->Memo1->Lines->Add(ProtocoloRX);
                     if(StrComandos.SubString(3,5) == "+CMT:"){

                        //ControleMsg = StrComandos.SubString(3,5); //Informação que verifica se chegou mensagem: +CMT:
                        //Data = StrComandos.SubString(25,8);
                        //Hora = StrComandos.SubString(34,8);
                        //Origem = StrComandos.SubString(10,11);
                        //Form1->Memo3->Lines->Add(ControleMsg+Data+Hora+Origem);
                        }
                     Synchronize(MostraString); //Mostra string de forma sincronizada.


                  }
                  */
                  cont++;
              }
              count=0;
            }
         }
         if(Modem == true) {
                Modem = false;[b]
                StrMens = "AT&K0\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
                StrMens = "AT\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
                StrMens = "AT\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
                /*StrMens = "ATE0\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);*/
                StrMens = "AT+CMGF=1\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
                StrMens = "AT+CNMI=,2\r\n";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Form1->Label5->Caption = StrMens;
                Sleep(1500);
         }

         if(GLBEnviaDados == true)
         {
            GLBEnviaDados = false;

            if(Form1->RadioButton1->Checked == true) {
                if(Form1->Memo2->Lines->Count > 0){
                        StrMens = Form1->Memo2->Text;
                        StrMens += "\r\n";
                        Form1->Memo2->Clear();
                        Form1->Memo2->SetFocus();
                        tama = StrMens.Length();
                        EscreveDados(StrMens.c_str(), tama, BytesEscritos);}}

            if(Form1->RadioButton2->Checked == true && x==true) {
                x=false;

                if(Form1->RadioButton2->Checked == true)
                        numero = Form1->Edit1->Text;
                StrMens = "AT+CMGS=\"81105794\",129\n\r";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Sleep(1500);
                Form1->Label5->Caption = StrMens;
                StrMens = Form1->Memo2->Text;
                StrMens += "";
                tama = StrMens.Length();
                EscreveDados(StrMens.c_str(), tama, BytesEscritos);
                Sleep(1500);[/b]
                }
         }
     }else{
        Sleep(1); //Necessário para não travar processo.
     }
   }
}
//--------------------------------------------------------------------------
//DEFINE TIMEOUTs
bool ConfiguraTimeOuts(void)
{
   if( GetCommTimeouts(hCom, &CommTimeouts) == 0 )
   {
      return false;
   }
   CommTimeouts.ReadIntervalTimeout = 2;
   CommTimeouts.ReadTotalTimeoutMultiplier = 0;
   CommTimeouts.ReadTotalTimeoutConstant = 2;
   CommTimeouts.WriteTotalTimeoutMultiplier = 5;
   CommTimeouts.WriteTotalTimeoutConstant = 5;

   if( SetCommTimeouts(hCom, &CommTimeouts) == 0 )
   {
      return false;
   }
   return true;
}
//--------------------------------------------------------------------------
//CONFIGURA PORTA SERIAL.
bool ConfiguraControle(void)
{
   if(!GetCommState(hCom, &dcb))
   {
      return false;
   }
   dcb.BaudRate = CBR_9600;
   dcb.ByteSize = 8;
   dcb.Parity = NOPARITY;
   dcb.StopBits = ONESTOPBIT;

   if( SetCommState(hCom, &dcb) == 0 )
   {
      return false;
   }
   return true;
}
//--------------------------------------------------------------------------
//Abre a Porta Serial COMx
bool AbrirPorta(char *NomePorta)
{
   hCom = CreateFile(
             NomePorta,
             GENERIC_READ | GENERIC_WRITE,
             0, // dispositivos comm abertos com acesso exclusivo
             NULL, // sem atributos de segurança
             OPEN_EXISTING, // deve usar OPEN_EXISTING
             0, //Entrada e saída sem ovelap.
             NULL // hTemplate deve ser NULL para comm
          );
   if(hCom == INVALID_HANDLE_VALUE)
   {
      return false;
   }
   return true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
        Close();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
        Memo1->Clear();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
    GLBEnviaDados = true;
    x=true;
}
//---------------------------------------------------------------------------
void AvisoSonoro(String var)
{
        if(var == "ERROR")
                sndPlaySound("error.wav",SND_ASYNC);
        if(var == "OK")
                sndPlaySound("ok.wav",SND_ASYNC);
}
void __fastcall TForm1::Memo2KeyPress(TObject *Sender, char &Key)
{
        //Form1->KeyPress(0x23);
        /*
        if(Key = 0x23)
        {
                if(Form1->Memo2->Lines->Count > 0) {
                GLBEnviaDados = true;
                Memo2->SetFocus(); }
        }
        */

}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormActivate(TObject *Sender)
{
        //ShowWindow(Application->Handle, SW_HIDE);
        //WindowState = 1;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
        Memo2->Clear();        
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RadioButton2Click(TObject *Sender)
{
        Form1->Edit1->Enabled = true;
        Edit1->Text = "";
        Edit1->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::RadioButton1Click(TObject *Sender)
{
        Form1->Edit1->Enabled = false;
        Edit1->Text = "";
        Memo2->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::RadioButton3Click(TObject *Sender)
{
       Form1->Edit1->Enabled = true;
       Edit1->Text = "9090";
       Edit1->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button8Click(TObject *Sender)
{
        Memo3->Clear();        
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button7Click(TObject *Sender)
{
        Memo3->ReadOnly = false;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button9Click(TObject *Sender)
{
        Memo3->Lines->Add("Mensagem recebida");
        Memo3->Lines->SaveToFile("Mensagem recebida.txt");
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button10Click(TObject *Sender)
{
     Memo3->Lines->SaveToFile("Mensagem recebida.txt");

}
//---------------------------------------------------------------------------
void __fastcall TForm1::Salvarcomo1Click(TObject *Sender)
{
        if(SaveDialog1->Execute())
        {
                Memo3->Lines->SaveToFile(SaveDialog1->FileName);
        }
        else
                MessageBeep(0);        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button6Click(TObject *Sender)
{
     FSelPos = 0;
     FindDialog1->Execute();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button11Click(TObject *Sender)
{
        TPrinter *Prntr = Printer();

        if(PrintDialog1->Execute())
        {
        TRect r = Rect(200, 200, Prntr->PageWidth - 200, Prntr->PageHeight- 200);
        Prntr->BeginDoc();
        //Graphics::TBitmap *BMP = new Graphics::TBitmap();
        //BMP->LoadFromFile("logo.bmp");
        //Printer()->Canvas->Draw(100,50,BMP);        //(coluna,linha)
        Printer()->Canvas->Font->Size = 12;
        Printer()->Canvas->Font->Name = "MS Sans Serif";
        Printer()->Canvas->Font->Color = clBlack;
        Printer()->Canvas->Font->Style = Printer()->Canvas->Font->Style << fsBold;
        //Printer()->Canvas->TextOut(450, 100, "RELATÓRIO (Informações de Sistemas)");

        for(int i = 0; i < Memo3->Lines->Count; i++)
        {
                Printer()->Canvas->Font->Size = 8;
                Printer()->Canvas->Font->Name = "MS Sans Serif";
                Printer()->Canvas->Font->Color = clBlack;
                Printer()->Canvas->Font->Style = Printer()->Canvas->Font->Style;
                Prntr->Canvas->TextOut(135, 300 + (i *
                Prntr->Canvas->TextHeight(Memo3->Lines->Strings[i])),
                Memo3->Lines->Strings[i]);
        }

        //Prntr->Canvas->Brush->Color = clBlack;
        Prntr->Canvas->FrameRect®;
        Prntr->EndDoc();
        }

}
//---------------------------------------------------------------------------
AnsiString __fastcall DataHora(void)
{
  return(TDateTime::CurrentDateTime().DateString()+" às "+TDateTime::CurrentDateTime().TimeString());
}
void __fastcall TForm1::Salvar1Click(TObject *Sender)
{
        Memo3->Lines->SaveToFile("Mensagem recebida.txt");
}
//---------------------------------------------------------------------------
"


Try posting your problem in the C and C++ forum. :)
Was This Post Helpful? 0
  • +
  • -

#14 Jukatzu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 03-April 09

Re: Sending ctrl-z through serial

Posted 03 April 2009 - 06:35 AM

hi,

I had the same problem as yours and I managed to solve it by the following syntax:

//add + (char)26 to the end of the pdu stream :: text = ....." + (char)26

(char)26 is the ascii equivalent to ctrl+z being the character you need!

it WILL work fine :)

NOTE : depending on some gsm supported devices, the second command needs to give time for the first to execute completely so if the program is not working, test it by tracing into and give time for each command to be passed correctly! then come up with an appropriate delay code-wise!

example : AT+CMGF=0 1st command
AT+CMGS=23 2nd command
: 3rd
: 4th

...when you see the BT dongle blinking faster it would mean it is sending the first command. WAIT until it stops, then send the second command via tracing into as instructed!

enjoy,
Justin
justin_farrugia@hotmail.com
Was This Post Helpful? 0
  • +
  • -

#15 gvrao  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 07-August 09

Re: Sending ctrl-z through serial

Posted 07 August 2009 - 04:06 AM

View PostDandy1903, on 10 Apr, 2008 - 06:02 AM, said:

Hi all,

I'm writing a very simple program which uses AT commands to send a SMS via a GSM modem on my com port. I've managed to successfully communicate with the modem through my program (thanks for the "serial Port Comms in c#" tutorial :^: ) But one line is stumping me.
When you issue the command to write a text in HyperTerminal you get a '>' prompt in which you type your message and then press 'ctrl-z' to return to the command prompt. How do I do this in my program?
Any suggestions are much appreciated or anu pointers in the right direction will do nicely.
Here is a bit of my code to help understanding.....maybe!!!

Thanks

 
private void button1_Click(object sender, EventArgs e)
        {
            //Firstly set the modem to text mode
            serialPort1.Write("at+cmgf=1\r\n");
            //Now enter message writing mode to send an sms to the number below
            serialPort1.Write("at+cmgw=\"+447878xxxxxx\"\r\n");
            //Now send the contents of the message
            serialPort1.Write("Test message from coded program");  [b]At the end of this line I need ctrl-z[/b]
            //Now send the message stored at position 2
            serialPort1.Write("at+cmss=2\r\n");
        }



Hi,
you can solve this by just adding (char)26 to the end of the string to be written. Some modems may require a "\r\n" after the ctrl+z. so try + (char)26 + "\r\n" if the code given below doesn't work for you.

The code will look like this
<code>
serialPort1.Write("Test message from coded program" + (char)26);
</code>

I came across this while searching for solutions myself to a similar problem. You might have got the solution much earlier, but I am posting it for the benefit of people landing here like me.

Happy coding!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1