Python Tkinter滑块小部件通过I2C写入值

2024-05-20 19:22:56 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我一直在寻找一个例子,现在似乎找不到任何例子,中继tkinter滑块值超过I2C到Arduino。到目前为止,我还没有试着和阿杜伊诺人沟通。接下来我将跨过这座桥;现在我只想知道如何编写幻灯片小部件值并通过I2C发送

这是python2中一个简单的GUI滑块小部件,我相信它是I2C通信的正确设置。我更新了Rpi来设置I2C。我想在Arduino中做的只是读取伺服控制的0到180值。重要的是它只写值或以某种方式可以用于输入。我有其他代码在arduino驱动相同的伺服,如果其他条件满足,这将被忽略。在

from Tkinter import*
import RPi.GPIO as GPIO
import time

import smbus

bus = smbus.SMBus=(1)

SLAVE_ADDRESS = 0x04



class App:



    def __init__(self, master):

        def SendScaleReading(self):
            S = scale.get()# Now how do we write this and get the Scale Value and send it??    
            bus(SLAVE_ADDRESS, ord('S'))#According to an example this should be 
                                        #"bus.write_byte(SLAVE_ADDRESS, ord('S'))"

        frame = Frame(master)
        frame.pack()

        scale = Scale(frame, from_=0, to=180, orient=HORIZONTAL, command=SendScaleReading)
        scale.grid(row=1, column=1)



root = Tk()
root.wm_title('I2C servo control')
app = App(root)
root.geometry("200x50+0+0")
root.mainloop()  

Tags: fromimportgpio部件addressrooti2cframe
2条回答

好吧,一个朋友帮了我一把,我离得不远了。一旦我走到这一步,我只是一个IO错误的小问题。我遇到了[Errno 5]个IO错误。确保Arduino和Pi之间有接地。当我搜索的时候,这似乎被许多解决方案忽略了。你需要SDA,SLA和Gnd都连接起来。在

不管怎么说,这是运行arduino i2c闪烁草图的代码。根据I2C上Rpi输入的滑块,这将使引脚13上的led闪烁更快或更慢。我将尝试编写此代码来控制下一个伺服,如果成功,我也将发布该代码。在

Rpi/python2代码如下:

from Tkinter import*
import RPi.GPIO as GPIO
import time

import smbus

bus = smbus.SMBus(1)

SLAVE_ADDRESS = 0x28



class App:



    def __init__(self, master):

        def SendScaleReading(self):
            S = scale.get()
            print("we have" );
            print( S )
            bus.write_byte_data(SLAVE_ADDRESS, S, S )

        frame = Frame(master)
        frame.pack()

        scale = Scale(frame, from_=0, to=180, orient=HORIZONTAL, command=SendScaleReading)
        scale.grid(row=1, column=1)



root = Tk()
root.wm_title('I2C servo control')
app = App(root)
root.geometry("200x50+0+0")
root.mainloop()  

Arduino i2c导线闪烁示意图如下:

^{pr2}$

好吧,伺服代码最终变得相当简单。任何人都可以自由使用,这样就可以保证我的改进了。在

Arduino I2C驱动伺服示意图如下:

#include <Wire.h>
#include <Servo.h>
// unique address for this I2C slave device
#define ADDRESS 0x28

Servo myservo;


int pos = 0;
void setup() {

myservo.attach(9);

  Wire.begin(ADDRESS);                // join i2c bus with address #4

  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent); // register the request handler


}

//gets called when I2C read occurs
void requestEvent() {
//any request for data will return 0x14 (random number i picked for testing)
  Wire.write( 0x14  );
}

// get called when I2C write occurs
void receiveEvent(int Pos) {

    int val = Wire.read();
    pos = val;

  while (Wire.available() > 0 ) {
    Wire.read();
  }
}


void loop()
{

myservo.write(pos);
delay(15);

}

相关问题 更多 >