Commit b9050ff4 authored by Alisson Claudino's avatar Alisson Claudino

Separação de classes em arquivos e config. serial na interface

parent ffbf973f
#include "HX711.h"
// HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0
HX711 channelA(A1, A0,32); //Instancia um objeto da classe HX711 vinculado ao canal A
HX711 channelB(A1, A0,128); //Instancia um objeto da classe HX711 vinculado ao canal B
void setup() {
Serial.begin(115200); //Inicia a Serial com taxa de tranferência de 115200 bps
channelA.set_scale(); //Reseta a escala do canal A
channelA.tare(); //
channelB.set_scale(); //Reseta a escala do canal B
channelB.tare();
Serial.print("Primeira Leitura do Canal A: \t\t");
Serial.print(channelA.read()); // Primeira leitura do canal A
Serial.print("\n\n");
Serial.print("Primeira Leitura do Canal B: \t\t");
Serial.print(channelB.read()); // Primeira leitura do canal B
Serial.print("\n\n");
Serial.print("Primeira média do canal A (20): \t\t");
Serial.print(channelA.read_average(20)); // Imprime a média de 20 leituras do canal A
Serial.print("\n\n");
Serial.print("Primeira média do canal B (20): \t\t");
Serial.print(channelB.read_average(20)); // Imprime a média de 20 leituras do canal B
Serial.print("\n\n");
}
void loop() {
Serial.print("Leitura (Canal A):"); //Realiza uma leitura do canal A e imprime na serial
Serial.print(channelA.read());
Serial.print("\n\n");
delay(200);
Serial.print("Leitura (Canal B):"); //Realiza uma leitura do canal B e imprime na serial
Serial.print(channelB.read());
Serial.print("\n\n");
delay(500);
}
#include "HX711.h"
double a=0,b=0;
// HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0
HX711 channelA(A1, A0,32); //Instancia um objeto da classe HX711 vinculado ao canal A
//HX711 channelB(A1, A0,128); //Instancia um objeto da classe HX711 vinculado ao canal B
void setup() {
Serial.begin(9600); //Inicia a Serial com taxa de tranferência de 115200 bps
channelA.set_scale(); //Reseta a escala do canal A
channelA.tare(); //
//channelB.set_scale(); //Reseta a escala do canal B
//channelB.tare();
//channelA.set_offset(0);
//channelB.set_offset(0);
Serial.print("Primeira Leitura do Canal A: \t\t");
Serial.print(channelA.read()); // Primeira leitura do canal A
Serial.print("\n\n");
/*Serial.print("Primeira Leitura do Canal B: \t\t");
Serial.print(channelB.read()); // Primeira leitura do canal B
Serial.print("\n\n");*/
/* Serial.print("Primeira média do canal A (20): \t\t");
Serial.print(channelA.read_average(20)); // Imprime a média de 20 leituras do canal A
Serial.print("\n\n");
Serial.print("Primeira média do canal B (20): \t\t");
Serial.print(channelB.read_average(20)); // Imprime a média de 20 leituras do canal B
Serial.print("\n\n");*/
}
void loop() {
//channelA.set_gain(128);
//Serial.print("\nLeitura (Canal A):"); //Realiza uma leitura do canal A e imprime na serial
a=channelA.read();
Serial.println(a);
while(!channelA.is_ready())
{}
/*if(a<b)
{Serial.print("\n\n");
Serial.print("ESSE:");
Serial.print(b);
Serial.print("\n\n");}*/
//while(millis()%100!=0);
//Serial.println(millis());
/*Serial.print(" ");
Serial.print(millis());
Serial.println();*/
//Serial.print("\n\n");
/*channelA.set_gain(32);
Serial.print("Leitura (Canal B):"); //Realiza uma leitura do canal B e imprime na serial
Serial.print(channelA.read_average(5));*/
/*Serial.print("\n\n");
a=analogRead(A3);
a=a*5/1023;
Serial.println(a);
Serial.println(channelA.get_scale());
//Serial.println(channelB.get_scale());
Serial.println(channelA.get_offset());
//Serial.println(channelB.get_offset());*/
/*channelA.power_down();
delay(500);
channelA.power_up();*/
}
#include <Arduino.h>
#include <HX711.h>
#if ARDUINO_VERSION <= 106
// "yield" is not implemented as noop in older Arduino Core releases, so let's define it.
// See also: https://stackoverflow.com/questions/34497758/what-is-the-secret-of-the-arduino-yieldfunction/34498165#34498165
void yield(void) {};
#endif
HX711::HX711(byte dout, byte pd_sck, byte gain) {
begin(dout, pd_sck, gain);
}
HX711::HX711() {
}
HX711::~HX711() {
}
void HX711::begin(byte dout, byte pd_sck, byte gain) {
PD_SCK = pd_sck;
DOUT = dout;
pinMode(PD_SCK, OUTPUT);
pinMode(DOUT, INPUT);
set_gain(gain);
}
bool HX711::is_ready() {
return digitalRead(DOUT) == LOW;
}
void HX711::set_gain(byte gain) {
switch (gain) {
case 128: // channel A, gain factor 128
GAIN = 1;
break;
case 64: // channel A, gain factor 64
GAIN = 3;
break;
case 32: // channel B, gain factor 32
GAIN = 2;
break;
}
digitalWrite(PD_SCK, LOW);
read();
}
long HX711::read() {
// wait for the chip to become ready
while (!is_ready()) {
// Will do nothing on Arduino but prevent resets of ESP8266 (Watchdog Issue)
yield();
}
unsigned long value = 0;
uint8_t data[3] = { 0 };
uint8_t filler = 0x00;
// pulse the clock pin 24 times to read the data
data[2] = shiftIn(DOUT, PD_SCK, MSBFIRST);
data[1] = shiftIn(DOUT, PD_SCK, MSBFIRST);
data[0] = shiftIn(DOUT, PD_SCK, MSBFIRST);
// set the channel and the gain factor for the next reading using the clock pin
for (unsigned int i = 0; i < GAIN; i++) {
digitalWrite(PD_SCK, HIGH);
digitalWrite(PD_SCK, LOW);
}
// Replicate the most significant bit to pad out a 32-bit signed integer
if (data[2] & 0x80) {
filler = 0xFF;
} else {
filler = 0x00;
}
// Construct a 32-bit signed integer
value = ( static_cast<unsigned long>(filler) << 24
| static_cast<unsigned long>(data[2]) << 16
| static_cast<unsigned long>(data[1]) << 8
| static_cast<unsigned long>(data[0]) );
return static_cast<long>(value);
}
long HX711::read_average(byte times) {
long sum = 0;
for (byte i = 0; i < times; i++) {
sum += read();
yield();
}
return sum / times;
}
double HX711::get_value(byte times) {
return read_average(times) - OFFSET;
}
float HX711::get_units(byte times) {
return get_value(times) / SCALE;
}
void HX711::tare(byte times) {
double sum = read_average(times);
set_offset(sum);
}
void HX711::set_scale(float scale) {
SCALE = scale;
}
float HX711::get_scale() {
return SCALE;
}
void HX711::set_offset(long offset) {
OFFSET = offset;
}
long HX711::get_offset() {
return OFFSET;
}
void HX711::power_down() {
digitalWrite(PD_SCK, LOW);
digitalWrite(PD_SCK, HIGH);
}
void HX711::power_up() {
digitalWrite(PD_SCK, LOW);
}
#ifndef HX711_h
#define HX711_h
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
class HX711
{
private:
byte PD_SCK; // Power Down and Serial Clock Input Pin
byte DOUT; // Serial Data Output Pin
byte GAIN; // amplification factor
long OFFSET = 0; // used for tare weight
float SCALE = 1; // used to return weight in grams, kg, ounces, whatever
public:
// define clock and data pin, channel, and gain factor
// channel selection is made by passing the appropriate gain: 128 or 64 for channel A, 32 for channel B
// gain: 128 or 64 for channel A; channel B works with 32 gain factor only
HX711(byte dout, byte pd_sck, byte gain = 128);
HX711();
virtual ~HX711();
// Allows to set the pins and gain later than in the constructor
void begin(byte dout, byte pd_sck, byte gain = 128);
// check if HX711 is ready
// from the datasheet: When output data is not ready for retrieval, digital output pin DOUT is high. Serial clock
// input PD_SCK should be low. When DOUT goes to low, it indicates data is ready for retrieval.
bool is_ready();
// set the gain factor; takes effect only after a call to read()
// channel A can be set for a 128 or 64 gain; channel B has a fixed 32 gain
// depending on the parameter, the channel is also set to either A or B
void set_gain(byte gain = 128);
// waits for the chip to be ready and returns a reading
long read();
// returns an average reading; times = how many times to read
long read_average(byte times = 10);
// returns (read_average() - OFFSET), that is the current value without the tare weight; times = how many readings to do
double get_value(byte times = 1);
// returns get_value() divided by SCALE, that is the raw value divided by a value obtained via calibration
// times = how many readings to do
float get_units(byte times = 1);
// set the OFFSET value for tare weight; times = how many times to read the tare value
void tare(byte times = 10);
// set the SCALE value; this value is used to convert the raw data to "human readable" data (measure units)
void set_scale(float scale = 1.f);
// get the current SCALE
float get_scale();
// set OFFSET, the value that's subtracted from the actual reading (tare weight)
void set_offset(long offset = 0);
// get the current OFFSET
long get_offset();
// puts the chip into power down mode
void power_down();
// wakes up the chip after power down mode
void power_up();
};
#endif /* HX711_h */
const int tensao = A0;
int sensorValue = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
while(millis()%20!=0)
{}
sensorValue = analogRead(tensao);
Serial.print("\nSensor_1 :");
Serial.print(sensorValue);
Serial.print(",");
Serial.print(millis());
delay(1);
}
help:
@echo 'Help details:'
@echo 'hex: compile hex file'
@echo 'flash: install hex file'
@echo 'program: compile hex and install'
hex:
avr-gcc -Os -DF_CPU=16000000 -mmcu=atmega328p -c main.cpp
avr-gcc -DF_CPU=16000000 -mmcu=atmega328p -o main.elf main.o
avr-objcopy -O ihex main.elf main.hex
rm main.o
rm main.elf
flash:
avrdude -c arduino -p atmega328p -P /dev/ttyUSB0 -U flash:w:main.hex
This diff is collapsed.
from PyQt5 import QtCore,QtGui,QtWidgets # importação de classes
import pyqtgraph
import serial
import time
import sys
from CalibracaoP import Ui_MainWindow
class SerialManager(object):
def __init__(self):
self.ser = serial.Serial('/dev/ttyUSB0', 115200) # Inicialização da Serial com baudrate 115200bps
self.ser.setDTR(False) # Reset do arduino para reinicio da leitura
time.sleep(0.022)
self.ser.setDTR(True)
self.ser.readline() # Primeiro valor da serial sai com lixo
def read(self):
if(self.ser.inWaiting()==0):
pass
return self.ser.readline()
class Graph(pyqtgraph.GraphicsLayout):
......@@ -40,13 +23,13 @@ class Graph(pyqtgraph.GraphicsLayout):
self.x1=[]
self.y1=[]
self.y2=[]
self.timeant=time.time()
#self.p1.enableAutoScale()
def updateGraph(self,y1,y2):
print(time.time()-self.timeant)
self.y1.append(y1)
self.y2.append(y2)
if len(self.y1)>self.x_range+1:
del self.y1[0]
del self.y2[0]
......@@ -57,11 +40,16 @@ class Graph(pyqtgraph.GraphicsLayout):
self.curve1.setData(self.x1, self.y1)
self.curve2.setData(self.x1,self.y2)
self.timeant = time.time()
def setGraphScale(self,x_range,y_range):
if(x_range==0):
x_range=1
def setGraphScale(self,x_range,y_range):
if(y_range==0):
y_range=1
self.x_range=x_range
self.y_range=y_range
self.x1=[]
......@@ -73,43 +61,4 @@ class Graph(pyqtgraph.GraphicsLayout):
self.p1.setXRange(0, self.x_range, padding=0)
self.p1.setYRange(0, self.y_range, padding=0)
self.curve1=self.p1.plot(pen=self.color1)
self.curve2=self.p1.plot(pen=self.color2)
class SystemEngine(object):
def __init__(self):
self.app = QtWidgets.QApplication(sys.argv)
self.dialog = QtWidgets.QMainWindow()
self.ser1 = SerialManager()
self.uiCalibra1 = Ui_MainWindow()
self.uiCalibra1.setupUi(self.dialog)
self.layout = Graph(100, 10230, 900, 600, 'r','g')
self.scene = QtGui.QGraphicsScene()
self.scene.addItem(self.layout)
self.uiCalibra1.sceneSelector(self.scene)
self.dialog.showMaximized()
self.prev_x_scale=100
self.x_scale=100
def updateData(self):
readData = self.ser1.read() # Lê o dado da serial
readData = readData.decode('utf8')
dado = readData.split(' ', 3)
self.x_scale=int(self.uiCalibra1.f_max.text())
if(self.x_scale != self.prev_x_scale):
self.layout.setGraphScale(int(self.x_scale),32700)
self.prev_x_scale = self.x_scale
self.layout.updateGraph(float(dado[0]),float(dado[1]))
if __name__ == '__main__':
engine=SystemEngine()
timer = QtCore.QTimer() #
timer.timeout.connect(engine.updateData) #
timer.start(0)
sys.exit(engine.app.exec_())
self.curve2 = self.p1.plot(pen=self.color2)
\ No newline at end of file
from PyQt5 import QtCore,QtGui,QtWidgets # importação de classes
import pyqtgraph
import serial
import serial.tools.list_ports
import time
import sys
from SerialManager import SerialManager
from CalibracaoP import Ui_MainWindow
from SystemEngine import SystemEngine
from Graph import Graph
if __name__ == '__main__':
engine=SystemEngine()
timer = QtCore.QTimer() #
timer.timeout.connect(engine.updateData) #
timer.start(0)
sys.exit(engine.app.exec_())
This diff is collapsed.
from PyQt5 import QtGui, QtCore, QtWidgets #importação de classes
import pyqtgraph as pg
import serial
import time
from CalibracaoP import Ui_MainWindow
ser = serial.Serial('/dev/ttyUSB0', 115200) #Inicialização da Serial com baudrate 115200bps
ser.setDTR(False) #Reset do arduino para reinicio da leitura
time.sleep(0.022)
ser.setDTR(True)
ser.readline() #Primeiro valor da serial sai com lixo
app = QtGui.QApplication([])
pg.setConfigOption('foreground', 'c')
window=Ui_MainWindow()
dialog = QtWidgets.QMainWindow()
window.setupUi(dialog)
layout = pg.GraphicsLayout()
scene=QtGui.QGraphicsScene()
window.sceneSelector(scene)
scene.addItem(layout)
p1 = layout.addPlot()
p1.showGrid(True,True)
p1.addLegend()
curve1 = p1.plot(pen='r',name="Sensor 1")
curve2 = p1.plot(pen='g',name="Sensor 2")
curve3 = p1.plot(pen='w',name="Sensor 3")
curve4 = p1.plot(pen='y',name="Sensor 4")
curve5 = p1.plot(pen='b',name="Sensor 5")
curve6 = p1.plot(pen='m',name="Sensor 6")
curve7 = p1.plot(pen='c',name="Sensor 7")
curve8 = p1.plot(name="Sensor 8")
#window.CentralGraph.setFixedSize(690,550)
layout.setPreferredSize(900,550)
y1 = [] #Inicialização da lista dinâmica dos valores de y
y2 = []
y3 = []
y4 = []
y5 = []
y6 = []
y7 = []
y8 = []
x1 = [] #Inicialização da lista dinâmica dos valores de x
x_max = 200 #Variável que define o tamanho do eixo
indx = 0 #Variável auxiliar de contagem
p1.setYRange(0, 5, padding=0) #Define os limites do gráfico
p1.setXRange(0, x_max, padding=0)
p1.setLabel("bottom","Tempo",'s')
p1.setLabel("left","Força",'Tonf')
p1.setLabel("right","Tensão no Calibrante",'V')
dialog.showMaximized()
def update(): #Método para atualizar os arrays com valores de x, y e atualizar o gráfico
global curve1,curve2, indx, y1, x1, ser #Dá acesso das variáveis globais à função
while (ser.inWaiting() == 0): #Aguarda a serial liberar dado
pass
readData = ser.readline() #Lê o dado da serial
readData=readData.decode('utf8')
dado=readData.split(' ',8)
print(dado[3])
y1.append(float(dado[0])*5/32767) #Armazena o dado na lista do eixo y
y2.append(float(dado[1])*5/32767)
y3.append(float(dado[2])*5/32767)
y4.append(float(dado[3])*5/32767)
y5.append(float(dado[4])*5/32767)
y6.append(float(dado[5])*5/32767)
y7.append(float(dado[6])*5/32767)
y8.append(float(dado[7])*5/32767)
indx += 1 #Adiciona um na variavel auxiliar
if len(y1) > x_max-1: #Verifica se foi excedido o tamanho máximo do eixo x para o array
del y1[0] #Caso sim, libera o valor da primeira posição para manter o array, e consequentemente o gráfico, com escala constante
del y2[0]
del y3[0]
del y4[0]
del y5[0]
del y6[0]
del y7[0]
del y8[0]
indx = x_max #impede indx de divergir
else:
x1.append(indx) #Vai adicionando valores de 0 a x_max no eixo x até que a lista x lote e tenha mesmo tamanho da lista y
window.forcaLabel.setText(dado[0])
window.calibranteLabel.setText(dado[1])
curve1.setData(x1,y1) #Atualiza os dados da curva
curve2.setData(x1,y2)
curve3.setData(x1,y3)
curve4.setData(x1,y4)
curve5.setData(x1, y5)
curve6.setData(x1, y6)
curve7.setData(x1, y7)
curve8.setData(x1, y8)
#app.processEvents() #
timer = QtCore.QTimer() #
timer.timeout.connect(update) #
timer.start(0) #
if __name__ == '__main__': #
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_'): #
QtGui.QApplication.instance().exec_()
import serial
import serial.tools.list_ports
import time
class SerialManager(object):
def __init__(self):
self.portList = serial.tools.list_ports.comports()
self.portNum=len(self.portList)
for i in range (0,self.portNum):
print(self.portList[i].device)
def startPort(self,port,baud):
self.ser = serial.Serial(port, baud) # Inicialização da Serial com baudrate 115200bps
self.ser.setDTR(False) # Reset do arduino para reinicio da leitura
time.sleep(0.022)
self.ser.setDTR(True)
self.ser.readline() # Primeiro valor da serial sai com lixo
def read(self):
if(self.ser.inWaiting()==0):
pass
return self.ser.readline()
\ No newline at end of file
from PyQt5 import QtCore,QtGui,QtWidgets # importação de classes
import pyqtgraph
import serial
import serial.tools.list_ports
import time
import sys
from SerialManager import SerialManager
from CalibracaoP import Ui_MainWindow
from Graph import Graph
class SystemEngine(object):
def __init__(self):
self.app = QtWidgets.QApplication(sys.argv)
self.dialog = QtWidgets.QMainWindow()
self.ser1 = SerialManager()
print(self.ser1.portList[0])
self.ser1.startPort(str(self.ser1.portList[1].device),115200)
self.uiCalibra1 = Ui_MainWindow()
self.uiCalibra1.setupUi(self.dialog)
self.uiCalibra1.serialListPanel(self.ser1.portList)
self.layout = Graph(100, 37500, 900, 600, 'r','g')
self.scene = QtGui.QGraphicsScene()
self.scene.addItem(self.layout)
self.uiCalibra1.sceneSelector(self.scene)
self.dialog.showMaximized()
self.prev_x_scale=100
self.x_scale=100
def updateData(self):
readData = self.ser1.read() # Lê o dado da serial
readData = readData.decode('utf8')
dado = readData.split(' ', 8)
self.x_scale=int(self.uiCalibra1.t_max.text())
if(self.x_scale != self.prev_x_scale):
self.layout.setGraphScale(int(self.x_scale),32700)
self.prev_x_scale = self.x_scale
self.layout.updateGraph(float(dado[0]),float(dado[1]))
\ No newline at end of file
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(703, 460)
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.CentralGraph = QtWidgets.QGraphicsView(self.centralWidget)
self.CentralGraph.setGeometry(QtCore.QRect(160, 20, 481, 361))
self.CentralGraph.setObjectName("CentralGraph")
self.ForceDisp = QtWidgets.QLabel(self.centralWidget)
self.ForceDisp.setGeometry(QtCore.QRect(60, 200, 57, 17))
self.ForceDisp.setObjectName("ForceDisp")
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 703, 23))
self.menuBar.setObjectName("menuBar")
self.menuXuxuzinho = QtWidgets.QMenu(self.menuBar)
self.menuXuxuzinho.setObjectName("menuXuxuzinho")
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
self.menuBar.addAction(self.menuXuxuzinho.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "SADAM - Análise de Dados"))
self.ForceDisp.setText(_translate("MainWindow", "TextLabel"))
self.menuXuxuzinho.setTitle(_translate("MainWindow", "Arquivo"))
def sceneSelector(self,scene):
self.CentralGraph.setScene(scene)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment