Playing with serial port

Got a LiveCode personal license? Are you a beginner, hobbyist or educator that's new to LiveCode? This forum is the place to go for help getting started. Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller

tabbiati
Posts: 18
Joined: Sat Jul 09, 2011 3:18 pm

Playing with serial port

Post by tabbiati » Fri Jun 08, 2012 1:08 pm

Hello to all,
i have a simple (not simple for me...) problem:
i want send text inside field to serial port not in block
but char to char with a delay between them ( there is a
slow microcontroller that receive it) and i need to select
port and baud rate; and other: how send value and not char?
Thanks for Your patient....

sturgis
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 1685
Joined: Sat Feb 28, 2009 11:49 pm

Re: Playing with serial port

Post by sturgis » Fri Jun 08, 2012 4:05 pm

Look in the dictionary at serialControlString

To set the baud of the serial connection (before actual connect)

set the serialControlString to "baud=1200" -- or whatever baud your controller expects.

To select port it depends on your operating system.

For example, on windows

open driver "COM3:" will open com port 3. --on windows, you can also open file "COM3:" and it does the same.

On a mac it will be something like open driver "/dev/cu.modem" -- taken from the open driver dictionary entry


You'll want to look at open driver in the dictionary and decide if you need to open for update, write, read, text, binary etc. (most likely for text update so you have 2 way text communication)

There should be a buffer in the controller. So you should set the baud rate to what the controller is expecting (as well as parity and stop bits) if the controller itself is just to slow to keep up with the serial port you'll need to code pauses into your write loop. (seems like this shouldn't really be necessary though)

tabbiati
Posts: 18
Joined: Sat Jul 09, 2011 3:18 pm

Re: Playing with serial port

Post by tabbiati » Fri Jun 08, 2012 5:33 pm

Thanks Sturgis,

I have just made some of You say me
but i have some problem: code work very well if i don't use
serialControlString ; if i use it sometimes work ok sometimes no.

Delay between data is necessary because during reception data microcontroller transfer
data to a slow extern memory and can lose others coming data.

You can see my code and i search for a better idea...
Other i have problem that i have a field to fill with data from microcontroller
that came at random time....

Code: Select all

global Seriale
global MaxMem

on mouseUp
    if the length of field Editor > (MaxMem - 3) then  answer "Impossibile caricare scheda: programma troppo lungo."
   if the length of field Editor <= (MaxMem - 3) then 
      put label of button Porta into Seriale
        --set serialControlString to "BAUD=1200"
   open driver Seriale
   set backgroundColor of graphic TX to RED
   wait for 1 seconds
   get the number of chars  of field "Editor"
   put 1 into contatore
   repeat for it
      write char contatore of field "Editor" to driver Seriale
      --write field Editor to driver Seriale
      put (contatore + 1) into contatore
      wait for label of button Ritardo milliseconds
      end repeat
   repeat for 3
       write EOF to driver Seriale
   end repeat
   set backgroundColor of graphic TX to GREEN
   close driver Seriale
   end if
end mouseUp

sturgis
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 1685
Joined: Sat Feb 28, 2009 11:49 pm

Re: Playing with serial port

Post by sturgis » Fri Jun 08, 2012 6:57 pm

You use serialcontrolstring to set the baud that the controller expects. Most likely it expects 9600 baud, but you'd have to read the documents on the controller to know for sure. (it might be adjustable too)
If you need to send your characters to the controller slower than the serial connection is able to send (because the controller is slow) you have to code the time delay into your write loop as you have done.

If you need to read and write at the same time you can "open driver seriale for update" so that you can do both.

If you are uploading a program, closing the port and then just want to read the output, you can call a second handler to do the read. You might consider a send in time loop for that one.

Code: Select all

global Seriale
global MaxMem
global gReading

on mouseUp
-- off the top of my head and untested
if gReading is true then -- if the read loop is running
      put false into gReading --make sure the read loop stops
      wait 50 milliseconds with messages -- not sure this line is necessary
      close driver seriale  
end if

    if the length of field Editor > (MaxMem - 3) then  answer "Impossibile caricare scheda: programma troppo lungo."
   if the length of field Editor <= (MaxMem - 3) then 
      put label of button Porta into Seriale
        --set serialControlString to "BAUD=1200"
   open driver Seriale
   set backgroundColor of graphic TX to RED
   wait for 1 seconds
   get the number of chars  of field "Editor"
   put 1 into contatore
   repeat for it
      write char contatore of field "Editor" to driver Seriale
      --write field Editor to driver Seriale
      put (contatore + 1) into contatore
      wait for label of button Ritardo milliseconds
      end repeat
   repeat for 3
       write EOF to driver Seriale
   end repeat
   set backgroundColor of graphic TX to GREEN
   close driver Seriale
   put true into gReading

   open driver seriale for read --re open the port for reading the controller output
   readLoop --start the read loop

   end if
end mouseUp

command readLoop
   if gReading then
      read from Seriale until empty
      put it into field "outfield" -- the field where you want to display the read characters    
      send "readLoop" to me in 50 milliseconds
   end if
end readLoop

tabbiati
Posts: 18
Joined: Sat Jul 09, 2011 3:18 pm

Re: Playing with serial port

Post by tabbiati » Sat Jun 09, 2012 3:50 pm

Thanks sturgis,
Microcontroller baud rate is easy on my control i set like i want
but i have problem when change baud rate in RunRev..
Your code seem good for me: test it tomorrow!

sturgis
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 1685
Joined: Sat Feb 28, 2009 11:49 pm

Re: Playing with serial port

Post by sturgis » Sat Jun 09, 2012 3:55 pm

Probably want to change this line -- put it into field "outfield" -- the field where you want to display the read characters
to:
put it AFTER field "outfield"

tabbiati
Posts: 18
Joined: Sat Jul 09, 2011 3:18 pm

Re: Playing with serial port

Post by tabbiati » Sun Jun 10, 2012 2:27 pm

Hello sturgis,
with some minor change i have, thank to Your help,
what i want and now my application see the light...
( after is ok).
Thanks again!

vadopiano
Posts: 10
Joined: Thu Jul 12, 2012 4:46 pm

Re: Playing with serial port

Post by vadopiano » Thu Jul 12, 2012 5:43 pm

Hello, i am a new member and unfortunately i don't speak a good english... like nothing!
Ok, i will write in italian (i hope that somebody very gently can help me).

Sto cercando di studiare runrev con una versione demo per testare se mi conviene usarlo in futuro, ma trovo molte difficoltà ad usare software per comunicare in seriale. Anni fa usavo il MAC e con Hypercard e Supercard (sigh, sob, gulp) facevo tutto, soprattutto per quanto riguarda comunicazione con controllers esterni via seriale.
Volevo provare oggi con runrev perché il codice è molto simile e di facile scrittura come Hypercard e perché non uso più il Mac, ma pur facendoci un po' tutto non mi riesce affatto bene gestire la porta seriale: i comandi di output funzionano regolarmente ma per gli input non riesco a leggerli, ho provato di tutto, sicuramente c'è qualcosa nel codice che mi sfugge, ho provato anche a interrogare il modem interno del laptop ma niente, mi ritorna sempre il 101 (eof).
Ho provato tutte le combinazioni possibili, soprattutto i ritardi per non saturare il buffer, ma niente.
Devo pilotare una interfaccia seriale-parallela che viaggia solo a 2400 baud, ma pur funzionando con Hypercard e Supercard (xcmd e xfcn) con runrev non vuole saperne... c'è qualcuno che puo' aiutarmi?
Ho già letto quasi tutti i post sull'argomento e applicato i suggerimenti ma niente di buono ho ottenuto.
Ringrazio molto e anticipatamente per qualsiasi nota che possa aiutarmi.
Saluti e grazie ancora.

mwieder
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 3581
Joined: Mon Jan 22, 2007 7:36 am
Contact:

Re: Playing with serial port

Post by mwieder » Thu Jul 12, 2012 5:57 pm

Hypercard e Supercard (sigh, sob, gulp)
:P
2400 baud
:shock:

Try:

http://www.troz.net/rev/index.irev?cate ... ial#stacks

sturgis
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 1685
Joined: Sat Feb 28, 2009 11:49 pm

