<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Programonauta on Medium]]></title>
        <description><![CDATA[Stories by Programonauta on Medium]]></description>
        <link>https://medium.com/@ricardo_66479?source=rss-81320e142d2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hr1wIneHQDms4iNRbm4U-Q.png</url>
            <title>Stories by Programonauta on Medium</title>
            <link>https://medium.com/@ricardo_66479?source=rss-81320e142d2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:54:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ricardo_66479/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JSON e Ada]]></title>
            <link>https://medium.com/@ricardo_66479/json-e-ada-b41703923693?source=rss-81320e142d2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b41703923693</guid>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[gnats]]></category>
            <category><![CDATA[ada]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Programonauta]]></dc:creator>
            <pubDate>Thu, 20 Jun 2019 19:00:17 GMT</pubDate>
            <atom:updated>2019-10-15T12:56:47.581Z</atom:updated>
            <content:encoded><![CDATA[<p>Read this story in English <a href="https://medium.com/@ricardo_66479/handling-json-data-in-ada-7744f4235cd4">here</a>.</p><p>Estou iniciando os estudos da linguagem Ada. E depois dos primeiros tutoriais, nos quais começamos com um simples “Hello World” e aos poucos vamos entrando nos detalhes da linguagem (veja meu post <a href="https://medium.com/@ricardo_66479/aprendendo-a-linguagem-ada-e4fc5361b490">aqui</a>), chegou a hora de aprender como trabalhar com coisas mais próximas do mundo real.</p><p>Eu estava curioso para saber como ler, e manipular arquivos JSON em ada. Assim, tentei procurar alguns tutoriais, os primeiros foram:</p><ul><li><a href="https://docs.adacore.com/gnatcoll-docs/json.html">Ada Core</a>, o mesmo site do GNAT Programming Studio</li><li><a href="https://rosettacode.org/wiki/JSON#Ada">Rosetta Code</a>, o site onde, segundo eles “a ideia é apresentar soluções de uma mesma tarefa no maior número de linguagens possível”.</li></ul><p>Eu decidi tentar o exemplo do Rosetta Code, por ser um pouco mais completo.</p><p>Então vamos ao passo-a-passo:</p><p>Primeiro, inicie o GPS e clique em“Create New Project”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*NEAJYCq_7UEsaGqFi8ZnaQ.png" /></figure><p>Escolha o Template: Simple Ada Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4w8YIcVMOeXdFTv-9ZfpCA.png" /></figure><p>Na próxima tela, confirme o diretório no qual você deseja salvar o projeto, escolha o nome o projeto e o nome principal (Main Name).</p><p>Main name é o nome da procedure que será chamada no início da execução, conforme veremos em breve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ux40l6pF3aaA-NnLDxd48Q.png" /></figure><p>E você agora tem uma tela pronta para programar. Veja o nome da Procedure Json, como foi escolhido no passo anterior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1YtslpkdZfMXh3_oMi7vw.png" /></figure><p>Eu reproduzirei todos os passos conforme eu fiz, mesmo tendo alguns erros. Eu mostrarei aqui como resolvê-los.</p><p>Copie e cole o código do site Rosetta Code, primeira opção que usa a biblioteca GNATCOOL. Se preferir, copie e cole o código abaixo, é o mesmo.</p><pre><strong>with</strong> Ada.<strong>Text_IO</strong>;<br><strong>with</strong> GNATCOLL.<strong>JSON</strong>;<br> <br><strong>procedure</strong> JSON_Test <strong>is</strong><br>   <strong>use</strong> Ada.<strong>Text_IO</strong>;<br>   <strong>use</strong> GNATCOLL.<strong>JSON</strong>;<br> <br>   JSON_String : <strong>constant</strong> String := &quot;{&quot;&quot;name&quot;&quot;:&quot;&quot;Pingu&quot;&quot;,&quot;&quot;born&quot;&quot;:1986}&quot;;<br> <br>   Penguin : JSON_Value := Create_Object;<br>   Parents : JSON_Array;<br><strong>begin</strong><br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;name&quot;, <br>                      Field      =&gt; &quot;Linux&quot;<strong>)</strong>;<br> <br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; <strong>1992)</strong>;<br> <br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Linus Torvalds&quot;<strong>))</strong>;<br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Alan Cox&quot;<strong>))</strong>;<br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Greg Kroah-Hartman&quot;<strong>))</strong>;<br> <br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents<strong>)</strong>;<br> <br>   Put_Line <strong>(</strong>Penguin.<strong>Write)</strong>;<br> <br>   Penguin := Read <strong>(</strong>JSON_String, &quot;json.errors&quot;<strong>)</strong>;<br> <br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; <strong>1986)</strong>;<br> <br>   Parents := Empty_Array;<br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Otmar Gutmann&quot;<strong>))</strong>;<br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Silvio Mazzola&quot;<strong>))</strong>;  <br> <br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents<strong>)</strong>;<br> <br>   Put_Line <strong>(</strong>Penguin.<strong>Write)</strong>;<br><strong>end</strong> JSON_Test;</pre><p>Clique no botão “Build and Run”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YApDq8txBRvxyEfSI_cikA.png" /></figure><p>Ao final, pode-se observar um erro e um aviso. Observe nas duas janelas inferiores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UelXVrPiNuy4SkQu4U779g.png" /></figure><p>Primeiro, vamos resolver o aviso (<em>warning</em>).</p><pre>json.adb:4:11: warning: file name does not match unit name, should be &quot;json_test.adb&quot;</pre><p>O problema é que demos o nome principal como “Json”, e ao copiar e colar o código o nome que veio é “JSON_Test”. Para resolver, basta alterar o nome da procedure para Json nas linhas 4 e 41:</p><pre>4   procedure JSON is<br>...<br>...<br>...<br>40     Put_Line (Penguin.Write);<br>41   end JSON;</pre><p>O erro:</p><pre>json.adb:2:06: file &quot;gnatcoll.ads&quot; not found</pre><p>A biblioteca GNATOOL é instalada juntamente com o GPS, mas é necessário informar que você irá usá-la. Para fazer isso, a partir do Project Explorer, clique na direita sobre o nome do projeto, e vá para Project → Properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*BR46Q42MSR7zFJ1PuNqAeA.png" /></figure><p>Na janela de propriedades, selecione Dependencies e arraste para a janela de dependências a bilbioteca gnatcool, conforme pode ser visto na imagem abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*tamERCosuMNEcAxt_yCQOQ.png" /></figure><p>Clique em Save, e você verá a biblioteca na árvore do projeto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*JM99efAV2HC1gDWwTwJE8g.png" /></figure><p>Vamos tentar compilar novamente. Mas…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*ZvrwGt45-GOG2Xd3WYAcrw.png" /></figure><p>Na janela inferior à direita, o GPS permite que você clique no erro para ir diretamente ao arquivo sugerido. No caso gnatcool-json.ads. Com isso fica mais fácil tentar descobrir o problema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*ZViTxttddR5u_HDqpxTDXg.png" /></figure><p>Em Ada, é possível usar Function Overloading, ou seja, declarar funções com o mesmo nome onde os parâmetros podem variar. A ideia é que o compilador possa escolher a função correta dependendo dos parâmetros utilizados, mas nesse caso, o compilador não identificou se o valor utilizado era do tipo Integer ou Long Integer. Lembre-se que Ada é uma linguagem fortemente tipada!</p><p>Para resolver isso, vamos usar type casting. (Agradeço ao Keith Thompson do <a href="https://groups.google.com/forum/#!topic/comp.lang.ada/ByOGWmVY5R4">Grupo de emails</a>)</p><pre>Penguin.Set_Field (Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; Integer&#39;(1992));<br> <br>   Append (Parents, Create (&quot;Linus Torvalds&quot;));<br>   Append (Parents, Create (&quot;Alan Cox&quot;));<br>   Append (Parents, Create (&quot;Greg Kroah-Hartman&quot;));<br> <br>   Penguin.Set_Field (Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents);<br> <br>   Put_Line (Penguin.Write);<br> <br>   Penguin := Read (JSON_String, &quot;json.errors&quot;);<br> <br>   Penguin.Set_Field (Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; Integer&#39;(1986));</pre><p>Clique em Build and Run… e SUCESSO!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27E9QWye_Aqj6gidVxtElw.png" /></figure><h4>Entendendo o código</h4><p>Agora, eu sugiro que você analise o código linha a linha.</p><p>O código é dividido em dois blocos: no primeiro o objeto JSON é criado desde o início, com as variáveis Penguin do tipoJSON_Value e Parents do tipoJSON_Array.</p><ol><li>Primeiro bloco de código</li></ol><p>Os dois primeiros comandos criam os campos JSON&quot;name&quot; and &quot;born&quot;</p><pre>Penguin.Set_Field (Field_Name =&gt; &quot;name&quot;, <br>                      Field      =&gt; &quot;Linux&quot;);<br> <br>   Penguin.Set_Field (Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; Integer&#39;(1992))</pre><p>O próximo passo é criar um Array:</p><pre>Append (Parents, Create (&quot;Linus Torvalds&quot;));<br>   Append (Parents, Create (&quot;Alan Cox&quot;));<br>   Append (Parents, Create (&quot;Greg Kroah-Hartman&quot;));</pre><p>E criar um outro campo JSON chamado&quot;parents&quot; cujo conteúdo é o Array criado</p><pre>Penguin.Set_Field (Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents);</pre><p>Para mostrar o resulto, é utilizado o comando Put_Line.</p><pre>Put_Line (Penguin.Write);</pre><p>2. Segundo bloco de código</p><p>Neste bloco o programa lê uma variável do tipo String chamada JSON_String cujo conteúdo é uma estrutura JSON:</p><pre>JSON_String : constant String := &quot;{&quot;&quot;name&quot;&quot;:&quot;&quot;Pingu&quot;&quot;,&quot;&quot;born&quot;&quot;:1986}&quot;;</pre><p>Para enviar o conteúdo para uma variável do tipoJSON_Value :</p><pre>Penguin := Read (JSON_String, &quot;json.errors&quot;);</pre><p>Agora, a variável Penguin tem a estrutura JSON:</p><pre>{<br>  &quot;name&quot;: &quot;Pingu&quot;,<br>  &quot;born&quot;: 1986<br>}</pre><p>A próxima instrução atualiza o campo born. No código original, eles usam o mesmo valor. Eu sugiro que você tente outro valor para verificar como funciona.</p><pre>   Penguin.Set_Field (Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; Integer&#39;(1987));</pre><p>Agora, variável Parents é esvaziada e são criados novos campos.</p><pre>Parents := Empty_Array;<br>   Append (Parents, Create (&quot;Otmar Gutmann&quot;));<br>   Append (Parents, Create (&quot;Silvio Mazzola&quot;));  <br> <br>   Penguin.Set_Field (Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents);<br> <br>   Put_Line (Penguin.Write);</pre><h4>Vamos explorar o funcionamento da biblioteca</h4><p>Se você também é um iniciante, sugiro utilizar as funcionalidades do GPS, usando o clique da direita para ver as declarações de variáveis, dos tipos, explorar o arquivo gnatcool-json.ads, alterar valores, tentar utilizar outros tipos e estruturas JSON, etc.</p><p>Espero que tenha gostado e vamos continuar os estudos da linguagem Ada!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b41703923693" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling JSON data in Ada]]></title>
            <link>https://medium.com/@ricardo_66479/handling-json-data-in-ada-7744f4235cd4?source=rss-81320e142d2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7744f4235cd4</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[gnats]]></category>
            <category><![CDATA[ada]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ada-language]]></category>
            <dc:creator><![CDATA[Programonauta]]></dc:creator>
            <pubDate>Thu, 20 Jun 2019 18:13:40 GMT</pubDate>
            <atom:updated>2019-06-20T19:01:38.914Z</atom:updated>
            <content:encoded><![CDATA[<p>Leia essa história em português <a href="https://medium.com/me/stats/post/b41703923693">aqui</a>.</p><p>As a beginner in Ada Language, after the first contact and the step-by-step tutorials where you begin with a Hello World and start to learn the basic features of the language (You can see my post <a href="https://medium.com/@ricardo_66479/learning-ada-language-a15ae46ccdfb">here</a>), it’s time to learn how to deal with things more “close” to the real life.</p><p>I was so curious to know how Ada deal with JSON, and try to find out some tutorials. Then the first two are:</p><ul><li><a href="https://docs.adacore.com/gnatcoll-docs/json.html">Ada Core</a>, the site where you can download GNAT Programming Studio</li><li><a href="https://rosettacode.org/wiki/JSON#Ada">Rosetta Code</a>, a site where “The idea is to present solutions to the same task in as many different languages as possible”</li></ul><p>I decided try the Rosetta Code example, to be a bit more complete.</p><p>So, let’s go to step-by-step</p><p>First, start the GPS, and click on “Create New Project”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*NEAJYCq_7UEsaGqFi8ZnaQ.png" /></figure><p>Now choose the Template: Simple Ada Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4w8YIcVMOeXdFTv-9ZfpCA.png" /></figure><p>In the next screen, confirm the Directory where you want to deploy your project and choose the Project Name and the Main Name.</p><p>The Main name is the name of procedure will be first called, as we’ll see shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ux40l6pF3aaA-NnLDxd48Q.png" /></figure><p>And you have a fresh screen ready to program. You can see the name of Procedure is Json, as you chose in previous step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1YtslpkdZfMXh3_oMi7vw.png" /></figure><p>I’ll reproduce all steps I did, even when I got some errors. I’ll show here how to solve them.</p><p>Let’s copy and paste the code from Rosetta Code site, first option that use GNATCOOL library. If you prefer , you can copy and paste the code below. Is the same.</p><pre><strong>with</strong> Ada.<strong>Text_IO</strong>;<br><strong>with</strong> GNATCOLL.<strong>JSON</strong>;<br> <br><strong>procedure</strong> JSON_Test <strong>is</strong><br>   <strong>use</strong> Ada.<strong>Text_IO</strong>;<br>   <strong>use</strong> GNATCOLL.<strong>JSON</strong>;<br> <br>   JSON_String : <strong>constant</strong> String := &quot;{&quot;&quot;name&quot;&quot;:&quot;&quot;Pingu&quot;&quot;,&quot;&quot;born&quot;&quot;:1986}&quot;;<br> <br>   Penguin : JSON_Value := Create_Object;<br>   Parents : JSON_Array;<br><strong>begin</strong><br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;name&quot;, <br>                      Field      =&gt; &quot;Linux&quot;<strong>)</strong>;<br> <br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; <strong>1992)</strong>;<br> <br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Linus Torvalds&quot;<strong>))</strong>;<br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Alan Cox&quot;<strong>))</strong>;<br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Greg Kroah-Hartman&quot;<strong>))</strong>;<br> <br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents<strong>)</strong>;<br> <br>   Put_Line <strong>(</strong>Penguin.<strong>Write)</strong>;<br> <br>   Penguin := Read <strong>(</strong>JSON_String, &quot;json.errors&quot;<strong>)</strong>;<br> <br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; <strong>1986)</strong>;<br> <br>   Parents := Empty_Array;<br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Otmar Gutmann&quot;<strong>))</strong>;<br>   Append <strong>(</strong>Parents, Create <strong>(</strong>&quot;Silvio Mazzola&quot;<strong>))</strong>;  <br> <br>   Penguin.<strong>Set_Field</strong> <strong>(</strong>Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents<strong>)</strong>;<br> <br>   Put_Line <strong>(</strong>Penguin.<strong>Write)</strong>;<br><strong>end</strong> JSON_Test;</pre><p>Click the Button “Build and Run”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YApDq8txBRvxyEfSI_cikA.png" /></figure><p>We get the first error and warning, as you could see in the two bottom windows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UelXVrPiNuy4SkQu4U779g.png" /></figure><p>Let’s start solving the warning.</p><pre>json.adb:4:11: warning: file name does not match unit name, should be &quot;json_test.adb&quot;</pre><p>The problem is we call the Main Name as “Json”, and when we copy and paste the code from Rosetta Code, the name is JSON_Test. To solve, just change the procedure name to Json on lines 4 and 41:</p><pre>4   procedure JSON is<br>...<br>...<br>...<br>40     Put_Line (Penguin.Write);<br>41   end JSON;</pre><p>The error:</p><pre>json.adb:2:06: file &quot;gnatcoll.ads&quot; not found</pre><p>The GPS install the library GNATCOLL, but you need to inform the project you will use it. To do this, from Project Explorer, right-click Click and go to Project → Properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*BR46Q42MSR7zFJ1PuNqAeA.png" /></figure><p>In the Properties window, select Dependencies, and Drag-and-drop gnatcool to the left how you can see in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*tamERCosuMNEcAxt_yCQOQ.png" /></figure><p>Click on Save button, and you’ll see the GnatCool library on the project tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*JM99efAV2HC1gDWwTwJE8g.png" /></figure><p>Let’s try Build and Run again. But…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*ZvrwGt45-GOG2Xd3WYAcrw.png" /></figure><p>In the right bottom window, GPS allow you click on error to go directly to gnatcool-json.ads file to try to figure out what is the problem. So, let’s do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*ZViTxttddR5u_HDqpxTDXg.png" /></figure><p>In Ada, is possible use a Function Overloading, functions with same name where you could vary the arguments. Is supposed the compiler can choose the correct function, but in this case, the compiler didn’t understand if the parameter is Integer or Long Integer. Remember Ada is a strongly typed language!</p><p>To solve this lets use type casting. (Thanks to Keith Thompson from <a href="https://groups.google.com/forum/#!topic/comp.lang.ada/ByOGWmVY5R4">Ada Email group</a>)</p><pre>Penguin.Set_Field (Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; Integer&#39;(1992));<br> <br>   Append (Parents, Create (&quot;Linus Torvalds&quot;));<br>   Append (Parents, Create (&quot;Alan Cox&quot;));<br>   Append (Parents, Create (&quot;Greg Kroah-Hartman&quot;));<br> <br>   Penguin.Set_Field (Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents);<br> <br>   Put_Line (Penguin.Write);<br> <br>   Penguin := Read (JSON_String, &quot;json.errors&quot;);<br> <br>   Penguin.Set_Field (Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; Integer&#39;(1986));</pre><p>Click on Build and Run… and SUCCESS!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27E9QWye_Aqj6gidVxtElw.png" /></figure><h4>Understanding the code</h4><p>Now I suggest you analyse the code line-by-line.</p><p>The code is divided in two blocks: the first one, the JSON object is created from the scratch with variables Penguin of type JSON_Value and Parents of type JSON_Array</p><ol><li>First Block of code</li></ol><p>The two first commands create fields &quot;name&quot; and &quot;born&quot;</p><pre>   Penguin.Set_Field (Field_Name =&gt; &quot;name&quot;, <br>                      Field      =&gt; &quot;Linux&quot;);<br> <br>   Penguin.Set_Field (Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; Integer&#39;(1992))</pre><p>The next step is create an Array:</p><pre>   Append (Parents, Create (&quot;Linus Torvalds&quot;));<br>   Append (Parents, Create (&quot;Alan Cox&quot;));<br>   Append (Parents, Create (&quot;Greg Kroah-Hartman&quot;));</pre><p>And create another field named &quot;parents&quot; where the content is the Array</p><pre>Penguin.Set_Field (Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents);</pre><p>To show the result, Put_Line command is used</p><pre>Put_Line (Penguin.Write);</pre><p>2. Second Block</p><p>In this block the program read a String variable named JSON_String where the content is a JSON structure:</p><pre>JSON_String : constant String := &quot;{&quot;&quot;name&quot;&quot;:&quot;&quot;Pingu&quot;&quot;,&quot;&quot;born&quot;&quot;:1986}&quot;;</pre><p>To read the string into a JSON_Value variable:</p><pre>Penguin := Read (JSON_String, &quot;json.errors&quot;);</pre><p>Now, Penguin variable have the JSON:</p><pre>{<br>  &quot;name&quot;: &quot;Pingu&quot;,<br>  &quot;born&quot;: 1986<br>}</pre><p>The next instruction update the field born. In the original code, they use the same value. I suggest you try another one to verify.</p><pre>   Penguin.Set_Field (Field_Name =&gt; &quot;born&quot;,<br>                      Field      =&gt; Integer&#39;(1987));</pre><p>Now, empty the variable Parents and create new entries, and finally show the JSON content.</p><pre>Parents := Empty_Array;<br>   Append (Parents, Create (&quot;Otmar Gutmann&quot;));<br>   Append (Parents, Create (&quot;Silvio Mazzola&quot;));  <br> <br>   Penguin.Set_Field (Field_Name =&gt; &quot;parents&quot;,<br>                      Field      =&gt; Parents);<br> <br>   Put_Line (Penguin.Write);</pre><h4>It’s time to explore</h4><p>If you are a beginner like me, I suggest you use the great features of GPS, using right click to see declarations of each variable type, explore the file gnatcool-json.ads, change the values, try use another types, etc.</p><p>I hope you enjoy and let’s move on studying Ada Language!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7744f4235cd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aprendendo a Linguagem Ada]]></title>
            <link>https://medium.com/@ricardo_66479/aprendendo-a-linguagem-ada-e4fc5361b490?source=rss-81320e142d2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4fc5361b490</guid>
            <category><![CDATA[ada]]></category>
            <category><![CDATA[linguagem-de-programação]]></category>
            <category><![CDATA[gnats]]></category>
            <dc:creator><![CDATA[Programonauta]]></dc:creator>
            <pubDate>Tue, 18 Jun 2019 22:36:21 GMT</pubDate>
            <atom:updated>2019-07-24T22:37:14.444Z</atom:updated>
            <content:encoded><![CDATA[<p>Read this story in English <a href="https://medium.com/@ricardo_66479/learning-ada-language-a15ae46ccdfb?postPublishedType=repub">here</a></p><h3>Nunca é tarde para começar</h3><p>Esse mês eu decidi começar os estudos da Linguagem de Programação Ada. Eu trabalho há um bom tempo com computação embarcada (lá se vão quase 30 anos) e desde o início usei basicamente C.</p><p>Há uns 5 anos, comecei a usar C++ e em 2017 fiz meu primeiro projeto usando Python rodando em uma Placa Raspberry Pi.</p><p>Mas sempre ouvi falar sobre as vantagens da Linguagem Ada, foi então que finalmente resolvi aprendê-la.</p><p>Os primeiros passos tem sido muito difíceis. É necessário rever todos os conceitos solidificados por anos. Não tem mais aquela flexibilidade do C, para mexer com variáveis, ponteiros, estruturas e vetores.</p><p>Mas o interessante, é que lendo os tutoriais, me vem à mente diversos problemas que eu tive durante minha experiência com C. Muitas noites sem dormir, preocupações, dores de cabeça e muitas vezes a “culpa” era de um pequeno ponteiro com o qual não fui tão cuidadoso, um <em>buffer overflow</em> difícil de detectar, a falta de um <em>cast</em> que destruía uma variável vizinha. Quem trabalha com C ou C++ sabe exatamente do que estou falando.</p><p>Uma das grandes vantagens do Ada é evitar que erros como esse aconteçam.</p><h3>Como começar</h3><p>GNAT é o compilador Ada e eu sugiro instalar o GPS (<em>GNAT Programming Studio</em>) uma IDE com muitos bons recursos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*0vuheY69_NDsNyxsQrxq2w.png" /></figure><p>Você pode baixá-lo no <a href="https://www.adacore.com/community">site da Ada Core</a>.</p><h3>Tutoriais</h3><p>Assim que você instala o GPS, você encontra um <a href="http://docs.adacore.com/live/wave/gps/html/gps_tutorial/">tutorial</a> que explica todos os recursos do GPS. É um bom tutorial, mas se você não conhece Ada, sugiro se familiarizar com a linguagem primeiro.</p><p>Você pode encontrar alguns tutoriais na internet, minha sugestão é <a href="https://learn.adacore.com/">esse tutorial no site Learn Adacore.com</a>.</p><p>Se você é um programador C++ ou Java, também sugiro acompanhar esse tutorial: <a href="https://learn.adacore.com/books/Ada_For_The_CPP_Java_Developer/index.html">Ada For CPP and Java Developer</a>.</p><h3>Hello World!</h3><p>Como de costume, começamos com um programa Hello World! Nesse momento não será necessário utilizar o GPS, podemos rodá-lo pela linha de comando.</p><p>Mas antes, inclua no PATH do sistema operacional o diretório onde foi instalado o GNAT, seguido de \bin</p><p>No meu caso (Windows 10), D:\GNAT\2019\bin</p><p>Assegure-se que o programa gcc aponta para esse diretório:</p><pre>where gcc<br>D:\GNAT\2019\bin\gcc.exe</pre><p>Crie o arquivoHelloWorld.adb:</p><pre>with Ada.Text_IO;<br>use  Ada.Text_IO;</pre><pre>procedure HelloWorld is<br>begin<br>     Put_Line (&quot;Hello World!&quot;);<br>end Main;</pre><p>Para compilá-lo use gprbuild</p><pre>&gt;gprbuild HelloWorld.adb<br>using project file D:\GNAT\2019\share\gpr\_default.gpr<br>Compile<br>   [Ada]          helloworld.adb<br>Bind<br>   [gprbind]      helloworld.bexch<br>   [Ada]          helloworld.ali<br>Link<br>   [link]         helloworld.adb</pre><p>Agora, basta rodar seu novo projeto Ada HelloWorld!</p><pre>&gt;helloworld<br>Hello World!</pre><h3>Conclusão</h3><p>Sei que será uma jornada e tanto. E vou compartilhar aqui cada passo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4fc5361b490" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Ada Language]]></title>
            <link>https://medium.com/@ricardo_66479/learning-ada-language-a15ae46ccdfb?source=rss-81320e142d2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15ae46ccdfb</guid>
            <category><![CDATA[gnats]]></category>
            <category><![CDATA[gnat-programming-studio]]></category>
            <category><![CDATA[ada]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Programonauta]]></dc:creator>
            <pubDate>Tue, 18 Jun 2019 22:15:21 GMT</pubDate>
            <atom:updated>2019-07-24T22:36:31.611Z</atom:updated>
            <content:encoded><![CDATA[<p>Leia esse artigo em português <a href="https://medium.com/@ricardo_66479/aprendendo-a-linguagem-ada-e4fc5361b490">aqui</a></p><h3>It’s Never Too Late to Start</h3><p>This month I decided start my study in Ada Language. I work with embedded computers a long time (almost 30 years) and since the beginning using basically C.</p><p>About 5 years ago I started use C++ and in 2017 I did my first project using Python, running in a Raspberry Pi board.</p><p>But I always heard about the advantages of Ada Language. And finally I decided go deeply.</p><p>The first steps are being very hard. I need to change my mind set, forged for years working with C, where you have a great flexibility to deal with variables, pointers, structures, and arrays.</p><p>But what is very interesting, reading some tutorials, I remember some very big problems that I faced during my experience with C. A lot of nights without sleep, concerns, headaches, and some times was that little pointer I didn’t take care with it. A buffer overflow that was very difficult to detect, a missing cast that destroy the variable beside you are accessing. Who works with C and C++ knows exactly what I’m talking about.</p><h3>How to start</h3><p>GNAT is the ada compiler, and I suggest install GPS (GNAT Programming Studio) an IDE with a lot of great features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*0vuheY69_NDsNyxsQrxq2w.png" /></figure><p>You can download a Community Version in the <a href="https://www.adacore.com/community">Ada Core site</a>.</p><h3>Tutorials</h3><p>As soon as you install GPS, you can find a <a href="http://docs.adacore.com/live/wave/gps/html/gps_tutorial/">tutorial</a> that explain the features of GPS. It’s a very good tutorial, but if you don’t know Ada, I suggest get familiar with it first.</p><p>You can find some tutorials in the internet, but I suggest follow <a href="https://learn.adacore.com/">this tutorial on Learn Adacore.com</a>.</p><p>If you are a C++ or Java programmer, I also suggest read this: <a href="https://learn.adacore.com/books/Ada_For_The_CPP_Java_Developer/index.html">Ada For CPP and Java Developer</a>.</p><h3>Hello World!</h3><p>As usual, let’s start with a Hello World program. For now, it’s not necessary use GPS, you can run it from command line.</p><p>First, update the PATH environment variable with directory where GPS was installed followed by \bin.</p><p>In my case (Windows 10), D:\GNAT\2019\bin</p><p>Verify if gcc is pointed to this directory:</p><pre>where gcc<br>D:\GNAT\2019\bin\gcc.exe</pre><p>Create a file named HelloWorld.adb:</p><pre>with Ada.Text_IO;<br>use  Ada.Text_IO;</pre><pre>procedure HelloWorld is<br>begin<br>     Put_Line (&quot;Hello World!&quot;);<br>end Main;</pre><p>To compile use gprbuild</p><pre>&gt;gprbuild HelloWorld.adb<br>using project file D:\GNAT\2019\share\gpr\_default.gpr<br>Compile<br>   [Ada]          helloworld.adb<br>Bind<br>   [gprbind]      helloworld.bexch<br>   [Ada]          helloworld.ali<br>Link<br>   [link]         helloworld.adb</pre><p>Now, it’s just run your new Ada HelloWorld project!</p><pre>&gt;helloworld<br>Hello World!</pre><h3>Conclusion</h3><p>I know it will be a very excited journey, and I will share with you every step here.</p><p>Every new post I will create a link here</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15ae46ccdfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Counting pulses with ESP32]]></title>
            <link>https://medium.com/@ricardo_66479/counting-pulses-with-esp32-70b0d8dd2829?source=rss-81320e142d2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b0d8dd2829</guid>
            <category><![CDATA[esp-idf]]></category>
            <category><![CDATA[esp32-tutorial]]></category>
            <category><![CDATA[turbine-flow-sensor]]></category>
            <category><![CDATA[freertos]]></category>
            <category><![CDATA[ttgo-board]]></category>
            <dc:creator><![CDATA[Programonauta]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 00:37:40 GMT</pubDate>
            <atom:updated>2019-03-05T16:52:21.108Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an article to show how to count pulses generated by a flow sensor.</p><p>I used the Pulse Counter example from the <a href="https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/pcnt.html">espressif esp-idf framework site</a>. You can find the example on the <a href="https://github.com/espressif/esp-idf/tree/6c49f1924/examples/peripherals/pcnt">espressif Github</a>.</p><p>But I’d like to use a sensor flow to measure water flow. I bought a very cheap sensor. And my test used a ESP32 TTGO board from WeMos, as depicted in the Figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*T92iY2dx33koFcQfrszrRg.jpeg" /><figcaption>Flowmeter with TTGO Board</figcaption></figure><h3>Changes made on example program</h3><p>The example program uses GPIO4 as Pulse Input PIN. The pulse is generated internally by a pulse generator on GPIO18.</p><p>To demonstrate that pulse can increase or decrease the counting, they use a signal on GPIO5. If GPIO5 is connected to GND, the count value will be decreased, if leave floating with internal pull up, the count will increase.</p><h4>Remove Pulse Generator and Control Setup</h4><p>All references do PWM generator was removed. On the original code, try to find ledc .</p><h4>Remove reverse counting</h4><p>Makes no sense a reverse counting in a flow sensor, so all commands and variables that define low limits, and controls to make counter decrease values was removed.</p><p>In the events setup,( pcnt_example_init function), was removed the events threshold 0 and Low Limit reached.</p><h4>Make the counter bigger</h4><p>The type of variable used to store the pulses counting is intl16_t , so to assure there the counter will not reach the upper limit, I create an unsigned long variable, a multiplier and set upper limit to 1000. So each time the limit is reached the multiplier is increased.</p><p>You can find the complete code on my <a href="https://github.com/programonauta/pulse-counter">Github</a>.</p><pre>unsigned long counterPulses;</pre><pre>unsigned long multPulses = 0;</pre><pre>...<br>...</pre><pre>        } else {<br>            pcnt_get_counter_value(PCNT_TEST_UNIT, &amp;count);<br>            counterPulses = multPulses * PCNT_H_LIM_VAL + count;<br>            printf(&quot;Current counter value :%lu\n&quot;, counterPulses);<br>        }<br>    }</pre><p>To calculate the actual number of pulses, multiply the “multiplier” multPulses by limit PCNT_H_LIM_VAL and sum the current counter count</p><h3>Run the test</h3><h4>Connections</h4><p>This board has few documentation in the Internet, but the pinout is enough to the test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*wEtvJxaA47ESrY7QsmM7LQ.png" /><figcaption>TTGO WeMos Pinout</figcaption></figure><p><strong>Connection</strong></p><p>PIN 19 → 5V</p><p>PIN 50 → GND</p><p>PIN 28 → GPIO4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*IM9k4mz2qqIp_lmC04ptZg.png" /><figcaption>Connection TTGO Board — Flow sensor</figcaption></figure><h4>Finally running the program</h4><ol><li>Connect your board on the computer using serial port.</li><li>Compile and flash the code</li></ol><pre>idf.py build<br>idf.py -p &lt;your serial port&gt; flash</pre><p>3. View the results using the serial monitor</p><p>When the sensor identifies the flow (you can blow it) the count will start.</p><pre>I (0) cpu_start: App cpu up.<br>I (205) heap_init: Initializing. RAM available for dynamic allocation:<br>I (212) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM<br>I (218) heap_init: At 3FFB3308 len 0002CCF8 (179 KiB): DRAM<br>I (224) heap_init: At 3FFE0440 len 00003BC0 (14 KiB): D/IRAM<br>I (231) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM<br>I (237) heap_init: At 40088BF0 len 00017410 (93 KiB): IRAM<br>I (243) cpu_start: Pro cpu start user code<br>I (261) cpu_start: Starting scheduler on PRO CPU.<br>I (0) cpu_start: Starting scheduler on APP CPU.<br>Current counter value :0<br>Current counter value :0<br>Current counter value :78<br>Current counter value :217<br>Current counter value :361<br>Event PCNT unit[0]; cnt: 500<br>THRES1 EVT<br>Current counter value :614<br>Current counter value :890<br>Event PCNT unit[0]; cnt: 0<br>H_LIM EVT<br>ZERO EVT<br>Current counter value :1068<br>Current counter value :1077<br>Current counter value :1293<br>...</pre><p>I defined the High Limit in 1000 and Threshold 1 in 500, so you can notice in the monitor the register of these events.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b0d8dd2829" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instalação da IDE do Arduino]]></title>
            <link>https://medium.com/@ricardo_66479/instala%C3%A7%C3%A3o-da-ide-do-arduino-3c0cda91b0cf?source=rss-81320e142d2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c0cda91b0cf</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[arduino-ide]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Programonauta]]></dc:creator>
            <pubDate>Sun, 13 Jan 2019 14:13:45 GMT</pubDate>
            <atom:updated>2019-01-13T16:17:19.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*1af2mRnFrRE3Vkc5Sw2GWg.png" /></figure><h4>Download e Instalação da IDE</h4><p>Baixe e instale o software da Windows Store ou diretamente do <a href="https://www.arduino.cc/en/Main/Software">site oficial</a>. Lá tem versões para Linux, Windows e Mac.</p><p>Se você está usando Windows 10, pode instalar diretamente da Windows Store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*UEsudTHMJsOQf4fwPl1tIA.png" /><figcaption>Instalação do Arduino IDE a partir da Windows Store</figcaption></figure><h4>Conexão ao dispositivo pela porta USB</h4><p>Conecte o dispositivo na porta USB. E verifique a porta serial em Tools --&gt; Port<strong>.</strong></p><h4>Dispositivo não reconhecido pela IDE no Windows</h4><p>Se mesmo com o dispositivo conectado a opção Port continua desabilitada como na figura abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*wEOqxVMoPkzGKSLzRJn3YA.png" /></figure><ul><li>Vá no Painel de Controle do Windows e Selecione Sistema e Segurança --&gt; Sistema --&gt; Gerenciador de Dispositivos.</li><li>Procure na seção “Portas (COM e LPT)”. Você deverá encontrar um porta aberta com o nome do dispositivo.</li><li>Tente a instalação padrão do Windows</li><li>Se não funcionar, procure pelo drive na Internet, baixe e instale.</li></ul><p>Uma vez resolvido o problema, verifique se o programa reconheceu a porta serial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*uEZV1h8NDy5kivgk6paZig.png" /></figure><h4>Teste da instalação</h4><p>Para testar a placa e a configuração da porta, execute um programa exemplo simples que vem com a IDE:</p><p>File --&gt; Examples --&gt; 01.Basics --&gt;</p><p>Para compilar e transferir o programa para o dispositivo basta clicar nos botão Upload, segundo botão localizado logo abaixo da barra de menus.</p><p>Após compilar e enviar para o dispositivo o led da placa irá piscar a cada 1 segundo, indicando que a IDE está corretamente instalada e configurada.</p><p>A IDE está pronta para você começar a programar seu Arduino. A seguir os próximos passos para configurar com mais detalhes seu ambiente de desenvolvimento.</p><h4>Configuração do diretório padrão</h4><p>Para configurar o diretório padrão vá em File --&gt; Preferences --&gt; Sketchbook Location</p><p>É recomendável que seja utilizado o diretório indicado em sketchBook Locationpara todos os projetos, a fim de evitar duplicidade ou incompatibilidade de bibliotecas instaladas.</p><h4>Localização das Bibliotecas</h4><p>A IDE do Arduino já instala uma grande quantidade de bibliotecas, porém não será rara a necessidade de utilizar outras bibliotecas, ou até mesmo você criar suas próprias bibliotecas.</p><p>A IDE do Arduino procura as bibliotecas em dois diretórios:</p><ul><li>No subdiretório libraries abaixo do diretório padrão indicado em Sketchbook Location</li><li>Diretório de Instalação da IDE.</li></ul><h4>Como saber qual o diretório de instalação</h4><p>Nem sempre é fácil descobrir o diretório de instalação da IDE, principalmente no Windows, porém há uma forma para descobrir:</p><p>Abra qualquer um dos programas exemplo fornecidos pela IDE: File --&gt; Examples --&gt; 01.Basics --&gt; Blink</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*Yj8B9ybYL_CoFJAv3kIy5w.png" /></figure><p>Vá em Sketch --&gt; Show Sketch Folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*rEpGxHp-lueeSzs1AZ5TtQ.png" /></figure><p>O sistema operacional abrirá uma janela no diretório do arquivo blink.io</p><p>&lt;Diretório de Instalação da IDE&gt;/examples/01.Basics/Blin</p><h4>Sua IDE está instalada</h4><p>Sugiro que agora você navegue pelos programas exemplos e comece a diversão, fazendo pequenas alterações. Em pouco tempo você vai estar totalmente familiarizado com o ambiente.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c0cda91b0cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>