RE: Getting the Adafruit_I2C Import Changed Into Another GPIO Layout - python

I have some problems with the MotorBridgeCape. I have all my software and I found most of it at GitHub.com at github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB and at their Wiki at seeedstudio.com/wiki/Motor_Bridge_Cape_v1.0.
Here is my issue. I connect my battery, two motors, and I run the .py file for DC Motors from their Wiki page. I get an error. The error reads as follows:
•Error accessing 0x4B: Check your I2C address
I checked online at their site. The seeedstudio.com site, in the forum section, stated that in 2014 there was an addressed answer. This answer was to update the firmware. I go into my BBB/BBG with the MotorBridgeCape attached and I download the .zip file and then unzip it.
The update to the firmware is as follows:
1.Connect cape to your BBG/BBB, download http://www.seeedstudio.com/wiki/images/ ... e_v1.0.zip to your BBG/BBB
2.unzip the file
3.Go to the directory Motor Bridge Cape V1.0 (cd Motor Bridge Cape V1.0)
4.upload firmware (make flash_firmware)
Once I unzip the .zip file, I get a "directory." The directory is listed as Motor Bridge Cape v1.0. I have no underscores in the file/directory.
So, it is not listed as Motor_Bridge_Cape_v1.0 and I cannot move to that file/directory. So, I used "\" to move to that directory.
So, I get to the directory stated and I use "make flash_Firmware". That gets me errors, too.
Here is the code for the MotorBridgeCapeforBBG_BBB:
https://github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB/blob/master/BBG_MotorBridgeCape/MotorBridge.py
Please see:
from Adafruit_I2C import Adafruit_I2C
import Adafruit_BBIO.GPIO as GPIO
import time
Reset = "P9_23"
MotorBridge = Adafruit_I2C(0x4b)
GPIO.setup(Reset, GPIO.OUT)
ReadMode = 0
WriteMode = 1
DeAddr = 0X4B
ConfigValid = 0x3a6fb67c
DelayTime = 0.005
This software above uses the Adafruit_I2C. Is there a way to change Adafruit_I2C to another "import" of GPIOs that does not have a bug?
The I2C import from Adafruit has a bug in it. If I can change the I2C import to import other GPIOs, like GPIO_46 and so on, I should be able to use the MotorBridgeCapeforBBG_BBB in my current code to make things go.
Please see:
import MotorBridge
import time
MotorName = 1
ClockWise = 1
CounterClockWise = 2
PwmDuty = 90
Frequency = 1000
if __name__=="__main__":
motor = MotorBridge.MotorBridgeCape()
motor.DCMotorInit(MotorName,Frequency)
while True:
motor.DCMotorMove(MotorName,ClockWise,PwmDuty)
time.sleep(2)
motor.DCMotorMove(MotorName,CounterClockWise,PwmDuty)
time.sleep(2)
print "hello"
motor.DCMotorStop(MotorName)
time.sleep(2)
Seth
P.S. Any recommendations would be very helpful.

I changed the line
MotorBridge = Adafruit_I2C(0x4b)
to
MotorBridge = Adafruit_I2C(0x4b,2)
and it worked for me. Also make sure you have python-smbus installed. See this webpage for more information.

Okay...
I checked out the BBG and the Motor Bridge Cape long enough. I did as you stated in the above answer. Thank you. It was that additional 2 in the sequence of the software. I also needed python smbus to run the software correctly.
Seth

An update to this item is now available on github.com at https://github.com/silver2row/bbg/blob/master/MBC/MotorBridge.py.
Also, you can view the README at the beginning of the github repository for accessing smbus2, getting your smbus2 line 302 changed, and for some simple source to test your findings.
There are a lot of changes to set up on your MotorBridge.py file. Please view the differences and change them accordingly.
Seth

the Motor Bridge Cape "needs" the Adafruit_GPIO.I2C library since the Adafruit_BBIO.I2C library is not existent right now. Also...this is old news since the Adafruit_GPIO.I2C library has been deprecated.
It is read only now. You can find that info. here: https://github.com/adafruit/Adafruit_Python_GPIO/blob/master/Adafruit_GPIO/I2C.py.
This is what I use now for the Motor Bridge Cape I2C functionality: https://github.com/kplindegaard/smbus2.
So, instead of using the set up of the old way listed above, use this:
#!/usr/bin/python3
# * Copyright (c) 2015 seeed technology inc.
# * Author : Jiankai Li
# * Create Time: Nov 2015
# * Change Log : Seth Dec. 2019 w/ help from #beagle at Freenode
# * and Prabakar's book called, "BealgeBone by Example."
# * license: http://www.gnu.org/licenses/gpl-3.0.txt is the license for my contributions...
# * license from Mr. Li can be found here: https://github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB/blob/master/BBG_MotorBridgeCape/MotorBridge.py (MIT).
# FileName : MotorBridge.py
# by Jiankai.li
from smbus2 import SMBus
import time
import pathlib
# reset pin is P9.23, i.e. gpio1.17
reset_pin = pathlib.Path('/sys/class/gpio/gpio49/direction')
reset_pin.write_text('low')
bus = SMBus('/dev/i2c-2')
...
Motor Bridge Cape and the BeagleBoard.org family of boards!

