2016-10-27 4 views
1

У меня есть программа python, которая берет данные из mcp3008 и датчика дождя. Я хочу отобразить его в gui, используя wxpython. Это моя сенсорная программа:Как отображать и динамически обновлять несколько статических текстов wxpython с данными из mcp3008?

import spidev 
from time import sleep 
import os 

spi = spidev.SpiDev() 
spi.open(0,0) 

def getAdc (channel): 
    if ((channel>7)or(channel<0)): 
     return -1 

    r = spi.xfer2([1, (8+channel) << 4, 0]) 

    adcOut = ((r[1]&3) << 8) + r[2] 
    percent = int(round(adcOut/10.24)) 
    volts = ((adcOut/1023) * 5) 
    if adcOut >= 0 and adcOut <= 300: 
      print "--------------------------------------------------------------" 
      print ("ADC Output:  {0:4d} Percentage: {1:3}% Voltage : {2} V".format(adcOut,percent,volts)) 
      print ("Rain Condition : Heavy Rain") 
      sleep(5) 

    elif adcOut >= 0 and adcOut <= 500: 
      print "--------------------------------------------------------------" 
      print ("ADC Output:  {0:4d} Percentage: {1:3}% Voltage : {2} V".format(adcOut,percent,volts)) 
      print ("Rain Condition : Moderate Rain") 
      sleep(5) 

    elif adcOut >= 0 and adcOut <= 700: 
      print "--------------------------------------------------------------" 
      print ("ADC Output:  {0:4d} Percentage: {1:3}% Voltage : {2} V".format(adcOut,percent,volts)) 
      print ("Rain Condition : Light Rain") 
      sleep(5) 

    else : 
      print "--------------------------------------------------------------" 
      print ("ADC Output:  {0:4d} Percentage: {1:3}% Voltage : {2} V".format(adcOut,percent,volts)) 
      print ("Rain Condition : No Rain") 
      sleep(5) 
while True: 
    getAdc(0) 

И вот моя программа wxpython, которую я создаю для ее отображения. Помогите мне, как объединить две программы в одну, чтобы отобразить данные.

import datetime 

global current_time 
current_time = datetime.datetime.strftime(datetime.datetime.now(), '%d-%m-%y %H:%M:%S') 

try: 
    import wx 
except ImportError: 
    raise ImportError, "The wxPython module is required to run this program." 

class RainSensorApp_wx(wx.Frame): 
    def __init__(self, parent, id, title): 
     wx.Frame.__init__(self, parent, id, size = (500, 300)) 
     self.SetBackgroundColour(wx.BLUE) 
     self.parent = parent 
     self.initialize() 

    def initialize(self): 
     sizer = wx.GridBagSizer() 
     font = wx.Font(20, wx.DECORATIVE, wx.ITALIC, wx.NORMAL) 
     self.SetFont(font) 

     self.label = wx.StaticText(self, -1, label = u'Rain Sensor Level: {0:4d} Percentage:  {1:3}% Voltage: {2} V'.format(adcOut, percent, volts)) 
     self.label.SetBackgroundColour(wx.BLUE) 
     self.label.SetForegroundColour(wx.WHITE) 
     sizer.Add(self.label, (1,0), (1,2), wx.EXPAND) 

     self.label = wx.StaticText(self, -1, label = u'Rain Condition: {}'.format(rain_condition)) 
     self.label.SetBackgroundColour(wx.BLUE) 
     self.label.SetForegroundColour(wx.WHITE) 
     sizer.Add(self.label, (2,0), (1,3), wx.EXPAND) 

     self.label = wx.StaticText(self, -1, label = u'Time Updated: {}'.format(current_time)) 
     self.label.SetBackgroundColour(wx.BLUE) 
     self.label.SetForegroundColour(wx.WHITE) 
     sizer.Add(self.label, (3,0), (1,4), wx.EXPAND) 

     self.SetSizer(sizer) 
     self.Show(True) 

    def on_timer(self): 
     wx.CallLater(1000, self.on_timer) 

if __name__ == "__main__": 
    app = wx.App() 
    frame = RainSensorApp_wx(None, -1, 'Rain Sensor Monitor') 
    app.Mainloop() 
    getAdc(0) 

после этого я добавлю таймер с помощью CallLater динамически обновлять несколько WxPython статического текста, как я просто научиться его вчера. Я ценю, кто поможет мне и прочитает мой пост.

ответ

0

Это немного взломать, поскольку я должен подражать бит spidev, но этого должно быть достаточно, чтобы вы начали.
Код документально подтвержден, где я думаю, что это важно.

import datetime 
#import spidev 
from time import sleep 
import os 

#spi = spidev.SpiDev() 
#spi.open(0,0) 
#Setup some variables as I don't have spidev 
global adcOut 
adcOut = 200 
percent = int(round(adcOut/10.24)) 
volts = ((adcOut/1023) * 5) 
rain_condition="none" 

