Showing posts with label fun. Show all posts
Showing posts with label fun. Show all posts

May 16, 2014

Módulo de acesso a redes TCP/IP ENC28J60

Ola

Já faz algum tempo que não posto nada sobre Arduino / sistemas embarcados; bom, como você já deve saber... ok, não vou usar a velha desculpa de falta de tempo.

Estou aqui para dizer que não estou estagnado no meu aprendizado sobre o Arduino e também para falar sobre minha última vitória; a mais ou menos um ano e meio, eu comprei um módulo Ethernet (ENC28J60) igual ao que segue abaixo para fazer alguns experimentos.

Acontece que eu nunca consegui fazer o mesmo funcionar; acabei apelando e comprando um Ethernet Shield (baseado no W5100) o qual funcionou sem maiores problemas. Outro dia eu estava mexendo nas minhas tralhas de eletrônica e encontrei o dito cujo (aquele que eu não havia conseguido fazer funcionar) e decidi que iria tentar novamente.

Depois de ler vários blogs, artigos, etc na internet, acabei obtendo sucesso. Abaixo segue a configuração que eu utilizei:
Veja abaixo como ficaram as conexões:

ArduinoENC28J60
ICSP
HEADER
MISOSO
MOSISI
SCKSCK
RESETRST
PINOS
I/O
VCC (3.3V)VCC
GNDGND
10CS
INT(2)INT






Veja abaixo um ótimo diagrama do Arduino Leonardo.



Observe que no Arduino Mega / Uno e outros, o conector ICSP também esta conectado aos pinos normais de I/O (mas não no Leonardo).


Como eu comentei, tive que fazer uma mudança na biblioteca utilizada para acessar o módulo. Básicamente no arquivo EtherCard/enc28j60.cpp eu mudei:

void ENC28J60::initSPI () {
    pinMode(SS, OUTPUT);
    digitalWrite(SS, HIGH);

    // rest of the code....
}

para:

void ENC28J60::initSPI () {
     pinMode(10, OUTPUT);
     digitalWrite(10, HIGH);


    // rest of the code....

Isso porque o pino SS esta definido com um valor (17) diferente do pino que eu escolhi, 10.

E pronto! Depois disso foi só abrir um dos exemplos da biblioteca, modificá-lo um pouco e temos temos um web server rodando no Arduino.

O que você acha? Eu acho isso muito massa ;)

Não hesite em deixar comentários / perguntas / sugestões / críticas.

Happy Coding.

OBS: Antes de postar eu notei no esquema de pinagens que no Leornardo o pino SS (17) é o pino A3; então teóricamente é possível utilizar a biblioteca citada sem modificações (basta ligar o pino CS do módulo no pino A3 do Arduino; teóricamente pois eu não testei :)

(Read this post in English)

Mar 5, 2014

Running scripts on google drive documents

Hi.

I admit I have always looked to "cloud based" document editing (such as google drive, Microsoft Office 365, etc) with certain dislike, mainly due to the misconception that these applications would not allow me to use my precious scripts (after all, any true developer shall use scripts everywhere, right? ;)

Even though I somewhat disliked the idea, I ended up ceding (the convenience of having it available anywhere is so hard to ignore :) and,for some time, I have been using one spreadsheet to store a piece of information I use on a monthly basis.