Re: Playing with serial port

Post by sturgis » Thu Jul 12, 2012 6:05 pm

Mi scuso in anticipo, io sto usando Google Translate per creare questo. Se l'italiano è cattivo, mi perdoni.

È necessario impostare la serialcontrolstring in base al dispositivo che si desidera utilizzare.

Se il dispositivo funziona a 2400 baud si avrebbe bisogno di fare quanto segue:
impostare il serialcontrolstring a "baud = 2400"
Potrebbe essere necessario regolare le impostazioni anche altri, come i bit di stop, parità, bit di dati. Le impostazioni predefinite sono 8, nessuno e 1.
Guardate la voce di dizionario per serialcontrolstring per vedere cos'altro può essere impostato.

Su Windows, con una connessione diretta ad un dispositivo ci si vuole collegare direttamene a una porta seriale, sì? Quindi non sarà l'apertura di un modem integrato in porto. Per parlare con il modem avrebbe dovuto inviare stringhe di controllo del modem per comporre e creare una connessione. Ciò non è necessario collegare direttamente servivano.

Lei ha detto che si stava ottenendo soltanto EOF in risposta. Molto probabilmente si sta utilizzando il modulo "leggere fino vuota" durante la lettura dalla porta seriale. Se non vi è nulla in attesa nel buffer il risultato dirà eof. Se il dispositivo scrive qualcosa alla porta seriale, e di leggere fino a vuoto, il _it_ variabile speciale conterrà ciò che si legge.

Riesci a scrivere con successo al controllore?

Ti dispiacerebbe inviare il vostro codice? Cosa regolatore stai lavorando? Puoi inviare il programma in esecuzione sul controller anche?

vadopiano
Posts: 10
Joined: Thu Jul 12, 2012 4:46 pm

Re: Playing with serial port

Post by vadopiano » Thu Jul 12, 2012 7:45 pm