Related

PyInstaller & Pymeasure : NotImplementedError

I am currently experiencing difficulties using PyInstaller on a code relying on Pymeasure library. The program is working fine from the prompt, but not when started from the executable generated by PyInstaller.
Here is an simple example of a code working from prompt but not when frozen:
import visa
from pymeasure.instruments.keithley import Keithley2000, Keithley2400
rm = visa.ResourceManager()
list_available = rm.list_resources()
print(list_available)
keithley = Keithley2400("GPIB1::23")
keithley.apply_current() # Sets up to source current
keithley.source_current_range = 10e-3 # Sets the source current range to 10 mA
keithley.compliance_voltage = 10 # Sets the compliance voltage to 10 V
keithley.source_current = 0 # Sets the source current to 0 mA
keithley.enable_source() # Enables the source output
keithley.measure_voltage() # Sets up to measure voltage
keithley.ramp_to_current(5e-3) # Ramps the current to 5 mA
print(keithley.voltage) # Prints the voltage in Volts
keithley.shutdown() # Ramps the current to 0 mA and disables output
Here is the output when I run the executable:
Please note that I have PyVISA 1.9.1 installed.
Why do I get this error and how do I fix that ?
You need to make sure you include the package metadata for PyVisa in your PyInstaller project. PyInstaller has a utility hook for that job; create a hook-pyvista.py hook file (if you don’t already have one) with:
from PyInstaller.utils.hooks import copy_metadata
datas = copy_metadata("pyvisa")
and tell PyInstaller about it with the --additional-hooks-dir command-line switch. See the documentation on how hooks work for more details.
pymeasurement relies on the pyvisa.__version__ attribute to determine if you have installed the correct version of that project. But pyvisa.__version__ defaults to "unknown" unless it can locate its metadata files, which would provide pkg_resources with the required metadata to retrieve the version for it.
You can verify that PyVisa was installed correctly by importing it yourself and testing the __version__ attribute:
import pyvisa
print("PyVisa version", pyvisa.__version__)
Are you sure you are connected to the instrument, your code references "GPIB1::23" but your print(list_available) returns "GPIB1::24"?

How to use IR Remote with Raspberry Pi using Python?

I bought this [IR Sensor and Remote][1] to use with my Raspberry Pi 3.
I have LIRC setup and I am able to detect an input from the IR Remote using the commands below:
sudo /etc/init.d/lirc stop
mode2 -d /dev/lirc0
When I run the above commands, I am able to detect input from the IR Remote. When I press any button on the IR REmote, I get an output like:
My question is - in the output above, I pressed '2" on the remote. How shall I go about deciphering (in python) which button is really pressed?
Update 1:
I tried using the python-lirc package but I get error on this line:
The previous answers shortcuts the lirc decoding. Since you have a working mode2 the kernel driver works and sends correct data to lircd. However, mode2 does not tell you if the decoding works.
To check the decoding you use irw(1). Until you have working output from this program, you don't know if lirc can decode your remote.
The lircrc file described above is used to transform the generic button presses (as shown by irw) to application-specific commands. To debug this file you use ircat(1).
When you have working output from irw(1) and ircat(1) your lirc setup is complete. A working lirc setup is really required before using any python package. BTW, as of upcoming 0.10.0 lirc will have native python bindings.
A comprehensive guide to setup lirc can be found at http://lirc.org/html/configuration-guide.html
You probably do not want to use the mode2 output for this. There is a Python library available (Here) which would likely be a much better way to go for this project.
Code:
import lirc
sockid = lirc.init("myprogram")
print(lirc.nextcode())
lirc.deinit()
lircrc configuration file
begin
button = 1 # what button is pressed on the remote
prog = myprogram # program to handle this command
config = one, horse # configs are given to program as list
end
begin
button = 2
prog = myprogram
config = two
end
Results after pressing button 1
['one', 'horse']
These days there is no need to use lirc as IR events are handled through the kernel.
In my case I setup an IR receiver on a GPIO pin in /boot/config.txt
dtoverlay=gpio-ir,gpio_pin=16
Then installed evdev
pip install evdev
Reboot, and the following worked (your input device path my vary)
from evdev import InputDevice, categorize, ecodes
dev = InputDevice('/dev/input/event0')
for event in dev.read_loop():
print(event)
When pressing some buttons on the remote I get:
$> sudo python3 irtest.py
device /dev/input/event0, name "gpio_ir_recv", phys "gpio_ir_recv/input0"
event at 1639133806.295636, code 04, type 04, val 64
event at 1639133806.295636, code 00, type 00, val 00
event at 1639133806.405607, code 04, type 04, val 64
event at 1639133806.405607, code 00, type 00, val 00
event at 1639133808.745610, code 04, type 04, val 16
...