It happens that last week I decided that one of the tasks involving that spreadsheet should be automated (basically, given some condition I'd like to add some information to a specific cell, which is a perfect job for a script) so I was considering moving the spreadsheet to my box and use LibreOffice (which I highly recommend, by the way) to edit it. 

While I was poking around my google spreadsheet menus, I stumbled in "Tools/Script Editor" menu option and realized that my resistance in using such online solutions had no ground whatsoever, i.e, it was just prejudice from my side :( I just selected that menu option and voila, scripts with debugging support!

That is all I needed! Some time (and a lot of keystrokes) later and I had my first script running; but the best was yet to come: not only I was able to reference my newly created function, but I could also schedule it to run from time to time! (that's exactly what I was looking for).

Following you can see my script:
function checkDate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];       
    
  var range = sheet.getRange("A1");
  
  var now = new Date();
  
  if (now.getHours() <= 10 || (now.getHours() >= 15 && now.getMinutes() > 30) || (now.getHours() >= 13 && (now.getHours() <= 14 && now.getMinutes() < 30)) ) {    
    range.setBackground("ORANGE");
    range.setValue("CLOSED");
  }
  else {
    range.setBackground("GREEN");
    range.setValue("OPEN");
  }
}
And it worked like a charm.

To my astonishment, today I figured it out that I can even execute WebServices (SOAP) from within my scripts (and of course I put it in action immediately) ! 

Happy Coding!

(Leia, uma versão extendida, deste post em portugues)

Aug 8, 2012

Connecting Nokia 5110 LCD breakout to Arduino

Hi

As I said in my last post, I have been playing with some hardware parts for Arduino.


In the "still to go" list I had:

  • Ethernet breakout
  • External EEPROM
  • RTC (DS 1307)
  • Nokia 5110 LCD
My plan was to tackle at least 2 of them during last weekend but I had a problem: all of this parts requires external components that I didn't have at hand. So I went to a local component shop but unfortunately I could not find most of the parts. 

The only part I had the required "missing" components was the Nokia LCD so I googled for "Nokia 5110 LCD  on Arduino" and voilá! The third entry in the results links to one great source of information about Arduino (and electronics in general). Now I was ready to start; I pulled my Arduino board, breadboard, the LCD (and required components) and put myself to connect them together.


My first disappointment came when I uploaded the sample application and nothing happened :(
Oopss.. maybe I have messed up with the connections... , let's see, pin x goes to y, pin z goes to w... no, everything looks connected correctly. After some head scratching I finally decided to do what I should have done from the beginning: Make sure the pin on my LCD breakout board matched the one in the Laydada  guide and of course they didn't! Compare the two pictures below (the red one is  mine and the blue one is the one used by ladyada):
As you can see they have different pinouts! Next step was to carefully reconnect the LCD and power on my Arduino (crossing my fingers hoping nothing bad had happened to neither my Arduino nor the LCD); this time everything but the backlight worked as expected; for some reason I could not explain the backlight refused to light up.  I checked and re-checked the connections many times but could not spot the problem. 

But at some point, during my investigation I could swear having seen the  backlight turning on and off; after some more testing I found out: by mistake I connected the backlight pin to the Arduino ground and that did the trick. But wait, both the LCD breakout schematic (not shown here) and the board itself does states that I should connect 3.3v on that pin... I have no idea what's happening here, but it is working. 

Next stop: external EEPROM.


Happy programming.

Jul 28, 2012

My new remote control (as a prototype so far)

Hi.


Moving on with my Arduino experiments I decided to experiment with the infrared library (I said in the original post that one should be able to find a library for almost any piece of hardware he/she want to connect to Arduino) :).


After some research I found this library which worked almost out of the box. The only problem with this library is that it don't have the definitions for my TV (Samsung) so the only option would be to use "raw" data which is not as convenient as the "sendXXX()/decodeXXX()" methods. After a little bit more research I was able to find this post which describes how to change the IR library to work with Samsung TVs).


So here is the prototype for my new remote control. 




So far it is pretty limited (only turn on/off the tv) but I have big plans for it :)


Happy programming.


Adriano

Jan 26, 2012

Interfaces in IL

After a long period of silence, today I've something interesting (IMHO) (and the time to, of course :)) to post about.

Last night I was reading a book about MS IL (intermediate language) when suddenly I stumbled with an intriguing paragraph about interfaces. The "intriguing" part motivated me to write a sample application to test whenever that would be valid in C# or not.
Given the following NUnit test, how can you define a type "IAmAnInterface" so it can pass ?
 
using System;
using NUnit.Framework;

namespace Testing
{
 