global current_time 
current_time = datetime.datetime.strftime(datetime.datetime.now(), '%d-%m-%y %H:%M:%S') 

try: 
    import wx 
except ImportError: 
    raise ImportError, "The wxPython module is required to run this program." 

class RainSensorApp_wx(wx.Frame): 
    def __init__(self, parent, id, title): 
     wx.Frame.__init__(self, parent, id, size = (500, 300)) 
     self.SetBackgroundColour(wx.BLUE) 
     self.parent = parent 
     self.initialize() 

    def initialize(self): 
     sizer = wx.GridBagSizer() 
     font = wx.Font(20, wx.DECORATIVE, wx.ITALIC, wx.NORMAL) 
     self.SetFont(font) 
     self.label1 = wx.StaticText(self, -1, label = u'Rain Sensor Level: {0:4d} Percentage:  {1:3}% Voltage: {2} V'.format(adcOut, percent, volts)) 

     #Give the labels unique names 

     self.label1.SetBackgroundColour(wx.BLUE) 
     self.label1.SetForegroundColour(wx.WHITE) 
     sizer.Add(self.label1, (1,0), (1,2), wx.EXPAND) 

     self.label2 = wx.StaticText(self, -1, label = u'Rain Condition: {}'.format(rain_condition)) 
     self.label2.SetBackgroundColour(wx.BLUE) 
     self.label2.SetForegroundColour(wx.WHITE) 
     sizer.Add(self.label2, (2,0), (1,3), wx.EXPAND) 

     self.label3 = wx.StaticText(self, -1, label = u'Time Updated: {}'.format(current_time)) 
     self.label3.SetBackgroundColour(wx.BLUE) 
     self.label3.SetForegroundColour(wx.WHITE) 
     sizer.Add(self.label3, (3,0), (1,4), wx.EXPAND) 

    #Create a timer and perform on_timer every 1000 milliseconds(change to 5000) 
     self.timer = wx.Timer(self) 
     self.Bind(wx.EVT_TIMER, self.on_timer, self.timer) 
     self.timer.Start(1000) 

     self.SetSizer(sizer) 
     self.Show(True) 

    def on_timer(self,event): 
     channel = 0 
     if ((channel>7)or(channel<0)): 
      return -1 
    #Hack out spidev references and use globals to emulate something happening 

#  r = spi.xfer2([1, (8+channel) << 4, 0]) 
#  adcOut = ((r[1]&3) << 8) + r[2] 

     global adcOut 
     adcOut = adcOut +1 
     percent = int(round(adcOut/10.24)) 
     volts = ((adcOut/1023) * 5) 
     if adcOut >= 0 and adcOut <= 300: 

     # Update the screen output 

       self.label1.SetLabel("ADC Output:  {0:4d} Percentage: {1:3}% Voltage : {2} V".format(adcOut,percent,volts)) 
       self.label2.SetLabel("Rain Condition : Heavy Rain") 

     elif adcOut >= 0 and adcOut <= 500: 
       self.label1.SetLabel("ADC Output:  {0:4d} Percentage: {1:3}% Voltage : {2} V".format(adcOut,percent,volts)) 
       self.label2.SetLabel("Rain Condition : Moderate Rain") 

     elif adcOut >= 0 and adcOut <= 700: 
       self.label1.SetLabel("ADC Output:  {0:4d} Percentage: {1:3}% Voltage : {2} V".format(adcOut,percent,volts)) 
       self.label2.SetLabel("Rain Condition : Light Rain") 

     else : 
       self.lable1.SetLabel("ADC Output:  {0:4d} Percentage: {1:3}% Voltage : {2} V".format(adcOut,percent,volts)) 
       self.lable2.SetLabel("Rain Condition : No Rain") 

if __name__ == "__main__": 
    Rs = wx.App() 
    RainSensorApp_wx(None, -1, 'Rain Sensor Monitor') 
    Rs.MainLoop() 
+0

благодарит за ваш ответ. Я отвечу вам в этот вторник и расскажу об этом после тестирования. если у кого-то есть другой ответ, я приветствую его, поскольку чем больше решений, тем я получаю более успешный ответ, который я получу. – anubismmt

+0

Я попробовал ваш код, и он работает, за исключением того, что он выдаёт (SyntaxWarning: имя 'adcOut' назначается перед глобальным объявлением) в оболочке python 2.7.10 перед запуском программы gui. Я также внес незначительные изменения в код вольт, чтобы отобразить его в двух десятичных знаках и добавить self.label3.SetLabel («Время обновлено: {}». Format (current_time) с глобальным current_time и инициализировать current_time, когда вы забыли обновить время – anubismmt

+0

Как указано в ответе «достаточно, чтобы вы начали». Это было немного взломать, чтобы обойти тот факт, что у меня нет доступа к «mcp3008 и датчику дождевой воды». Что касается обновления проблемы с форматированием и временем, ваш исходный код не включал их, и я не читатель разума. Кроме этого, вас больше всего приветствуют. –