Help with my code please, it's urgent

Hi, I'm currently trying to use an accelerometer (ADXL345) attached to a Arduino Nano Every to record the values of a piezo cantilever beam as it vibrates. I need help with my code, I found multiple ones online and I have been using this one but I don't think it works and I am stuck. The idea is the code will take values of the cantilever beam like a data acquisition card.

Low Cost Arduino DAQ Example · GitHub (I've used this code) Is this right?

Arduino & ADXL345 Accelerometer Interfacing with Processing (I was using this code to try understand what's happening but I have no clue.

Any help would be greatly appreciated :slight_smile: and thank you in advance!

Maybe try Adafruit's library. Link on product page
ADXL345 - Triple-Axis Accelerometer (+-2g/4g/8g/16g) w/ I2C/SPI [STEMMA QT / Qwiic] : ID 1231 : $17.50 : Adafruit Industries, Unique & fun DIY electronics and kits

Library Reference | ADXL345 Digital Accelerometer | Adafruit Learning System

Download the ADXL345 library and install it. You will also need the Adafruit Sensor Library if you do not already have it installed.

1 Like

One of the best tutorials in days! :laughing:

1 Like

Can you post your code, please.
Don't forget to use code tags.

Sorry, here is the code :slight_smile:

import serial import numpy as np import matplotlib.pyplot as plt import time

serial_port = 'COM19'
baud_rate = 250000
label_name = 'circle'
num_class_samples = 10 # Number of samples to collect
time_per_sample = 2.0 # Seconds
accel_sample_rate = 100 # Times per second (Hz) to read from acceleromater
num_accel_samples = int(time_per_sample * accel_sample_rate)

ser = serial.Serial(serial_port, baud_rate, timeout=1)
time.sleep(2)
ser.write('r'.encode('ascii'))
line = ser.readline()
ser.close()
print(line)
def capture_accel(ser, nsamples):
samples = np.zeros((nsamples, 3))
for i in range(nsamples):

    # Use timer to determine when to take measurement next
    start = time.time()

(from here is a code online)
# Transmit 'r' to have Arduino respond with X, Y, and Z acceleration
ser.write('r'.encode('ascii'))
line = ser.readline()
parsed = line.decode().rstrip().split('\t')
sample = np.array([float(axis) for axis in parsed])
samples[i] = sample

    # Wait before reading again
    while (time.time() - start) < (1. / accel_sample_rate):
        pass
    
return samples

// Capture sample set
accel_data = np.zeros((num_class_samples, num_accel_samples, 3))
ser = serial.Serial(serial_port, baud_rate, timeout=1)
print('Waiting for Arduino to reset...')
time.sleep(2)
i = 0
while i < num_class_samples:
input('Press enter and draw shape with board')
try:

  //Sample from Arduino
  samples = capture_accel(ser, num_accel_samples)
  accel_data[i] = np.array(samples)
  print('Sample', i, 'captured with shape:', accel_data[i].shape)
  i += 1
  
except:
  print('Error parsing samples. Try again.')
  pass

ser.close()

//Plotting data points
for sample_idx in range(5):
fig = plt.figure(figsize=(14,2))
ax = fig.add_subplot(111)
ax.plot(accel_data[sample_idx, :, 0], label='x')
ax.plot(accel_data[sample_idx, :, 1], label='y')
ax.plot(accel_data[sample_idx, :, 2], label='z')
plt.legend(loc='upper left')
plt.show()

// Save data
np.save(label_name, accel_data)

//Test: load array
test_data = np.load(label_name + '.npy') print(test_data)

Is this okay? I'm new to arduino and I was told majority of the code should be online and okay to use.

Posted the code but has to run through Akismet first.

I can't see your code.

It should be up now :slight_smile: if not I can screenshot it and post it

I'm sorry, I assumed there'd be some Arduino code

So it's no good?

I don't know if it's good or bad, I'm not qualified to offer an opinion because I don't really speak Java or Python

Have you tried Processing?

Sorry, here is the code

Is this a CircuitPython question? Post that on the Adafruit forum.

please edit your post, select the code part and press the </> icon in the tool bar to mark it as code. It's barely readable as it stands. (also make sure you indented the code in the IDE before copying, that's done by pressing ctrlT on a PC or cmdT on a Mac)

Sorry I went MIA yesterday. Would anyone know where to start with the code as I am lost? That code is a mix of python too (I think) some was from online.

Keep it simple and stupid firstly.
Run some tutorials for the hardware selected.
If you are happy with the results of the tutorials you can merge these to your project.
Have a nice day and enjoy coding in C++.

1 Like

Update:

Here is my code, when it's the exact same as someone that previously carried out this project the code doesn't work at all. Would anyone know why it's not working, the error is that the Wire was not declared in the scope. I have seen this exact code work for others but not me. Any help would be appreciated.

int ADXL345 = 0x53; // The ADXL345 sensor I2C address
String x,y,z; 
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
Wire.begin();
}

void loop () {
  // put your main code here, to run repeatedly:
  Wire.beginTransmisssion(ADXL345);
  Wire.wrtie(0x32);
  Wire.write(8); // (8dec -> 0000 1000 binary) Bit D3 High for measuring enable 
  Wire.endTransmission(false);
  Wire.requestFrom(ADXL345, 6, true);
  x = getWireRead();
  Y = getWireRead();
  z = getWireRead();

type or paste code here

  Serial.println("X: " + x + "g  Y: " + y + "g  Z: " + z + " g");
  delay(100);
}
`
float getWireRead(){
  float value = (Wire.read()|Wire.read() << 8 );
  return value/256

Because you don't have "#include <Wire.h>" ?

It's a bit weird to see a function returning a float, having its return value assigned to a String.

Please note also "doesn't work" and "doesn't compile" are not at all the same thing.

1 Like

You have a lot of errors in it

  1. You declared variable y, but try to use Y
  2. You can't concateate the things in Serial.print like this:
  1. Your getWireRead() function doesn't have a terminating ';' and '}'

etc...

Also you failed to insert the code to the message correctly...

1 Like
const int groundpin = 18;  
const int powerpin = 19;   
const int xpin = A3;       // x-axis 
const int ypin = A2;       // y-axis
const int zpin = A1;       // z-axis 

#include<Wire.h>
int ADXL345 = 0x53;  // The ADXL345 sensor I2C address
String x, y, z;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Wire.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  Wire.beginTransmission(ADXL345);
  Wire.write(0x32);
  //Wire.write(8);  // (8dec -> 0000 1000 binary) Bit D3 High for measuring enable
  Wire.endTransmission(false);
  Wire.requestFrom(ADXL345, 6, true);
 // print the sensor values:
  Serial.print(analogRead(xpin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(ypin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(zpin));
  Serial.println();
  //Serial.println("X: " + x + "g  Y: " + y + "g  Z: " + z + " g");
  delay(100);


}
float getWireRead() {
 float value = (Wire.read() | Wire.read() << 8);
  return value / 256;
}

Thanks everyone, I changed the code again, no errors this time.
Is this okay? Or is there anything I should change etc?

Also sorry if the code isn't posted properly, I'm on an extremely tight schedule and am panic typing very fast.

your function

getWireRead()

is not used in the code....