Arduino pyfirmata analog reading problems - python

I am having some problems reading analog values from my Arduino Mega using pyfirmata.
I use Arduino Mega with a Mega Sensor Shield.
I would like to read analog values from a HW-201 IR sensor (pin A5).
I have uploaded the Standard firmata sketch on Arduino IDE, and I am running the following code using Anaconda Spyder:
import serial
import serial.tools.list_ports
from pyfirmata import ArduinoMega, util
from time import sleep
def readArduinoPort():
COM = []
ports = list(serial.tools.list_ports.comports())
for p in ports:
if "Arduino" in p.description:
COM.append(str(p.device))
return COM
COM = readArduinoPort()
board = ArduinoMega(COM[0])
pin = board.get_pin('a:5:i')
it = util.Iterator(board)
it.start()
try:
while True:
print(pin.read())
sleep(0.1)
except KeyboardInterrupt:
pass
Now, this code runs just fine the first time I use it, generating numbers close to 1 when the sensor is detecting proximity and numbers close to 0 when not detecting anything.
However, whenever I try to run the Iterator a second time (without restarting the kernel), the code generates seemingly random numbers (almost like the pin was floating, like nothing was connected to it).
Any idea why this is happening? Is this a normal behavior?
Thank you!
I already checked these questions that do not entirely address my issue:
arduino pyfirmata analog reading
Analog readings on Arduino returns wrong values
I have the same result by not having anything pinned to pin A5 of the Arduino Mega.
I wasn't sure, but I tried adding:
board.analog[5].enable_reporting()
before the iterator and then:
board.analog[5].disable_reporting()
but nothing changed.

Board Differences
I ran into the same problem. I own both a Mega and an Uno and needed to select the appropriate Board and Processor in the tools menu:
Tools > Board > _board_
Tools > Processor > _processor_

Related

Issue with daisychaining MCP3008 SPI on Raspberry Pi with Python

At the moment I am trying to let two MCP3008's communicate through SPI with my raspberry pi and a Python script. A potentiometer should send a certain analog value to the MCP3008 input channel.
Here is my setup in Fritzing:
Breadboard Schematic
and here is the schematic overview:
Schematic Overview
The SPI wiring is based upon a standard daisychain schematic as shown in:
SPI Daisy Chain
The Python Code I am using is:
import spidev
import time
spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz = 1000000
def read_spi(channel):
spidata = spi.xfer2([0,(8+channel)<<4,0])
return ((spidata[1] & 3) << 8) + spidata[2]
try:
while True:
channeldata = read_spi(0)
print (channeldata)
time.sleep(.1)
except KeyboardInterrupt:
spi.close()
I am getting values, but they fluctuate a lot with every value possible between 0 and 1023.
I've tried it with one MCP3008 without daisychaining of course and it worked fine, so my guess is that it has something to do with either the daisychain being incorrect, or the addressing of the MCP3008.
Can you guys help me out? Thanks alot!!
Cheers,
Devatu
Might be a late response, but according to the data sheet this chip can't be daisy-chained at all.
I am also looking for an ADC which can be daisy-chained.

Does Fusion 360 not have access to USB ports by default?

I'm working on making my own 3D mouse, sort of like 3D Connexion's own model. I'm using Autodesk's Fusion 360 as my application, and Fusion's API(Application Program Interface) to interact with the mouse. I have a gyroscope + accelerometer that spits raw measurements into an Arduino, which then sends those values(through the serial port using the Serial library). I'm then using the PySerial library(because Fusion's API uses python for it's language) to read that data coming from the Arduino, and spit it into Fusion, where I can control the camera position. The issue that I'm running into is that, for testing, I can print the values of the gyro + accelerometer to the Command Prompt just fine with a Python script. But when I try the exact same script in Fusion's code editor(Spyder), it doesn't work. I know that the Serial library is being imported, but the script doesn't work. Is it possible that Fusion 360 doesn't have access to the USB ports? If so, how could I fix it?
Here is a little snipet of my code:
#This is a python script that when run in the CMD, it works just fine.
import serial
ser = serial.Serial()
ser.baudrate = 9600
ser.port = 'COM3'
ser.open()
while True:
result = ser.readline()
result = str(result)
print (result)
All that this code does, is it reads the value of a potentiometer hooked up to an Arduino. It then prints those values into the CMD.
Here is the code that comes from the Fusion 360 API:
#This is the Fusion 360 code that doesn't work.
import adsk.core, adsk.fusion, adsk.cam, traceback
import serial
def get(app):
try:
ui = app.UserInterface
ser = serial.win32.Serial()
ser.baudrate = 9600
ser.port = 'COM3'
ser.open()
value = ser.read()
value = str(value)
adsk.doEvents()
ui.messageBox(value)
except:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def Main():
try:
app = adsk.core.Application.Get()
ui = app.UserInterface
ui.messageBox("Everything is working till this point")
adsk.doEvents()
get(app)
except:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
Main()
exit()
Thanks in advance!
In answer to your question, it may be so that Fusion360 does not have access to serial ports directly.
Fusion360 has a JavaScript API available and had to add custom calls to allow access to local machine resources like files.
(JavaScript does not have that natively).
That may be the nature of the problem you are up against, even though your program is written in Python. (I think F360 uses its JavaScript API to display its own User Interface).
Also, I see a difference between the code snippets:
ser = serial.win32.Serial()
...
ser = serial.Serial()
Perhaps you can call the first program from F360, and simply write to a file or something like that, to test it.