Python - How to get the start/base address of a process?

How do I get the start/base address of a process? Per example Solitaire.exe (solitaire.exe+BAFA8)
#-*- coding: utf-8 -*-
import ctypes, win32ui, win32process
PROCESS_ALL_ACCESS = 0x1F0FFF
HWND = win32ui.FindWindow(None,u"Solitär").GetSafeHwnd()
PID = win32process.GetWindowThreadProcessId(HWND)[1]
PROCESS = ctypes.windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS,False,PID)
print PID, HWND,PROCESS
I would like to calculate a memory address and for this way I need the base address of solitaire.exe.
Here's a picture of what I mean:
I think the handle returned by GetModuleHandle is actually the base address of the given module. You get the handle of the exe by passing NULL.
Install pydbg
Source: https://github.com/OpenRCE/pydbg
Unofficial binaries here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg
from pydbg import *
from pydbg.defines import *
import struct
dbg = pydbg()
path_exe = "C:\\windows\\system32\\calc.exe"
dbg.load(path_exe, "-u amir")
dbg.debug_event_loop()
parameter_addr = dbg.context.Esp #(+ 0x8)
print 'ESP (address) ',parameter_addr
#attach not working under Win7 for me
#pid = raw_input("Enter PID:")
#print 'PID entered %i'%int(pid)
#dbg.attach(int(pid)) #attaching to running process not working
You might want to have a look at PaiMei, although it's not very active right now https://github.com/OpenRCE/paimei
I couldn't get attach() to work and used load instead. Pydbg has loads of functionality, such as read_proccess_memory, write_process_memory etc.
Note that you can't randomly change memory, because an operating system protects memory of other processes from your process (protected mode). Before the x86 processors there were some which allowed all processors to run in real mode, i.e. the full access of memory for every programm. Non-malicious software usually (always?) doesn't read/write other processes' memory.
The HMDOULE value of GetModuleHandle is the base address of the loaded module and is probably the address you need to compute the offset.
If not, that address is the start of the header of the module (DLL/EXE), which can be displayed with the dumpbin utility that comes with Visual Studio or you can interpret it yourself using the Microsoft PE and COFF Specification to determine the AddressOfEntryPoint and BaseOfCode as offsets from the base address. If the base address of the module isn't what you need, one of these two is another option.
Example:
>>> BaseAddress = win32api.GetModuleHandle(None) + 0xBAFA8
>>> print '{:08X}'.format(BaseAddress)
1D0BAFA8
If The AddressOfEntryPoint or BaseOfCode is needed, you'll have to use ctypes to call ReadProcessMemory following the PE specification to locate the offsets, or just use dumpbin /headers solitaire.exe to learn the offsets.
You can use frida to easy do that.
It is very useful to make hack and do some memory operation just like make address offset, read memory, write something to special memory etc...
https://github.com/frida/frida
2021.08.01 update:
Thanks for #Simas Joneliunas reminding
There some step using frida(windows):
Install frida by pip
pip install frida-tools # CLI tools
pip install frida # Python bindings
Using frida api
session = frida.attach(processName)
script = session.create_script("""yourScript""")
script.load()
sys.stdin.read() #make program always alive
session.detach()
Edit your scrip(using JavaScrip)
var baseAddr = Module.findBaseAddress('solitaire.exe');
var firstPointer = baseAddr.add(0xBAFA8).readPointer();
var secondPointer = firstPointer.add(0x50).readPointer();
var thirdPointer = secondPointer.add(0x14).readPointer();
#if your target pointer points to a Ansi String, you can use #thirdPointer.readAnsiString() to read
The official site https://frida.re/

Programmatically detect system-proxy settings on Windows XP with Python