Spettacolare la velocità della risposta... e anche il tuo italiano :wink:
Comunque se vuoi puoi scrivere in inglese, lo so leggere ma faccio molti errori in scrittura.
Ok & tank!
I baud sono pochi perché pilotando un controller meccanico esterno c'è più bisogno di rallentare che velocizzare :)
Le configurazioni le ho provate tutte, anche con lo stack di Sarah ovviamente, con i delay e pause, loop di lettura e scrittura, anche per il modem interno non risponde ai comandi AT mentre con altri piccoli software è ok, naturalmente è senza cavo.
La periferica (device) ha sempre funzionato egregiamente, ci controllavo dei motori step to step, è una cosa tipo Arduino, efficiente ma anche più semplice.
Lavora con soli 4 chars in output e 3 in input (e un 4 per ricezione), ma quello che non mi convince è che non cambia mai e poi mai il risultato in input, sempre 101 o EOF, neanche mai un stupido carattere diverso anche se illegibile... anche questo è inspiegabile: non dà segni vita!
Ovviamente la periferica funziona, per esempio ho un piccolo software in VisualBasic... penoso e non gestibile, ma per testare è ok, con runrev esegue tutte le routine che gli impongo senza interrupt o bugs, ma nel campo di ricezione non importa nulla, solo 101 o EOF, chiedo anche il numero dei dati: 1 word in 3 chars appunto.
Quello che mi sorprende è che ignora completamente il modem interno, che non uso più perché mi collego in LAN, pur configurandolo come già lo riconosce il sistema, e poi il modem dovendosi adattare ad altri modem non ha una trasmissione fissa ma varia da 300 a 250000 baud, ma sembra invisibile.
A memoria ricordo questo che ho scritto, ma ho tentato molte altre combinazioni:
Fisso prima il serialcontrolstring, risponde che è OK (infatti i dati in output sono perfetti e regolari.
CRLF dato di chiusura, ma ho provato anche CR, EOF, etc...
-----
open file poRta for binary update-----(COM1:) , ho provato anche con open file xxx for write e for read, naturalmente open e close a ogni invio ma non con update.
put numtochar(x)& numtochar(x)& numtochar(x) into invioDati
write invioDati & CRLF to file poRta
wait...x (sometime yes sometime nodepend)
read from file poRt until empty--- (or EOF,CRLF,LF,for 10 etc...uintx... insomma tutte le opzioni dal dictionary runrev)
wait...x (sometime yes sometime no, depend)
if the result is not empty then put it into riceVuto
put num of words of riceVuto && num of chars of riceVuto & return after fld "entrata"--- verifico quanto legge
put chartonum(riceVuto) & return after fld "entrata"
-----
Note: output perfetto, se cambio qualcosa del serialcontrolstring non funziona, quindi è OK.
Chiedo soltanto come far apparire un dato qualsiasi in ricezione, poi una soluzione la trovo, un po' come facevo con Hypercard (sigh, sob, gulp... my first and last love!!! but many years ago))

Per ora ringrazio tutti, appena posso più tardi invio delle semplici routines che ho usato, sono in un altro pc.
Ciaooooo!!!

vadopiano
Posts: 10
Joined: Thu Jul 12, 2012 4:46 pm

Re: Playing with serial port

Post by vadopiano » Thu Jul 12, 2012 7:49 pm

P.S:
Ho provato anche con un semplice modem esterno via cavo: nessun risultato, trasmette ma non riceve.
Grazie e ciao.

sturgis
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 1685
Joined: Sat Feb 28, 2009 11:49 pm

Re: Playing with serial port

Post by sturgis » Thu Jul 12, 2012 9:04 pm

Are you sure you want to open it for binary update?

I think you said that you can connect to the board using other software (perhaps hyperterm?) Out of curiosity if you connect the board, run it for a moment with hyperterm (or whatever you have available) then disconnect and connect with livecode (leaving the board plugged in to the system), does your livecode serial stack start working?

vadopiano
Posts: 10
Joined: Thu Jul 12, 2012 4:46 pm

Re: Playing with serial port

Post by vadopiano » Thu Jul 12, 2012 10:19 pm

Hallo, no non sono sicuro sia buona idea aprire in binary mode, l'avevo considerato, anche se in output funziona correttamente, ma come ho scritto ho provato anche con il solo update, write e read (con write e read ovviamente ogni volta chiudevo e aprivo il file.
Non ho usato yperterminal per il modem test ma "modemtest" o il pannello di controllo Windows e andava ok, e ho fatto anche prove a connettere il device prima o dopo lo startup del pc: niente purtroppo.
Come ripeto quel che non capisco è perché il modem non si vede... bah, mistery!
In Windows nel miolaptop la porta del modem interno è COM3: tutti la vedono, chiaro che i driver sono corretti, tutti meno runrev, c'è un'istruzione precisa per interrogare il modem con runrev in WinXP or Win7? Forse se riesco a vedere il modem posso fare un altro passo avanti (i hope).
Tank again, ciao.

vadopiano
Posts: 10
Joined: Thu Jul 12, 2012 4:46 pm

Re: Playing with serial port

Post by vadopiano » Fri Jul 13, 2012 4:58 pm

Ciao, sono sempre in panne...
Con una piccola modifica al SerialTest.rev sono riuscito a comunicare con il modem interno, esegue i comandi inviati e risponde e leggo la risposta,ma dal device la risposta non arriva ancora, cioé arriva di sicuro ma non riesco ad estrarla, di certo ho difficoltà a gestire runrev.
Ho vagato in rete e ho trovato un sito, di lingua spagnola, dove si usa proprio questo device e ho avuto conferma che i parametri sono corretti: 4 caratteri in output per i comandi e tre per ricevere risposta: praticamente funziona come il modem che al comando di AT&V risponde automaticamente.
In conclusione credo che anche il device funziona così come il modem, con la differenza che i dati rimangono nel buffer e non riesco a leggerli come il modem. Ci sono anche i test ma sono scritti in Java, un codice che non conosco, ma leggendo le routine è chiaro che la procedura fino all'invio è esatta, mi manca l'istruzione per leggerla con runrev... il mio account non mi permette di segnalare siti nel forum ma se c'è qualcuno che conosca un po' di Java potrei trovare il modo per ricopiare gli scripts che sono in formato grafico, non in testo.
Tank you again... e saluti!

Post Reply