Wednesday, May 28, 2014

Arduino Code - 4017 Arduino Gateway

Add Analog In to the WebSocket protocol.

Digital Out

Turning on: "DOn=ON"
Turning off: "DOn=OFF"
n is channel number (0-7)
There is no reply.

Digital In

When you send "DI", it replies in "bbbbbbbb" format.
b is equal to each input channel, and it is either '0' or '1'.

Analog In

When you send "AIn", it replies in "+dd.ddd" format. 
n is channel number between 0 to 7. 
"+dd.ddd" is between -10.000 - +10.000.


The original is in posting: http://seosmartia.blogspot.kr/2014/05/arduino-code2-webarduinoadam.html

#include <SPI.h>
#include <Ethernet.h>
#include <WebSocket.h>
#include <SoftwareSerial.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x25, 0xC4 };
byte ip[] = { 192,168,219,16 };

WebSocket wsServer;

int DE485 = 2;
SoftwareSerial Soft485(3, 4);
void ADMA4017_config(void);

char rx485Ln[8];
int rx485ix;
void AdamReceiver(void);

void setup() {
 Serial.begin(9600);

 Soft485.begin(9600);
 pinMode(DE485, OUTPUT);
 ADMA4017_config(); // Only need to be configured once.

 Ethernet.begin(mac, ip);
 wsServer.registerConnectCallback(&onConnect);
 wsServer.registerDataCallback(&onData);
 wsServer.registerDisconnectCallback(&onDisconnect);
 wsServer.begin();
 delay(100);

 rx485ix = -1;
}

void loop() {
 wsServer.listen();
 AdamReceiver();
}

void onConnect(WebSocket &socket) {
 Serial.println("onConnect called");
}

void onDisconnect( WebSocket &socket ) {
 Serial.println("onDisconnect called");
}

void ADMA4017_config(void) {
 digitalWrite(DE485, HIGH);
 // refer to ADAM - 4017 Arduino Gateway posting
 Soft485.write("02080600");
 Soft485.write(0x0D);
 digitalWrite(DE485, LOW);
}

void onData(WebSocket &socket, char* rxLn, byte rxSz) {
 // Analog In
 if((rxLn[0] == 'A') && (rxLn[1] == 'I')) {
  digitalWrite(DE485, HIGH);
  // Analog In cmd for 4017 is #AAN(cr)
  Soft485.write("#00");
  Soft485.write(rxLn[2]);
  Soft485.write(0x0D);
  digitalWrite(DE485, LOW);
 }
}

void AdamReceiver(void) {
 char rxChr;

 if(Soft485.available()) {
  rxChr = Soft485.read();
  if(rxChr == '>')
   rx485ix = 0;
  else if(rx485ix >= 0) {
   if(rxChr == 0x0d) {
    // 4017's replay is >+dd.ddd(cr)
    if(rx485ix == 7) {
     // The reply conatins decimal pts like
     // "+09.456"; however, JS handles it very
     // well.
     wsServer.send(rx485Ln, 7);
    }
    rx485ix = -1;
   }
   else {
    rx485Ln[rx485ix++] = rxChr;
    if(rx485ix > 7) 
     rx485ix = -1;
   }
  }
 }
}

Full codes can be found in following links