I develop a critical application used by a multi-national company. Users in offices all around the globe need to be able to install this application.
The application is actually a plugin to Excel and we have an automatic installer based on Setuptools' easy_install that ensures that all a project's dependancies are automatically installed or updated any time a user switches on their Excel. It all works very elegantly as users are seldom aware of all the installation which occurs entirely in the background.
Unfortunately we are expanding and opening new offices which all have different proxy settings. These settings seem to change from day to day so we cannot keep up with the outsourced security guys who change stuff without telling us. It sucks but we just have to work around it.
I want to programatically detect the system-wide proxy settings on the Windows workstations our users run:
Everybody in the organisazation runs Windows XP and Internet Explorer. I've verified that everybody can download our stuff from IE without problems regardless of where they are int the world.
So all I need to do is detect what proxy settings IE is using and make Setuptools use those settings. Theoretically all of this information should be in the Registry.. but is there a better way to find it that is guaranteed not to change with people upgrade IE? For example is there a Windows API call I can use to discover the proxy settings?
In summary:
We use Python 2.4.4 on Windows XP
We need to detect the Internet Explorer proxy settings (e.g. host, port and Proxy type)
I'm going to use this information to dynamically re-configure easy_install so that it can download the egg files via the proxy.
UPDATE0:
I forgot one important detail: Each site has an auto-config "pac" file.
There's a key in Windows\CurrentVersion\InternetSettings\AutoConfigURL which points to a HTTP document on a local server which contains what looks like a javascript file.
The pac script is basically a series of nested if-statements which compare URLs against a regexp and then eventually return the hostname of the chosen proxy-server. The script is a single javascript function called FindProxyForURL(url, host)
The challenge is therefore to find out for any given server which proxy to use. The only 100% guaranteed way to do this is to look up the pac file and call the Javascript function from Python.
Any suggestions? Is there a more elegant way to do this?
Here's a sample that should create a bullet green (proxy enable) or red (proxy disable) in your systray
It shows how to read and write in windows registry
it uses gtk
#!/usr/bin/env python
import gobject
import gtk
from _winreg import *
class ProxyNotifier:
def __init__(self):
self.trayIcon = gtk.StatusIcon()
self.updateIcon()
#set callback on right click to on_right_click
self.trayIcon.connect('popup-menu', self.on_right_click)
gobject.timeout_add(1000, self.checkStatus)
def isProxyEnabled(self):
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings")
subCount, valueCount, lastModified = QueryInfoKey(aKey)
for i in range(valueCount):
try:
n,v,t = EnumValue(aKey,i)
if n == 'ProxyEnable':
return v and True or False
except EnvironmentError:
break
CloseKey(aKey)
def invertProxyEnableState(self):
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", 0, KEY_WRITE)
if self.isProxyEnabled() :
val = 0
else:
val = 1
try:
SetValueEx(aKey,"ProxyEnable",0, REG_DWORD, val)
except EnvironmentError:
print "Encountered problems writing into the Registry..."
CloseKey(aKey)
def updateIcon(self):
if self.isProxyEnabled():
icon=gtk.STOCK_YES
else:
icon=gtk.STOCK_NO
self.trayIcon.set_from_stock(icon)
def checkStatus(self):
self.updateIcon()
return True
def on_right_click(self, data, event_button, event_time):
self.invertProxyEnableState()
self.updateIcon()
if __name__ == '__main__':
proxyNotifier = ProxyNotifier()
gtk.main()
As far as I know, In a Windows environment, if no proxy environment variables are set, proxy settings are obtained from the registry's Internet Settings section. .
Isn't it enough?
Or u can get something useful info from registry:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer
Edit:
sorry for don't know how to format comment's source code, I repost it here.
>>> import win32com.client
>>> js = win32com.client.Dispatch('MSScriptControl.ScriptControl')
>>> js.Language = 'JavaScript'
>>> js.AddCode('function add(a, b) {return a+b;}')
>>> js.Run('add', 1, 2)
3

Is there any Ruby or Python interpreter for Lego Mindstorm?

I want to start coding in Python or Ruby. Since I own a Lego Midstorms kit I thought it would be nice to program against it. Are there any good translators / interpeters for the Mindstorms brick?
The nxt-python and ruby-nxt projects are remote control interfaces to the NXT. They both run on a PC and remotely control the NXT via Bluetooth or USB.
If you are looking for running alternative firmware on the NXT, there are several different alternatives.
Steve Hassenplug has a webpage with a comprehensive list of all of the known alternative firmware and remote control options.
NXT Software
With python you can use jaraco.nxt or nxt-python to control the NXT robot. I don't own one so I've never used any of those.
Found this example using nxt-python:
#!/usr/bin/env python
import nxt.locator
from nxt.motor import Motor, PORT_B, PORT_C
def spin_around(b):
m_left = Motor(b, PORT_B)
m_left.update(100, 360)
m_right = Motor(b, PORT_C)
m_right.update(-100, 360)
sock = nxt.locator.find_one_brick()
if sock:
spin_around(sock.connect())
sock.close()
else:
print 'No NXT bricks found'
Seems nice.
Here's an open source project for Ruby
Try pynxc
http://code.google.com/p/pynxc/

Categories