SHARE
TWEET

Arduino RS485 VFD control

a guest Oct 10th, 2014 2,310 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <SoftwareSerial.h>
  2.  
  3. // RS485 connections
  4. // D8 = DI (TX)
  5. // D9 = DE
  6. // D10 = RE
  7. // D11 = RO (RX)
  8.  
  9. // adjust speed
  10. String     speed=":010203030BB837\r\n";
  11.  
  12.  
  13. char* read_speed=":01040300";
  14. char* change_speed=":010203030BB8";
  15. char* stop=":01030108";
  16. char* start=":01030101";
  17.  
  18.  
  19. SoftwareSerial myserial(11,8); // RX, TX
  20.  
  21. void setup() {
  22.  Serial.begin(9600);
  23.  pinMode(9,OUTPUT);
  24.  pinMode(10,OUTPUT);
  25.  myserial.begin(9600);
  26.  digitalWrite(9,LOW); digitalWrite(9,LOW);
  27. }
  28.  
  29. void setSpeed(int v) {
  30.     Serial.print("Set new speed "); Serial.println(v,DEC);
  31.     char* n=change_speed;
  32.   //char n[13];
  33.   //strcpy(n,change_speed);
  34.   n[9]=toHexa((v/256)>>4);
  35.   n[10]=toHexa((v/256)&0xf);
  36.   n[11]=toHexa((v&0xff)>>4);
  37.   n[12]=toHexa((v&0xff)&0xf);
  38. Serial.println(n);
  39.   query(n); // set new speed
  40. }
  41.  
  42. void loop() {
  43.  // while(myserial.available()) Serial.write(myserial.read());
  44.   delay(1000);
  45.  
  46.   query(start);
  47.   delay(10000);
  48.  
  49.   //delay(5000);
  50.   for(long v=1000; v<16000; v+=1000) {setSpeed(v); delay(5000); }
  51.  
  52.   query(stop);
  53.   delay(10000);
  54. }
  55.  
  56. void transmit(String msg) {
  57.   // activate driver
  58.   digitalWrite(9,HIGH); digitalWrite(9,HIGH);
  59.   delay(50);
  60.   myserial.print(msg);
  61.   delay(1);
  62.   digitalWrite(9,LOW); digitalWrite(9,LOW);
  63. }
  64.  
  65. char hexa(char byte) { // return hexa value of that ASCII char
  66.   if(byte<='9') return byte & 0x0f;
  67.   if(byte<='F') return (byte & 0x0f) + 9; // A=0x41 --> 0x0a
  68. }
  69.  
  70. char toHexa(int i) {
  71.  if(i<10) return 0x30 | i;
  72.  return 0x41 + i - 10;
  73. }
  74.  
  75. char crc(char* buffer) {
  76.  int l=strlen(buffer);
  77.  int i=1;
  78.  int chk=0;
  79.  while(i<l) { Serial.print(hexa(buffer[i])<<4|hexa(buffer[i+1]),HEX); chk+= ( hexa(buffer[i])<<4|hexa(buffer[i+1]) ); i+=2; Serial.print(" ");}
  80.  Serial.print(":"); Serial.println(chk,HEX);
  81.   Serial.println(0x100-chk,HEX);
  82.  return (0x100-chk) & 0xff;
  83. }
  84.  
  85. void query(char* cmd) {
  86.   char lrc = crc(cmd);
  87.   String msg = cmd;
  88.   msg+=toHexa((lrc&0xf0)>>4);
  89.   msg+=toHexa(lrc&0x0f);
  90.   msg+="\r\n";
  91.   Serial.print(msg);
  92.   transmit(msg);
  93. }
RAW Paste Data
Top