Fixar det I morgon kväll!Isaksson skrev:Jag skulle tycka det vore intressant att se koden till arduino, om du inte har något emot att posta den?
Exakt det fick jag!Isaksson skrev:Förresten, när du körde din sensor med koden från elmätaren, fick du då "Timed out listening fir data" eller fick du något annat svar tillbaka?
Kod: Markera allt
LOOP FOREVER
SetBaud(300)
Send("\#1")
Flush()
SetBaud(1200)
noofparityerrors=0
LOOP FOREVER
Receive(char)
IF parityerror(char)
noofparityerrors++
message = message + (char & 127)
IF length(message) >= 79
break
IF timeout
break
END LOOP
IF noofparityerrors > 0
print("Parity error: " + message)
ELSE
IF length(message) < 79
print("Too short: " + message)
ELSE
print(message)
END LOOP
Kod: Markera allt
ptr = strtok(message, ' ')
if (ptr) print(atol(ptr) / 100.0)
ptr = strtok(message, NULL)
if (ptr) print(atol(ptr) / 1000.0)
osv.
Kod: Markera allt
#include <SoftwareSerial.h>
// Pin definitions
#define PIN_KAMSER_RX 9 // Kamstrup IR interface RX
#define PIN_KAMSER_TX 10 // Kamstrup IR interface TX
#define PIN_LED 13 // Standard Arduino LED
SoftwareSerial kamSer(PIN_KAMSER_RX, PIN_KAMSER_TX, false); // Initialize serial
void setup () {
Serial.begin(57600);
Serial.print("Initializing...");
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, 0);
// setup kamstrup serial
pinMode(PIN_KAMSER_RX,INPUT);
pinMode(PIN_KAMSER_TX,OUTPUT);
Serial.println("done.");
}
bool parity_check(unsigned input) {
bool inputparity = input & 128;
int x = input & 127;
int parity = 0;
while(x != 0) {
parity ^= x;
x >>= 1;
}
if ( parity & 0x1 != inputparity )
return(1);
else
return(0);
}
void loop () {
byte sendmsg1[] = { 175,163,177 }; // /#1 with even parity
byte r = 0;
byte to = 0;
byte i;
char message[255];
int parityerrors;
digitalWrite(PIN_LED, 1);
kamSer.begin(300);
for (int x = 0; x < 3; x++) {
kamSer.write(sendmsg1[x]);
}
kamSer.flush();
kamSer.begin(1200);
to = 0;
r = 0;
i = 0;
parityerrors = 0;
char *tmpstr;
float m_energy, m_volume, m_tempin, m_tempout, m_tempdiff, m_power;
long m_hours, m_flow;
while(r != 0x0A)
{
if (kamSer.available())
{
// receive byte
r = kamSer.read();
if (parity_check(r))
{
parityerrors += 1;
}
r = r & 127; // Mask MSB to remove parity
message[i++] = char(r);
}
else
{
to++;
delay(25);
}
if (i>=79)
{
if ( parityerrors == 0 )
{
Serial.print("OK: " );
message[i] = 0;
tmpstr = strtok(message, " ");
if (tmpstr)
m_energy = atol(tmpstr)/1000.0;
else
m_energy = 0;
tmpstr = strtok(NULL, " ");
if (tmpstr)
m_volume = atol(tmpstr)/100.0;
else
m_volume = 0;
tmpstr = strtok(NULL, " ");
if (tmpstr)
m_hours = atol(tmpstr);
else
m_hours = 0;
tmpstr = strtok(NULL, " ");
if (tmpstr)
m_tempin = atol(tmpstr)/100.0;
else
m_tempin = 0;
tmpstr = strtok(NULL, " ");
if (tmpstr)
m_tempout = atol(tmpstr)/100.0;
else
m_tempout = 0;
tmpstr = strtok(NULL, " ");
if (tmpstr)
m_tempdiff = atol(tmpstr)/100.0;
else
m_tempdiff = 0;
tmpstr = strtok(NULL, " ");
if (tmpstr)
m_power = atol(tmpstr)/10.0;
else
m_power = 0;
tmpstr = strtok(NULL, " ");
if (tmpstr)
m_flow = atol(tmpstr);
else
m_flow = 0;
Serial.print(m_energy,3);
Serial.print(" ");
Serial.print(m_volume);
Serial.print(" ");
Serial.print(m_hours);
Serial.print(" ");
Serial.print(m_tempin);
Serial.print(" ");
Serial.print(m_tempout);
Serial.print(" ");
Serial.print(m_tempdiff);
Serial.print(" ");
Serial.print(m_power,1);
Serial.print(" ");
Serial.print(m_flow);
Serial.println("");
}
else
{
Serial.print("ERR(PARITY): " );
message[i] = 0;
Serial.println(message);
}
break;
}
if (to>100)
{
message[i] = 0;
Serial.print("ERR(TIMEOUT):" );
Serial.println(message);
break;
}
}
digitalWrite(PIN_LED, 0);
delay(58000);
}
Kod: Markera allt
#!/usr/bin/python
# -*- coding: latin-1 -*-
import sys
import serial
import signal
import time
import datetime
import MySQLdb
import os.path
traceenabled = False
logenabled = True
def TracePrint(text):
global traceenabled
if traceenabled == True:
print(str(datetime.datetime.now()) + " " + text)
sys.stdout.flush()
def LogPrint(text):
global logenabled
global logenabled
if logenabled == True or traceenabled == True:
print(str(datetime.datetime.now()) + " " + text)
sys.stdout.flush()
def ConnectDB():
global db
db = None
TracePrint("ConnectDB(): Attempting to connect to MySQL")
try:
db = MySQLdb.connect("", "pi", "", "onewire")
TracePrint("ConnectDB(): Succeeded to connect!")
except MySQLdb.Error as e:
LogPrint("ConnectDB(): ERROR: " + str(e))
def InsertValuesToDB( line ):
global db
sqlstmt1 = "INSERT INTO data VALUES ( NOW(), 3, 1, " + line.split(" ")[4] + ", 1, 1 )"
sqlstmt2 = "INSERT INTO data VALUES ( NOW(), 3, 2, " + line.split(" ")[5] + ", 1, 1 )"
sqlstmt3 = "INSERT INTO data VALUES ( NOW(), 3, 3, " + line.split(" ")[7] + ", 1, 1 )"
sqlstmt4 = "INSERT INTO data VALUES ( NOW(), 3, 4, " + line.split(" ")[8] + ", 1, 1 )"
if ( db is None ):
TracePrint("InsertValuesToDB(): We're not connected to database, lets reconnect")
ConnectDB()
if ( db is None ):
LogPrint("InsertValuesToDB(): ERROR: No DB connection to execute SQL statement")
else:
try:
TracePrint("InsertValuesToDB(): About to execute:")
TracePrint(" " + sqlstmt1 )
TracePrint(" " + sqlstmt2 )
TracePrint(" " + sqlstmt3 )
TracePrint(" " + sqlstmt4 )
cursor=db.cursor()
cursor.execute(sqlstmt1)
cursor.execute(sqlstmt2)
cursor.execute(sqlstmt3)
cursor.execute(sqlstmt4)
TracePrint("InsertValuesToDB(): Committing" )
db.commit()
cursor.close()
TracePrint("InsertValuesToDB(): Done" )
except MySQLdb.Error as e:
LogPrint("InsertValuesToDB(): ERROR: " + str(e))
db.close()
db = None
def signal_handler(signal, frame):
LogPrint("Program terminated by SIGTERM signal.")
cleanupandexit();
def cleanupandexit():
if db != None:
db.close()
sys.exit(0)
print("Python version: " + str(sys.version) )
print("Log is: " + str(logenabled) )
print("Trace is: " + str(traceenabled) )
sys.stdout.flush()
signal.signal(signal.SIGTERM, signal_handler)
ConnectDB()
LogPrint("Opening /dev/ttyUSB0")
ser = serial.Serial('/dev/ttyUSB0',57600)
line = ser.readline()
while 1 :
try:
line = ser.readline().rstrip()
TracePrint("Got line from arduino: " + line );
if line.count(' ') == 8 and line.split(" ")[0] == "OK:":
if os.path.isfile('/mnt/1wire/bus.1/FF.CA0800000100/line20.1'):
TracePrint("Updating LCD")
f1=open('/mnt/1wire/bus.1/FF.CA0800000100/line20.1', 'w')
f1.write("Fv:%5skW" % (line.split(" ")[7]))
f1.close()
else:
TracePrint("LCD 1-wire file not found.")
InsertValuesToDB(line)
else:
LogPrint(line)
except KeyboardInterrupt:
LogPrint("Program terminated by keyboard interrupt.")
cleanupandexit()