 [TestFixture]
 public class BlobPost_Interface
 {
  [Test]
  public void Test()
  {
   var type = typeof(IAmAnInterface);
   Assert.That(type.IsInterface, Is.True);

   var field = type.GetField("fld");
   Console.WriteLine("    Field: {0}", field);
   Assert.That(field, Is.Not.Null);

   field.SetValue(null, 10);

   Assert.That(field.GetValue(null), Is.EqualTo(10));
  }
 }
}

Just in case you missed it, the crux here, is that the test expects IAmAnInterface to be an interface and (and here lies the issue) to define a (static) field! 

How come? An interface with fields?

Well, it happens that the C# specification (and the compiler also!) disallows such constructs, but they are actually valid in IL (as described in Common Language Infrastructure ,session 8.9.4)!

So, in order to get this to work I simply created an assembly in IL (actually I disassembled an assembly written in C# and changed it) that looks like:
.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         
  .ver 4:0:0:0
}
.assembly TestString
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78   // ....T..WrapNonEx
                                                                                                             63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 )       // ceptionThrows.
  .hash algorithm 0x00008004
  .ver 0:0:0:0
}
.module TestString.dll
// MVID: {64C46A76-194E-4608-A835-B41B179AF4FA}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003       // WINDOWS_CUI
.corflags 0x00000001    //  ILONLY
// Image base: 0x004D0000


// =============== CLASS MEMBERS DECLARATION ===================

.class interface public abstract auto ansi IAmAnInterface
{
  .method public hidebysig newslot specialname abstract virtual 
          instance int32  get_value() cil managed
  {
  } // end of method IAmAnInterface::get_value
  
  .field public static int32 fld

} // end of class IAmAnInterface


// =============================================================

and referenced it in my C# test application inside VS2010 which happily showed the field in IntelliSense but gave an error when I tried to compile the code (so I resorted to reflection, and it worked) (see picture below):
What do you think?

Best

Adriano

Aug 1, 2008

Here we come again :)

For some time now, my computer started to give me signs that its time is coming. It's a pity since it is only 2 years old and has a not so bad configuration. For me, it's always a dichotomy between a pain and a pleasure when I need to figure out a new configuration. Should I go for a brand computer or should I build it myself? Should I by the latest/fastest/expansive(est) :) processor/memory/whatever (in a useless try to protect my investment) or should I stick to more affordable parts? Please, keep in mind that I live in Brasil and here computers are not so cheap as in some other places. Anyway, just for fun, I am dumping all my previous computer's configuration along side my wishes for the new one:
Year Processor Freq. # Core RAM Hard Disk Graphics Card Internet
1989 6502 0,75 Mhz 1 256 Kb NA OnBoard NA
1992 Ciryx 486 DLC 40 Mhz 1 4 Mb 100 Mb Trident NA
1996 Pentium 100 100 Mhz 1 16 Mb 1.0 Gb ? 28 Kbps
1999 Athlon 400 400 Mhz 1 128 Mb 30 Gb 4 Mb 56 Kbps
2002 Athlon XP 2.1 1.8 Ghz 1 512 Mb 60 Gb AGP 64Mb 350 Kbps
2006 Athlon 64 3.8 X2 2.0 Ghz 2 2.0 Gb 370 Gb PCI-X 256Mb 2.0 Mbps
2008? Core 2 Quad 9XXXX > 2.50 Ghz 4 8.0 Gb 500 Gb PCI-X 256Mb 6.0 Mbps
Well, what can I say? Current PC, RIP :) What do you think? Adriano

Jun 2, 2008

New programing language!

Hi! Today I got an "job opportunity" from one of jobs sites I'm registered (no, I'm not looking for a new job, I just didn't unregistered) with a really intriguing subject:
A skilled professional with 3 years of experience in C, Sharp and VB.NET.
I have to admit that I do know C and also a little of VB.NET, but I have never seen SHARP :) Ok, probably it was just a mistyping, but I bet the person who wrote this subject has no idea about programing languages whatsoever ;)