Raspberry Pi MAX31856 Thermocouple Temperature Reading Error

I'm working with t-type thermocouple and needs to read the temperature data using python on Raspberry Pi 3. I used Adafruit MAX31856 to connect the thermocouple to the Pi and and tried to read it using this module.
I want to read the temperature for an extended period of time so I tried to print it out in a while loop However, anytime I run my code, I only get few 'correct' readings then the temperature resets to 0 until I re-run the code again - see the attached image.
I don't know what is causing this, and I don't think this is a connection problem since it prints the correct temperature when I re-run the code without touching the set-up.
Does anyone know why the reading is resetting to 0?
Here is my code:
from Adafruit_MAX31856 import MAX31856
import time
# Raspberry Pi software SPI configuration.
CLK = 4
CS = 22
DO = 17
DI = 27
sensor = MAX31856(clk=CLK, cs=CS, do=DO, di=DI)
while True:
temp = sensor.readTempC()
print('Thermocouple Temperature: {0:0.3F}*C'.format(temp))
time.sleep(1.0)
Try resetting sensor by putting sensor = MAX31856(clk=CLK, cs=CS, do=DO, di=DI) in the while loop.

pySerial very strange behaviour ... Code works when executed in shell but not in a script

I'm struggling with pySerial. To be brief ... The code below works great when executed in the Python Shell ...
>>> import serial
>>> s=serial.Serial("COM5", 9600)
>>> while(1):
s.write("#")
s.readline()
Produces the output below in the shell:
1L
'56.73\r\n'
1L
'56.73\r\n'
When the same code is written in a script say "readSerial.py" the script will either not transmit the hashtag that triggers the serial device to transmit the data, or will not receive the replied data.
I'm using pySerial 3, but have noticed the same behavior with 2.7. Using Python 2.7.10 64 bit on Win10. But also noticed this behavior on Raspberry Pi with /dev/ttyACM0. I would really like to have this solved. I'm not that experienced in Python so this might be an oversight.
Hardware is checked and double checked.
Thanks,
KK
Thanks, but I really know how to print data from Python. The problem is really with pySerial. Here is the complete code, please don't discus errors in commented out code. These are of no concern here.
#from numpy import array
#import matplotlib.animation as animation
import time
import serial as s
#data = array([])
Arduino = s.Serial("COM5", 9600)
i = 0
while (1):
try:
Arduino.write("#")
time.sleep(.1)
inString = Arduino.readline()
data = float(inString)
print i, ":", data
i += 1
time.sleep(1)
except KeyboardInterrupt:
break
Arduino.close()
But like said this doesn't work. As far as I can tell the readline() function does not return. And ... there 's really no point in making it return by setting the tx timeout. To add to the mistery; When the code is debugged (i.e. stepped trough) it does work.
Thanks in advance,
KK
From the FAQ :
Example works in serial.tools.miniterm but not in script.
The RTS and DTR lines are switched when the port is opened. This may
cause some processing or reset on the connected device. In such a
cases an immediately following call to write() may not be received by
the device.
A delay after opening the port, before the first write(), is
recommended in this situation. E.g. a time.sleep(1)

Raspberry Pi python serial FT232 not receive 8bytes

I FT232 module connected to the Raspberry Pi (with USB cable). I want to receive 8bytes (1 byte). On Windows, Terminal draws me correctly beats (eg. 00001011). In the following python script:
#!/usr/bin/python
import serial
import binascii
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
while True:
str1 = ser.read(1)
if str1 == '':
print ''
else:
print bin(int(binascii.hexlify(str1),16))
returns only 2 bits at the end:
0b11111100 ,
0b11111101 ,
0b11111110 ,
0b11111111
What am I doing wrong that draws me just 2bits at the end?
Below please find screen how to receive data on Windows:
http://mateok.ovh/windows.jpg
And on Raspberry Pi:
http://mateok.ovh/linux.jpg
I would like to get on the Raspberry Pi received data were the same.
Edit:
I was able to find a solution! It turned out that the reason is ... that the device had been connected before starting the Raspberry Pi! If they Disconnect and reconnect only when the Raspberry Pi starts - values are returned well! Maybe someone knows the cause of this? And how can I fix it? I do not want every time you re-connect the converter ..

Categories

Resources