text:
Using ArduinoISP on an Arduino Uno to program an ATmega328
I have an Arduino Uno R3 and would like to use it to program a blank ATmega328 on a breadboard. I've followed the instructions for the 8 MHz version on http://arduino.cc/en/Tutorial/ArduinoToBreadboard with an added 10K pullup resistor on the RESET pin of the ATmega328 on the breadboard; and I've uploaded the ArduinoISP sketch from the Arduino 1.0.5 distribution to my Uno.
I've also added the metadata for my setup: the following is the contents of  ~/sketchbook/hardware/breadboard/boards.txt:
atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=stk500v1
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05
atmega328bb.bootloader.path=arduino:atmega
atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

I've also added the following section to my ~/.avrduderc file:
part
    id          = "m328";
    desc        = "ATMEGA328";
    has_debugwire   = yes;
    flash_instr     = 0xB6, 0x01, 0x11;
    eeprom_instr    = 0xBD, 0xF2, 0xBD, 0xE1, 0xBB, 0xCF, 0xB4, 0x00,
              0xBE, 0x01, 0xB6, 0x01, 0xBC, 0x00, 0xBB, 0xBF,
              0x99, 0xF9, 0xBB, 0xAF;
    stk500_devcode  = 0x86;
    # avr910_devcode    = 0x;
    signature       = 0x1e 0x95 0x14;
    pagel       = 0xd7;
    bs2         = 0xc2;
    chip_erase_delay    = 9000;
    pgm_enable = "1 0 1 0 1 1 0 0 0 1 0 1 0 0 1 1",
         "x x x x x x x x x x x x x x x x";

    chip_erase = "1 0 1 0 1 1 0 0 1 0 0 x x x x x",
         "x x x x x x x x x x x x x x x x";

    timeout = 200;
    stabdelay   = 100;
    cmdexedelay = 25;
    synchloops  = 32;
    bytedelay   = 0;
    pollindex   = 3;
    pollvalue   = 0x53;
    predelay    = 1;
    postdelay   = 1;
    pollmethod  = 1;

    pp_controlstack =
    0x0E, 0x1E, 0x0F, 0x1F, 0x2E, 0x3E, 0x2F, 0x3F,
    0x4E, 0x5E, 0x4F, 0x5F, 0x6E, 0x7E, 0x6F, 0x7F,
    0x66, 0x76, 0x67, 0x77, 0x6A, 0x7A, 0x6B, 0x7B,
    0xBE, 0xFD, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00;
    hventerstabdelay    = 100;
    progmodedelay   = 0;
    latchcycles     = 5;
    togglevtg       = 1;
    poweroffdelay   = 15;
    resetdelayms    = 1;
    resetdelayus    = 0;
    hvleavestabdelay    = 15;
    resetdelay      = 15;
    chiperasepulsewidth = 0;
    chiperasepolltimeout = 10;
    programfusepulsewidth = 0;
    programfusepolltimeout = 5;
    programlockpulsewidth = 0;
    programlockpolltimeout = 5;

    memory "eeprom"
    paged       = no;
    page_size   = 4;
    size        = 1024;
    min_write_delay = 3600;
    max_write_delay = 3600;
    readback_p1 = 0xff;
    readback_p2 = 0xff;
    read = " 1 0 1 0 0 0 0 0",
           " 0 0 0 x x x a9 a8",
           " a7 a6 a5 a4 a3 a2 a1 a0",
           " o o o o o o o o";

    write = " 1 1 0 0 0 0 0 0",
            " 0 0 0 x x x a9 a8",
        " a7 a6 a5 a4 a3 a2 a1 a0",
        " i i i i i i i i";

    loadpage_lo = " 1 1 0 0 0 0 0 1",
              " 0 0 0 0 0 0 0 0",
              " 0 0 0 0 0 0 a1 a0",
              " i i i i i i i i";

    writepage = " 1 1 0 0 0 0 1 0",
            " 0 0 x x x x a9 a8",
            " a7 a6 a5 a4 a3 a2 0 0",
            " x x x x x x x x";

    mode        = 0x41;
    delay       = 20;
    blocksize   = 4;
    readsize    = 256;
    ;

    memory "flash"
    paged       = yes;
    size        = 32768;
    page_size   = 128;
    num_pages   = 256;
    min_write_delay = 4500;
    max_write_delay = 4500;
    readback_p1 = 0xff;
    readback_p2 = 0xff;
    read_lo = " 0 0 1 0 0 0 0 0",
          " 0 0 a13 a12 a11 a10 a9 a8",
          " a7 a6 a5 a4 a3 a2 a1 a0",
          " o o o o o o o o";

    read_hi = " 0 0 1 0 1 0 0 0",
          " 0 0 a13 a12 a11 a10 a9 a8",
          " a7 a6 a5 a4 a3 a2 a1 a0",
          " o o o o o o o o";

    loadpage_lo = " 0 1 0 0 0 0 0 0",
              " 0 0 0 x x x x x",
              " x x a5 a4 a3 a2 a1 a0",
              " i i i i i i i i";

    loadpage_hi = " 0 1 0 0 1 0 0 0",
              " 0 0 0 x x x x x",
              " x x a5 a4 a3 a2 a1 a0",
              " i i i i i i i i";

    writepage = " 0 1 0 0 1 1 0 0",
            " 0 0 a13 a12 a11 a10 a9 a8",
            " a7 a6 x x x x x x",
            " x x x x x x x x";

    mode        = 0x41;
    delay       = 6;
    blocksize   = 128;
    readsize    = 256;

    ;

    memory "lfuse"
    size = 1;
    min_write_delay = 4500;
    max_write_delay = 4500;
    read = "0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0",
           "x x x x x x x x o o o o o o o o";

    write = "1 0 1 0 1 1 0 0 1 0 1 0 0 0 0 0",
            "x x x x x x x x i i i i i i i i";
    ;

    memory "hfuse"
    size = 1;
    min_write_delay = 4500;
    max_write_delay = 4500;
    read = "0 1 0 1 1 0 0 0 0 0 0 0 1 0 0 0",
           "x x x x x x x x o o o o o o o o";

    write = "1 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0",
            "x x x x x x x x i i i i i i i i";
    ;

    memory "efuse"
    size = 1;
    min_write_delay = 4500;
    max_write_delay = 4500;
    read = "0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0",
           "x x x x x x x x x x x x x o o o";

    write = "1 0 1 0 1 1 0 0 1 0 1 0 0 1 0 0",
            "x x x x x x x x x x x x x i i i";
    ;

    memory "lock"
    size = 1;
    min_write_delay = 4500;
    max_write_delay = 4500;
    read = "0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0",
           "x x x x x x x x x x o o o o o o";

    write = "1 0 1 0 1 1 0 0 1 1 1 x x x x x",
            "x x x x x x x x 1 1 i i i i i i";
    ;

    memory "calibration"
    size = 1;
    read = "0 0 1 1 1 0 0 0 0 0 0 x x x x x",
           "0 0 0 0 0 0 0 0 o o o o o o o o";
    ;

    memory "signature"
    size = 3;
    read = "0 0 1 1 0 0 0 0 0 0 0 x x x x x",
           "x x x x x x a1 a0 o o o o o o o o";
    ;
;

So I thought I'd be good to go: I've set the programmer type to ArduinoISP and the board type to ATmega328 on a breadboard (8 MHz internal clock) in the IDE.
However, when I try to either upload the Arduino bootloader, or use the Upload using programmer feature on the Blink example, I get this:
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

Full output:
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328 -cstk500v1 -P/dev/ttyACM0 -b19200 -Uflash:w:/tmp/build6008715511691559175.tmp/Blink.cpp.hex:i

avrdude: Version 5.11.1, compiled on Apr 28 2013 at 18:46:46
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/cactus/.avrduderc"

         Using Port                    : /dev/ttyACM0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
         AVR Part                      : ATMEGA328
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
avrdude: Send: A [41] . [80]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [02]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [81]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [01]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [82]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [12]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [98]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
avrdude: Send: A [41] . [84]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [85]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [86]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [87]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [89]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: Send: A [41] . [81]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [01]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [82]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [12]
avrdude: Recv: . [10]
avrdude: Send: B [42] . [86] . [00] . [00] . [01] . [01] . [01] . [01] . [03] . [ff] . [ff] . [ff] . [ff] . [00] . [80] . [04] . [00] . [00] . [00] . [80] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: Send: E [45] . [05] . [04] . [d7] . [c2] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: Send: P [50]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: AVR device initialized and ready to accept instructions

Reading | avrdude: Send: V [56] 0 [30] . [00] . [00] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: V [56] 0 [30] . [00] . [01] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
################avrdude: Send: V [56] 0 [30] . [00] . [02] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
################################## | 100% 0.06s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

I've double-checked and triple-checked, I've rebuilt the whole circuit on another breadboard with another ATmega328, I've even checked the jumper cables one by one, they all work.
How do I use my Arduino Uno as an ISP to upload code to this blank ATmega328?

Feeling really stupid about it in retrospect...
One last thing I tried was taking the ATmega328P out from the Arduino Uno and plugging the blank ATmega328 in its place, thinking I could use the Uno programmer as such to burn the bootloader on the chip. That didn't work and I don't know if it's supposed to work.
However, to plug the new chip into the DIL on the Uno, I had to bend the DIP legs inwards slightly to give it a smaller straddle. After seeing that it didn't work, I plugged the ATmega328P back into the Uno and plugged the ATmega328 back into the breadboard. However, this time, because of the smaller straddle, it slipped in deeper into the breadboard, the plastic package actually touching the board. And with this setup, wiring it up again via the Arduino and using the ArduinoISP I was able to burn both the bootloader and (via the 'Upload with programmer' functionality) test programs to it.
TL;DR: I didn't have the blank ATmega328 properly plugged into the breadboard...

Hehe so many times I've done something similar. :P

By the way, when checking connections it is always good to test for continuity from pin to pin. That way you pick up these kind of problems.

@geometrikal: how would I do that? I don't see how I could clip an alligator clip onto the tiny part of the DIP leg that sticks out of the breadboard.

Buy a multimeter with probes (e.g. http://www.thomasnet.com/articles/image/digital-multimeter.jpg). Can get a cheap set for < $20. Pretty handy for troubleshooting.

Do you have another UNO or similar? Try getting the boot loader upload working on a stock board just to confirm it is not the programmer. 0x000000 usually means it can't talk to the chip being programmed.

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

This is the clue to the solution. The signature is different between different versions of the ATmega328, for example:

ATmega328-PU
ATmega328P-PU

and so on...
You can google on "arduino signature error ATmega328P" to find the solution.
One hint is: http://forum.arduino.cc/index.php?topic=201920.0
I can be more specific if you post the version off the ATmega328 you have.

No (valid) AVR has a 0x000000 signature.


text:
HC-SRO4 always returns zero no matter what I do?
Wondering if it's the sensor or the code?  can anyone help?
I've used the code here
/*
HC-SR04 Ultrasonic Sensor with LCD dispaly

HC-SR04 Ultrasonic Sensor
  VCC to Arduino 5V
  GND to Arduino GND
  Echo to Arduino pin 12
  Trig to Arduino pin 13

LCD Display (I used JHD162A)
  VSS to Arduino GND
  VCC to Arduino 5V
  VEE to Arduino GND
  RS to Arduino pin 11
  R/W to Arduino pin 10
  E to Arduino pin 9
  DB4 to Arduino pin 2
  DB5 to Arduino pin 3
  DB6 to Arduino pin 4
  DB7 to Arduino pin 5
  LED+ to Arduino 5V
  LED- to Arduino GND

Modified by Ahmed Djebali (June 1, 2015).
*/
#include <LiquidCrystal.h> //Load Liquid Crystal Library
LiquidCrystal LCD(11,10,9,2,3,4,5);  //Create Liquid Crystal Object called LCD

#define trigPin 13 //Sensor Echo pin connected to Arduino pin 13
#define echoPin 12 //Sensor Trip pin connected to Arduino pin 12

//Simple program just for testing the HC-SR04 Ultrasonic Sensor with LCD dispaly
//URL:

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  LCD.begin(16,2); //Tell Arduino to start your 16 column 2 row LCD
  LCD.setCursor(0,0);  //Set LCD cursor to upper left corner, column 0, row 0
  LCD.print("Target Distance:");  //Print Message on First Row
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  LCD.setCursor(0,1);  //Set cursor to first column of second row
  LCD.print("                "); //Print blanks to clear the row
  LCD.setCursor(0,1);   //Set Cursor again to first column of second row
  LCD.print(distance); //Print measured distance
  LCD.print(" cm");  //Print your units.
  delay(250); //pause to let things settle
}

Is the LCD working correctly? Have you tried displaying the values over Serial? Also you can test with the examples, that comes with the NewPing library. If with the example it still not works, there is something wrong with the wiring or the sensor. Then you should show us the wiring. And you could test, if the sensor outputs anything.

I bet it's the sensor or the way you wired it. Add a Serial.println(duration); to eliminate any other overseen errors. Does that "0" appear every 0.25 sec or every 1.25 sec only? ( Which indicates a pulseIn timeout )

This is my first project and I am new to the arduino and programming stuff, and yes the LCD is working perfectly.When I try to display values on the Serial monitor nothing shows up but the LCD it displays- Target distance=0cm and when I remove the hcsr04 it displays values like 180,179,178 without the sensor.I've used the schematics from this site https://www.instructables.com/id/Arduino-LCD-Project-for-Measuring-Distance/.Or is there a problem with my code?

Where should I add Serial.println(duration); before the LCD.print(distance); or after the LCD.print("  cm"); ?

The position is not important, just after pulseIn. I don't see an obvious error with your code. The advises, that we can currently give you, are meant for debugging - finding the error.

I tried but there are no errors in the code.

Please dude,I am new to this type of stuff and Tbh I actually don't know what to do right now?I'm blank man.

Where do you think is the error in the code,or do I need to add something ? If please,let me know where to add the statements.

I've ordered a new HCSR-04 sensor,Thanks

Even the new hcsr04 detects 0 cm.Help?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Arduino - "expected primary-expression before '.' token" Error
#include "Ultrasonic.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  // put your setup code here, to run once:
  lcd.begin();
  Serial.begin(9600);
}
Ultrasonic ultrasonic(11, 12); //Ultrasonic ultrasonic(Trig,Echo);
void loop()
{
  int a = (Ultrasonic.Ranging(CM));
  if (a >= 15 && a < 20)
  { Serial.println("guvenli");
    lcd.print("guvenli");
    delay(500);
    lcd.clear();
    tone(3, 2000, 100);
    delay(500);
    noTone(3);
  }
  if (a >= 10 && a < 15) {
    Serial.println("guvenli dikkat");
    lcd.print("guvenli dikkat");
    delay(500);
    lcd.clear();
    tone(3, 2000, 50);
    delay(250);
    noTone(3);
  }
  if (a < 5)
  {
    Serial.println("vurdun");
    lcd.print("vurdun");
    delay(500);
    lcd.clear();**uıhhf
    tone(3, 2000, 50);
    delay(50);
    noTone(3);
  }
}

In this code i'm getting an error like this:
   C:\Users\*\AppData\Local\Temp\arduino_modified_sketch_113625\sketch_apr29a.ino: In function 'void loop()':

sketch_apr29a:19:22: error: expected primary-expression before '.' token

   int a = (Ultrasonic.Ranging(CM));

                      ^

exit status 1
expected primary-expression before '.' token

Please show as a full working example of your code, that shows the problem. This cannot be your full code. Also please provide a link to the library, that you use for Ultrasonic.

http://pasted.co/172df900

I guess you used the following libraries: LiquidCrystal-I2C and Ultrasonic-HC-SR04

And please copy your full code into the question, so that it does not rely on a link, that may become invalid over time. I did that for you now.

If I remove the **uıhhf in line 40 (which does seem like a typo), your sketch compiles fine for me. I don't receive the shown error. I'm using Arduino IDE 1.8.5 and Arduino Uno as target board.

this is all of code

now im getting this code: "Arduino:1.8.8 (Windows 8.1), Kart:"Arduino/Genuino Uno"
C:\Users\ETKullanici\Desktop\sketch_apr29a\sketch_apr29a.ino: In function 'void loop()':
sketch_apr29a:16:21: error: 'class Ultrasonic' has no member named 'Ranging'
int a=(ultrasonic.Ranging(CM));
                 ^

exit status 1
'class Ultrasonic' has no member named 'Ranging'
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences."

Then maybe you have a different ultrasonic library, than I linked above. Please provide a link to the library, that you really use.

i think it's not about library issue, you have `error: expected primary-expression before '.' token
int a = (Ultrasonic.Ranging(CM));but you are using a variableUltrasonic ultrasonic(11, 12);` Please check your code again!!.

@chrisl: You replaced the original code that generated the “expected primary-expression” error with modified code that no longer has that error. Why did you do that? Now the question makes no sense anymore.

@AnT I just copied the code from the pasted link, that the OP provided. You may vote to revoke my edit of the question

@chrisl: I understand. It means that the edit was made by the author of the code. Yet, it does not change the fact that the code no longer matches the error message, defeating the purpose of this entire question.

Ultrasonic is a class name. Why are you trying to use it before a . in an expression?
Judging by the declaration, you need ultrasonic. That is your object name. ultrasonic, not Ultrasonic.

Comparing the provided code with the error text, I would bet that one or the other is a typo, notice the case of 'ultrasonic' in the code does not match the corresponding line in the error.

@Kelly S. French: Well, if you look through the editing history, you'll see that the code in the original post did match the error text. Meanwhile, the pastebin version linked by the author in the comments is slightly different - the Ultrasonic error is already fixed. Later the code here was replaced with pastebin version. So the question became inconsistent with itself.

Good point, I had not considered looking through the edit history. My misgivings were more around my surprise at the error text given that a problem with strict case-matching wouldn't typically be related to a missing 'primary expression' as usually there needs to be a named identifier before the '.' and to expect an expression there would make me wonder if the cause were elsewhere, for instance the snippet ' **uıhhf in line 40 ' mentioned by chrisl, which definitely look like a syntax error but I can't see how it would generate that error either. Did the OP not include the whole error log?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to use an Arduino along with a PPG sensor to find respiration rate
I am working on a project where I am trying to determine respiration rate through an Arduino Nano and a MikroE Heart Rate 3 Click device.  I have been working on this for a few months, reading different research papers attempting to find an algorithm that would give me respiration rate values, but am having trouble finding an algorithm that both does what I need and encode it into the Arduino.  Does anyone know of a code that would work?
I have so far have only the basic code that reads the PPG values, but it does not provide me with the Respiration rate values.  This is the code I have so far:
/*
 * AFE4404 Basic Read library example.
 * https://github.com/rakshithbk/AFE4404-Library
 *
 * On Arduino Uno -  | AFE4404 | Uno Pin
 *                   | I2C_Dat | A4
 *                   | I2C_Clk | A5
 * get_led_val() will return uint32_t values.
 *
 * Advanced - you can modify the sample period and other
 * parameters in the library files (refer AFE4404 datasheet)
 */

#include <Wire.h>
#include <AFE_connect.h>

AFE A;

void setup() {
  Serial.begin(115200);
  Serial.println("AFE4404 basic readings -\n");
  A.init();
}

void loop() {
  Serial.print("LED 1 Val = ");
  Serial.print(A.get_led1_val());
  Serial.print("\t LED 2 Val = ");
  Serial.print(A.get_led2_val());
  Serial.print("\t LED 3 Val = ");
  Serial.print(A.get_led3_val());
  Serial.println();
}

You are basically asking the same thing, as the question before yours, which was asked by a different user. That's unusual in such temporal proximity. Are you somewhat related?

Yes our projects are related, as we are actually working together along with one other member.  However, while the other question asks about finding oxygen saturation from the sensor, I am focusing on how to find the respiration rate.  We have the initial code to get a reading but each need an individual algorithm with which we can determine the different measurements from those initial signals.


text:
processing data received via serial
Hey i'm trying to make an Arduino that can log key presses from a keypad and save that as a variable. When it receives information from another arduino via serial I want it to create a variable from each position (like comma separated values "/" in this case).Then if its being asked for its data by the master to transmit its string of data.
The code I have below is recording key presses, when it receives serial it puts it in to a string then looks at the first position in that string this becomes the variable RSVP, if RSVP is equal to the Arduinos address (iAm) and later if the checksum adds up, I would like it to respond with its serial string.
for some reason every serial command i send to it, it mirrors back the command i sent to it correctly but when i tell it to separate the first position in to the RSVP variable it always returns 1. Not sure if this is to do with converting characters to integers or something if that's all then hopefully an easy fix once you know how.
I have seen a few posts saying its best to use an array rather than a string (but this is based on the IDE serial example so not sure if that's correct)and presumable would need fully re writing which doesn't sound like an easy fix. Also I don't know how I would go about making an array from serial, and I might not to know how to separate CSVs I have seen a few examples but unfortunately i'm a dimwit. Been on this one problem for 3 days now and i'm still in exactly the same place, but with a slightly fried brain.
#include <Keypad.h>

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},

};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

int iAm = 1;                                    //this is device number 1
float checkSum = 0.00;                          //check sum to send as serial
float voltage = 5.26;                           //system voltage
int data[20] {0, 0, 0, 0, 0, 0, 0, 0, 0};       //keypad output call
char rsvp = 0;
int rsvp1 = 0;
void setup() {
  Serial.begin(9600);

  inputString.reserve(200);    // reserve 200 bytes for the inputString:
}

void loop() {

  int key = keypad.getKey();

  if (key) {
      int key1 = key -48;

      if (data[key1] == 1){
       data[key1] = 0;

      }
      else {
        data[key1] = 1;
      }

  }
    // print the string when a newline arrives:
  if (stringComplete)  {
    rsvp = inputString.charAt(0);
    rsvp1 = int(rsvp);

    if (rsvp1 = iAm) {
      checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
      Serial.print(inputString);
      Serial.println(rsvp1);
      Serial.print(iAm);
      Serial.print("/");
      Serial.print(data[1]);
      Serial.print("/");
      Serial.print(data[2]);
      Serial.print("/");
      Serial.print(data[3]);
      Serial.print("/");
      Serial.print(data[4]);
      Serial.print("/");
      Serial.print(data[5]);
      Serial.print("/");
      Serial.print(data[6]);
      Serial.print("/");
      Serial.print(data[7]);
      Serial.print("/");
      Serial.print(data[8]);
      Serial.print("/");
      Serial.print(data[9]);
      Serial.print("/");
      Serial.print(voltage);
      Serial.println("/");
      Serial.println(checkSum);
    // clear the string:
    inputString = "";
    stringComplete = false;
    }
  }
}
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  de
   if (Serial.available() > 0) {
    int recieved = Serial.read();
    if (recieved == iAm){
      checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
      Serial.print(iAm);
      Serial.print("/");
      Serial.print(data[1]);
      Serial.print("/");
      Serial.print(data[2]);
      Serial.print("/");
      Serial.print(data[3]);
      Serial.print("/");
      Serial.print(data[4]);
      Serial.print("/");
      Serial.print(data[5]);
      Serial.print("/");
      Serial.print(data[6]);
      Serial.print("/");
      Serial.print(data[7]);
      Serial.print("/");
      Serial.print(data[8]);
      Serial.print("/");
      Serial.print(data[9]);
      Serial.print("/");
      Serial.print(voltage);
      Serial.println("/");
      Serial.println(checkSum);
    }
   }
}

the program does not record the sequence of keypresses ... it only records which keys were pressed ... is that the desired behavior?

yea that's correct, its just to tell the master which outputs it would like off or on, the master will reply telling the keypad which outputs are on which will turn on an associated LED on the keypad. any additional keypads on the same serial network will also get  the message and know to update their demand for outputs to the current master state.

do you have an answer to the original question jsotola?

one of your if statements does not evaluate the comparison of two values, but actually assigns the value of one variable to another variable ... it is what is called a logic error ... syntax is correct, but the if statement does not do what you expected

main question is why are you not debugging the code? ... i see no serial.print() statements throughout your code, so that you could see the value of variables as the program execution progresses

the debugging serial prints are here if (rsvp1 = iAm) {
checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
Serial.print(inputString);
Serial.println(rsvp1);
Serial.print(iAm); rsvp1 and iAm are the variables being compared in the if statement that was causing problems, so the serial prints are immediately after the part of the code that was causing the issue, is there a better place for the debugging to be done, or a better way of doing it? thanks,  the == got me closer.

use your immagination ... do not assume that a variable has some particular value ... for instance, rsvp = inputString.charAt(0); ... you don't actually know the value of rsvp after that statement executes


text:
SG 90 not working
I have tried almost everything but the servo is not moving at all
here is my schematics
https://create.arduino.cc/projecthub/arcaegecengiz/how-to-use-servo-motors-with-arduino-b02bed
Here is my code
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

I cannot see your schematics, since they seem to be in fritzing format (fzz?) and I don't have that program. So please include the schematic as image in your question. Also, since that is a schematic from a tutorial, a good quality, in focus picture of your actual setup (where we can see the actual connections) might be good. Your code seems to be the standard sweep example. I don't see much to troubleshoot there


text:
How to expand this code for more than four 74hc165 shift registers? It works well with maximum four 74hc165 shift registers at a time
#define NUMBER_OF_SHIFT_CHIPS   4
#define DATA_WIDTH   NUMBER_OF_SHIFT_CHIPS * 8

int LoadPin    = 9;
int EnablePin  = 8;
int DataPin    = 11;
int ClockPin   = 12;

unsigned long pinValues;
unsigned long oldPinValues;

void setup()
{
  Serial.begin(9600);

  pinMode(LoadPin, OUTPUT);
  pinMode(EnablePin, OUTPUT);
  pinMode(ClockPin, OUTPUT);
  pinMode(DataPin, INPUT);

  digitalWrite(ClockPin, LOW);
  digitalWrite(LoadPin, HIGH);

  pinValues = read_shift_regs();
  print_byte();
  oldPinValues = pinValues;
}

void loop()
{
  pinValues = read_shift_regs();
  if (pinValues != oldPinValues)
  {
    print_byte();
    oldPinValues = pinValues;
  }
}

unsigned long read_shift_regs()
{
  long bitVal;
  unsigned long bytesVal = 0;

  digitalWrite(EnablePin, HIGH);
  digitalWrite(LoadPin, LOW);
  delayMicroseconds(5);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(EnablePin, LOW);

  for (int i = 0; i < DATA_WIDTH; i++)
  {
    bitVal = digitalRead(DataPin);
    bytesVal |= (bitVal << ((DATA_WIDTH - 1) - i));

    digitalWrite(ClockPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(ClockPin, LOW);
  }

  return (bytesVal);
}

void print_byte() {
  byte i;
  Serial.println("*Shift Register Values:*\r\n");

  for (byte i = 0; i <= DATA_WIDTH - 1; i++)
  {
    Serial.print(pinValues >> i & 1, BIN);

    Serial.print("  ");

  }
  Serial.print("\n");
  Serial.println(); Serial.println();
}

Welcome to Arduino:SE.  Where did you get this version of the code?

possibly not a code problem

And what happens when you use more than 4 (by daisy chaining more shift registers and setting NUMBER_OF_SHIFT_CHIPS accordingly)? What is the actual problem description? What did you expect to happen and what actually did happen? What was the Serial output and the expected Serial output?

It looks like your read_shift_regs() function returns an unsigned long value, which consists of 32 bits. Each shift register reads back 8 bits, so with 4 of these shift registers you will fill all bits of a 32-bit unsigned long. If you attempt reading more than 4 registers, you will lose previously read bits. The solution is to make a function that can return more than 32 bits.

I would just add another shift register chain. A schematic would help understand better what you are doing.

After I put 'NUMBER_OF_SHIFT_CHIPS' as 5, the 1st shift register doesn't work but 5th one starts working. Also when I put  'NUMBER_OF_SHIFT_CHIPS' as 6 then 1st and 2nd shift registers don't work but rest four shift registers start working. So, I think @StarCat is right. What needs to be changed in this code?

You need to understand the code to think on a solution. There are several possible solutions, but you should try the ones you understand. You may start by thinking how to "organize" more than 32 bits. As you found, an unsigned long cannot do this, perhaps an array of unsigned char or uint8_t is fine. -- We commonly don't give recommendations because that leads to opinion-based discussions, which are frowned upon.

As StarCat mentioned in the comments, you return the read value as an unsigned long, which can hold exactly 4 bytes. When trying to write more into it with your current code you will loose the previous data. So you need a data structure that is able to hold all the data that you want to read.
I suggest that you do it like the shiftIn() function of the Arduino framework: Use a DATA_WIDTH of 8 bits (1 byte) and enclose the reading loop into another for loop, where you iterate over NUMBER_OF_SHIFT_CHIPS, getting exactly one byte from each chip and putting it into an array of byte (aka uint8_t). There are multiple ways to do this, but I will describe only one, not necessarily the best one for your situation.
First declare an array of byte on global scope. It needs to be NUMBER_OF_SHIFT_CHIPS bytes big. We initialize the data to zero:
byte shift_data[NUMBER_OF_SHIFT_CHIPS] = {0};

Set DATA_WIDTH to 8 bits:
#define DATA_WIDTH   8

Now look into read_shift_regs(). Enclose the for loop into another for loop iterating over NUMBER_OF_SHIFT_CHIPS and use that index to write the data into the corresponding byte in shift_data (by using shift_data[j] with the corresponding index j). As we write a global array we don't need to return anything, so you can make the function void (unless you want to return some other information).
void read_shift_regs()
{
  long bitVal;

  digitalWrite(EnablePin, HIGH);
  digitalWrite(LoadPin, LOW);
  delayMicroseconds(5);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(EnablePin, LOW);
  for(int j = 0; j < NUMBER_OF_SHIFT_CHIPS; j++){
    for (int i = 0; i < DATA_WIDTH; i++)
    {
      bitVal = digitalRead(DataPin);
      shift_data[j] |= (bitVal << ((DATA_WIDTH - 1) - i));

      digitalWrite(ClockPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(ClockPin, LOW);
    }
  }
}

Then change all lines with
pinValues = read_shift_regs();

to
read_shift_regs();
And finally - to actually use the read values - you now need to access a complete array instead of a single variable. I will leave that to you. Basically its again just iterating over all elements of the array.
Note:

I have not tested the above code in any way. Its more about explaining the principle.
One can also handle the array with parameters, but if you don't know how to use arrays as parameters, then this can give you a lot of other errors. So I didn't suggest that.

using void before read_shift_regs() function gives error "void value not ignored as it ought to be". Which data type should I use here and why? Also, to print the output I use a for loop to return the shift_data[j] but output does not change.   P.S : I might be wrong here because i am new to arduino coding.

If you look at my implementation of the function you see that I don't use return. The functions doesn't need to return anything because the data is already globally a available in the array. And you get that error because you probably still have pinValues = read_shift_regs(); somewhere. As I instructed you need to remove erything before the function call in that line (so no assignment with = )

What do you nean by "use a for loop to return shift_data[i]"? You can only return one time, not multiple times

If you look at above code in void loop, I have set if(pinValues!=oldpinValues) then the output bytes are printed for complete 8 x 8 matrix. I am not able to get the output here. Can you suggest a way to read values such that I can see them in Serial monitor? So, that I can take it as a reference for printing outputs.


text:
How can I get an external program to change values inside the Arduino C++ code?
How can I get some constantly changing values from a separate C++ program entered and uploaded into the Arduino?
I notice when I upload code to the Arduino in the IDE it takes about a second to start moving. This is also a problem. I would like there to be no delay after instructions to the motor change.
My goal is to get a trained neural network model from the PyTorch C++ version to control the motor's spin and speed. I would assume the IDE does not allow one to import PyTorch?
I tried looking around on the Arduino website for this, but it seems like the IDE is the only option. My solution would be something that imports the Arduino library into a C++ program just like I import the PyTorch library into my C++ program.
My ficticous C++ code. Just written to illustrate what I would like to happen.
import pytorch
import arduino

// if I had an encoder on the motor giving position readings as inputs (I know this isn't how it's done in real code)
sensors = arduino_encoder_sensors

// trained model
m = pytorch.load_torch_model('model')

// model taking sensors as inputs and outputting desired speed and distance executions to the motor
speed, dist = m(sensors)

Arduino Code:
const int stepPin = 8;
const int dirPin = 9;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}
  digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  for(int x = 0; x < dist; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(speed);
    digitalWrite(stepPin,LOW);
  delay(1000); // One second delay
}

the Arduino sketch runs on the Arduino, you can send values to the Arduino over serial port

Thank you. I'm looking around for this option. Any examples what code into the serial port looks like? Is it something I can send out of any C++ program? I can't picture how this works. Not the USB, but a serial port?

your fictitious code has no I/O to another device ... it also has a 1 second delay, during which the arduino is doing nothing ... see blinkWithoutDelay example sketch

It sounds like self modifying code, that will not work, it takes a lot of time. Why not set up a communication link so they can talk to each other. You can use CAN, Ethernet or something else depending on how much data and how fast it has to be transfered. RS485 will work with the serial port in the Arduino. Remember if the processor only has one USART that will also have to be used for uploading code etc.  The data can be saved in RAM. You can use software serial or another Arduino that has more than one port.

It's difficult to understand what you're asking. An Arduino program is just C++ code; if a library is compatible you can import it. Arduinos can also be very resource-constrained, so the type of Arduino is important to know. Any editor/IDE with some form of Arduino support can be used (e.g., I use the Arduino IDE, VS Code, and CLion).

Is it a copy and paste error, that you don't have a loop() function? Currently your code isn't compilable. And are you missing a closing bracket for the for loop? Currently the delay is inside the for loop, but I think you mean it to be outside.

What values?  Both ways?  From arduino -> otherComputer and from otherComputer -> Arduino?

Your question seems very confused, so I will try to shine a light on some basic distinctions.

How can I get some constantly changing values from a separate C++ program entered and uploaded into the Arduino?

In your whole question you seem to confuse program and data. The program on the Arduino doesn't need to change with every changing of the values. Instead you would have a constant program, which receives changing values from the PC.
So it seems you want to send data from your python program on your PC to the Arduino. This data doesn't have anything to do with the actual program on the Arduino. The program just should use the data to act accordingly. You can use any of the communication interfaces that are usable with Arduinos and PCs, though the simplest option would be the Serial interface, which gets bridged to your PC via the USB port. The Serial interface is what you see in the Serial Monitor.
How to use a serial port in python can be googled quite easily. For the Arduino side there are many tutorials and examples about it online. You would also need to think about your communication protocol, which you want to impose on the Serial byte stream. For example you could use ASCII encoded text, each message delimited to the next by a newline character '\n', each message containing first the command and then needed parameters. Since only you know what exactly you want to send to the Arduino, you need to design this yourself.

I notice when I upload code to the Arduino in the IDE it takes about a second to start moving. This is also a problem.

This is due to the bootloader. When you upload a program this is done via the Serial interface. Normally microcontrollers can only be programmed over specialized interfaces (like ISP). But Arduinos (and other microcontrollers) can be programmed with a bootloader. That is a program sitting on the microcontroller, which runs anytime you power the microcontroller on your reset it. On Arduinos it will listen on the Serial port for a moment in the case that you want to upload a new code. If yes, then it handle the communication and write the new code to the Arduinos flash memory. If not, it will execute whatever program currently is saved in flash.
So you cannot avoid this delay without changing or deleting the bootloader. Deleting it would mean that you need a programmer board to upload new code (another Arduino can do that). Changing it would also require a programmer board, because you would need to write the new bootloader version to the Arduino with it.
I would debate if this delay is really a problem. It only appears on a reset, like when you upload new code. And why would you want to reset the Arduino or upload new codes that fast? For doing your motor movement you don't need new programs on the Arduino for every movement; you need a code that will move according to data send through the Serial interface. And that doesn't require resetting. And it works fast.
That said, with your current code (ignoring the obvious syntax problems most likely from copy and past errors) you will still have delays, even when you implement Serial communication. In general you shouldn't use long delay() calls. You use delay(1000), which makes the Arduino twiddle its thumbs for one whole second each loop iteration. Instead use the non-blocking coding style shown in the BlinkWithoutDelay example that comes with the Arduino IDE. It uses the millis() function as a clock, checking it regularily for the time to do something. There are many tutorials about that online.

My goal is to get a trained neural network model from the PyTorch C++ version to control the motor's spin and speed. I would assume the IDE does not allow one to import PyTorch?

No, it doesn't. It is based on Java, not on python. As described above you need to write your own python program and use a fitting serial port python module for the communication over the Serial interface. In that python program you can import PyTorch, do your  neural network processing and then send the resulting commands over Serial to the Arduino.

I tried looking around on the Arduino website for this, but it seems like the IDE is the only option. My solution would be something that imports the Arduino library into a C++ program just like I import the PyTorch library into my C++ program.

It is not really clear what you mean here. For communicating with an Arduino over Serial you can use any program that can interface with a serial port on your PC. There are many programs dedicated for this. Since you want to do your neural networking stuff in python, just use a fitting python module that handles serial port connections.
If you talk about writing programs for Arduinos and uploading them: This can be done in many other IDEs other than the Arduino IDE. Dave Newton mentioned some in his comment: VS Code and CLion. I also remember the Atom IDE. Or you can write your code in any text editor of your liking and then compile and upload the code with the Arduino CLI tool (that's what I do mostly).

I hope this clears up the confusion a bit so that you now can work toward a working solution.

I want to import PyTorch and a saved model into the Arduino IDE. I didn't know if this was possible, but I'm working on figuring out if that is possible now. If I can't import PyTorch and the model into the IDE then I need the Arduino library and ability to 'upload' code to the Arduino device in some other way that I am not yet aware of. This is what I am asking. I'd appreciate an upvote on my question. I don't see any part of it as confused. I'm not being snarky when I say that. I am NOT going to be using Python. If someone would just suggest a method other than the IDE I would give them a gr

@Ant But if you don't want to use python, why do you want to import PyTorch, which is a python library? And you definitely cannot import PyTorch in the Arduino IDE or an Arduino program. Just completely different frameworks. There might be C++ libraries for neural networks which are Arduino compatible, but then the Uno is most likely a bad choice, since it has so few RAM and processing power. Does the model fit in 2KB RAM? I think there are microcontroller boards dedicated to AI stuff with way more RAM and processing power (most likely not directly by Arduino but Arduino compatible).

PyTorch is available in a C++ version. I am using PyTorch in C++

Ah, ok, must have overread that. Sure, you can include any C++ libraries in your code that you like. You will need to place these libraries either in the libraries folder or in the same folder as the sketch so that the Arduino IDE finds them. Though I don't know of they are compatible or usable with Arduinos. You can try it. I would guess that you run into memory problems on the Uno. Also have a lookout for dynamic memory allocation, which is often really bad on microcontrollers due to memory fragmentation. Tomorrow I eill change my answer to fit better

Dave Newton answered that I could import any C++ library. I didn't realize the IDE was flexible enough to do that. Since he said that I have been trying to install the C++ version of PyTorch. It's taking me hours to get it installed with the right CUDA version and getting Pytorch 'built' after the install. The answer to my OP is to launch Arduino in an env with Libtorch installed and put #include <torch/torch.h> in the IDE. I think. Should work, I'm told here.

I was thinking about memory earlier today. Yes, I might need a custom upgrade!


text:
Can a MEMS accelerometer sensor be used as a shock sensor?
I am trying to make an IOT project- SMART DOOR where I have used a serve motor and NodeMcu and for adding further functionality I have been thinking of adding a theft detection feature where whenever a large force is applied on the lock an alarm starts beeping and for that I don't have a shock sensor but I do have MEMS accelerometer sensor(MPU6050 Accelerometer and Gyroscope).
So can I use it to add this functionality?
If yes, can I get a little guide on what configuration and sensitivity I should use?
THANK YOU!

Please don't scream at us. I removed the capslock from the title for you

haha! Thank you :D

Sure you can. A "shock" is merely a large amount of acceleration over a short period of time.
You would probably want to set the MPU6050 to its least sensitive setting (±16g), and you might even be able to make use of the "tap" function whereby the MPU6050 itself looks for a sudden short sharp shock to trigger an interrupt (though that may be a little too sensitive for your needs, I don't know).

Thank you so much!


text:
ESP32 SPI communication with MCP3903 not working
I am trying to read out the Microchip MCP3903 six channel ADC using an ESP32 via SPI communication. The MCP3903 is powered with 5V and 3,3V and is connected with an external 3,57 MHz crystal. The ESP32 I use is the Olimex ESP32-EVB and the code is uploaded with the Arduino IDE. It works perfectly for other projects, so the ESP seems to be OK.
For the MCP3903 a library exists (https://github.com/mjklopfer/MCP3903) with an example that I am trying to run but nothing is happening. I have tried to use VSPI (GPIO 23, 19,18 and 5) and HSPI (GPIO 13, 12, 14, 15) but I am not getting a CLK signal when I check with the scope. I also tried to alter the code using pointers as suggested here: SPI Digital Potentiometer not working on ESP32, but also that is not changing anything.
You can find the code of the MCP3909 example that I am trying out below. I suppose that when the MCP is not connected, I would still see the CLK running? Is there something special that needs to happen with the GPIOs, like pull-up resistors or something the like? How can I check that the problem is software related or hardware related?
/*
mcp3903example.ino
Arduino example for the MCP3903 - Example tested
Extended from the Arduino Library for MCP3903 A/D Converter
 * MCP3903 Library
 * Kerry D. Wong
 * http://www.kerrywong.com, http://www.kerrywong.com/2014/05/10/mcp3903-library/, https://github.com/kerrydwong/MCP3903) * 5/2014
Minor Arduino Feature extensions by Zhi Luo, Kaixin Chen, Yaxin "Erica" Deng, Yutian Ren, and Michael Klopfer, Ph.D.
University of California, Irvine
2018
*/

#include <SPI.h>
#include "MCP3903.h"

//Set the gains and offsets for your ADC channels:
#define ch0_gain 2.383490972 //these are values for calibration. By setting these values, reads will be the same as the inputs.
#define ch0_offset -0.007884781 //the maximum read for each channel will be around 0.7866. The deviation for these values is around 2%

#define ch1_gain 2.383490972
#define ch1_offset -0.007884781

#define ch2_gain 2.383490972
#define ch2_offset -0.007884781

#define ch3_gain 2.383490972
#define ch3_offset -0.007884781

#define ch4_gain 2.383490972
#define ch4_offset -0.007884781

#define ch5_gain 2.383490972
#define ch5_offset -0.007884781

MCP3903 mymcp3903;  //Initialize mymcp3903 object for the MCP3903

void setup()
{
    //esp.begin(); Needed with ESP8266 for ESP class functions
  Serial.begin(9600); //set serial comm at 9600 bps
  SPI.begin(); //Start SPI
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));  //Start SPI transaction with defined parameters
        mymcp3903.init(10); // (10 for UNO; 15 for esp8266)Setings for your Arduino's/ESP8266's SPI pin used for interfacing(pinCS) - make sure this is the pin you have your CS on!
        mymcp3903.reset(MCP3903::OSR_256);
        mymcp3903.setGain(1,MCP3903::GAIN_8);
  //Need to initialize all channels to use
  SPI.endTransaction(); //End SPI transaction

}

void loop()
{
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));  //Start SPI transaction with defined parameters

  //Print out the ADC value of channel 0
  Serial.print("Channel 0 ADC Value: "); //Start your line here
    double ch0 = mymcp3903.readADC(0);
    double ch0Cal = (ch0* ch0_gain)+ch0_offset;
    Serial.println(ch0Cal);//Add value then end your line
  delay(10);  //Delay before next Ch read (totally optional)

  //Print out the ADC value of channel 1
    Serial.print("Channel 1 ADC Value: "); //Start your line here
    double ch1 = mymcp3903.readADC(1);
    double ch1Cal = (ch1* ch1_gain)+ch1_offset;
    Serial.println(ch1Cal);//Add value then end your line
  delay(10);  //Delay before next Ch read (totally optional)

  //Print out the ADC value of channel 2
    Serial.print("Channel 2 ADC Value: "); //Start your line here
    double ch2 = mymcp3903.readADC(2);
    double ch2Cal = (ch2* ch2_gain)+ch2_offset;
    Serial.println(ch2Cal);//Add value then end your line
  delay(10);  //Delay before next Ch read (totally optional)

  //Print out the ADC value of channel 3
  Serial.print("Channel 3 ADC Value: "); //Start your line here
    double ch3 = mymcp3903.readADC(3);
    double ch3Cal = (ch3* ch3_gain)+ch3_offset;
    Serial.println(ch3Cal);//Add value then end your line
  delay(10);  //Delay before next Ch read (totally optional)

  //Print out the ADC value of channel 4
  Serial.print("Channel 4 ADC Value: "); //Start your line here
    double ch4 = mymcp3903.readADC(4);
    double ch4Cal = (ch4* ch4_gain)+ch4_offset;
    Serial.println(ch4Cal);//Add value then end your line
  delay(10);  //Delay before next Ch read (totally optional)

  //Print out the ADC value of channel 5
  Serial.print("Channel 5 ADC Value: "); //Start your line here
    double ch5 = mymcp3903.readADC(5);
    double ch5Cal = (ch5* ch5_gain)+ch5_offset;
    Serial.println(ch5Cal);//Add value then end your line
  delay(10);  //Delay before next Ch read (totally optional)

    delay(100);  //Delay, then re-run loop to read sensors again
  //SPI.endTransaction(); //End SPI transaction - we are keeping this open for this example
}

I suggest you just reduce your program to using SPI to send a byte repeatedly. Remove the MCP3903 library from the equation.


text:
Arduino Mega reading from external sensor Issue
I have one external sensor and I want it to be connected with Arduino. The sensor came up with a usb cable and the pin out diagram is also given in the data sheet .
When I simply connect the the cabe which came along the sensor (E322968) with no Arduino board involved, but through Arduino IDE and setting baud rate to 115200 I am able to see the output in serial monitor of the Arduino .

I want to capture this data to some variables for further manipulation. In the data sheet the pinout is specified as

Please help me get the data to Arduino variable .
What I tried is connected,

the RX1 or Arduino mega to the TX1 of the sensor (pin2) and
from Arduino VCC(5v) to VCC of the sensor :: pin(1)
ground to gnd of sensor, (pin5)

the RX1 or Arduino mega to the TX1 of the sensor (pin2) and

That will not work. These pins are for RS232, which uses the same communication protocol (UART) as the Arduino, but it uses different voltage levels. But fortunately your sensor has also RX and TX pins at TTL level (Transistor-Transistor-Logic). You want to connect these to the Arduino.
One thing to keep in mind: The sensor logic seems to work at 3.3V (voltage on the RX and TX lines). If you also want to send data to the sensor, you may need to step down the 5V of the Uno to the 3.3V of the sensor on its RX line (since 5V might damage the sensor). You can use a simple voltage divider with 2 resistors or a proper level shifter (which uses transistors) (voltage dividers limit the communication speed, though 115200baud should not be a problem).

It will be very much help full if you can share a schematic for the same including the level shifter to be used. And I am using  an Arduino Mega

Look for example here. Though you only need this, if you want to connect Arduino TX to sensor RX (for sending data to the sensor). You don't write, if you really need that

Thanks , I want to connect Tx(ard)->Rx(sens) , may be in future as I can send commands to the sensor for changing the output modes .

More correctly: RS232 is the protocol (standard) and an UART (universal asynchronous receiver/transmitter) is a type of integrated circuit (IC - chip) that is designed to work a.o. according to that protocol.


text:
Newbie interfacing MLX90614 with arduino Due (Atmel3X8E)
I am a newbie trying to interface the infrared temperature sensor MLX90614 with the arduino Due. But it keeps sending out junk values in the serial monitor. I've tried it out on the Arduino Mega and it works perfectly. What might be the problem and how do I rectify it?
Thanks in advance.
#include <Wire.h>
#include <Adafruit_MLX90614.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit MLX90614 test");
  mlx.begin();
}
void loop() {
  Serial.print("Ambient = "); Serial.print(mlx.readAmbientTempC());
  Serial.print("*C\tObject = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");
  Serial.print("Ambient = "); Serial.print(mlx.readAmbientTempF());
  Serial.print("*F\tObject = "); Serial.print(mlx.readObjectTempF()); Serial.println("*F");
  Serial.println();
  delay(500);
}

Please include your code into your question

How do you wire the MLX90614 with the board? What MLX90614 interface/shield you are using? One thing that I could think of is that Arduino Mega is a 5V development board, while Arduino Due is a 3.3v development board.

@chrisl the code is the same example in the library to check the working of the sensor.

hcheung .. no, i am not using any shield for this..


text:
Substitute multiple potentiometers for push buttons and single potentiometers
this is my first post here.
For some time I have been struggling with a problem and would like to know if anyone has a solution to share.
I am building a 4 tone sequencer, where I use 4 potentiometers to change the pitch of each tone beat. I want to add more beats to the sequencer so I would like to have an elegant solution instead of keep adding potentiometers.
 My idea was to use 1 potentiometer to control the pitch and use multiple push buttons with the single potentiometer for this process.
 All in all it goes like this:
 - When switch1=HIGH, pitch1=analogRead(A0);
 - When switch2=HIGH, pitch2=analogRead(A0);
 The problem is that when I change pitch1 and pitch2 the end up getting the same values as soon as I press their switch. My code looks like this:
   if(switch1state==HIGH)
  {
    Tone1Pot=analogRead(A0); // 0 – 1023
    pitch1=Tone1Pot/13;
  }

tone(speakerPin, notes[pitch1], 200);

Serial.print(pitch1);
Serial.print("     ");
delay(tempo);

if(switch2state==HIGH)
  {
    Tone2Pot=analogRead(A0); // 0 – 1023
    pitch2=Tone2Pot/13;
  }

tone(speakerPin, notes[pitch2], 200);

Serial.print(pitch2);
Serial.print("     ");
delay(tempo);

I would really like to store that analog reading value when I press switch1 and keep it until switch1 goes HIGH again.
EDIT:
Let me try to explain the issue better:
I have 2 push buttons and 1 potentiometer, all of them are inputs. The code I am aiming for is to do the following: 1 - While pressing push button1 I want to read the value of potentiometer and store it to a variable1. When the button1 is not pressed I want to keep that variable stored. 2 - While pressing push button2 I want to read the value of potentiometer and store it to a variable2. When the button2 is not pressed I want to keep that variable stored.
I have successfully achieved this, however the problem comes when I press button1 again to adjust variable1, variable2 is also getting adjusted in the process, even when I am not pressing button2
Chris - The push buttons are correct since I can change the states of the digital pins when I press them ( and I measure the 5V when pressed). I do not need the buttons to be pressed at the same time. What I need is the buttons to trigger the event of storing potentiometer data only when either one of them is pressed accordingly.
jsotola - Sorry for the bad explanation. I hope this one is better.
Code:
#include "pitches.h"

int notes[]={

NOTE_B1,
NOTE_C2,
NOTE_CS2,
NOTE_D2,
NOTE_DS2,
NOTE_E2,
NOTE_F2,
NOTE_FS2,
NOTE_G2,
NOTE_GS2,
NOTE_A2,
NOTE_AS2,
NOTE_B2,
NOTE_C3,
NOTE_CS3,
NOTE_D3,
NOTE_DS3,
NOTE_E3,
NOTE_F3,
NOTE_FS3,
NOTE_G3,
NOTE_GS3,
NOTE_A3,
NOTE_AS3,
NOTE_B3,
NOTE_C4,
NOTE_CS4,
NOTE_D4,
NOTE_DS4,
NOTE_E4,
NOTE_F4,
NOTE_FS4,
NOTE_G4,
NOTE_GS4,
NOTE_A4,
NOTE_AS4,
NOTE_B4,
NOTE_C5,
NOTE_CS5,
NOTE_D5,
NOTE_DS5,
NOTE_E5,
NOTE_F5,
NOTE_FS5,
NOTE_G5,
NOTE_GS5,
NOTE_A5,
NOTE_AS5,
NOTE_B5,
NOTE_C6,
NOTE_CS6,
NOTE_D6,
NOTE_DS6,
NOTE_E6,
NOTE_F6,
NOTE_FS6,
NOTE_G6,
NOTE_GS6,
NOTE_A6,
NOTE_AS6,
NOTE_B6,
NOTE_C7,
NOTE_CS7,
NOTE_D7,
NOTE_DS7,
NOTE_E7,
NOTE_F7,
NOTE_FS7,
NOTE_G7,
NOTE_GS7,
NOTE_A7,
NOTE_AS7,
NOTE_B7,
NOTE_C8,
NOTE_CS8,
NOTE_D8,
NOTE_DS8
};

int Tone = 0;
int speakerPin = 3;

int switch1=6;
int switch2=7;
int switch3=8;
int switch4=9;
int switch5=10;
int switch6=11;
int switch7=12;
int switch8=13;

void setup() {

Serial.begin(9600);

pinMode(switch1, INPUT);
pinMode(switch2, INPUT);
pinMode(switch3, INPUT);
pinMode(switch4, INPUT);
pinMode(switch5, INPUT);
pinMode(switch6, INPUT);
pinMode(switch7, INPUT);
pinMode(switch8, INPUT);

}

void loop() {

 // get potentiometers inputs
//int TonePot = analogRead(A0); // 0 – 1023
//int DurationPot = analogRead(A1); // 0 – 1023
int TempoPot = analogRead(A2); // 0 – 1023

int Tone1Pot;
int Tone2Pot;
int Tone3Pot;
int Tone4Pot;
int Tone5Pot;
int Tone6Pot;
int Tone7Pot;
int Tone8Pot;

int Duration1Pot;
int Duration2Pot;
int Duration3Pot;
int Duration4Pot;
int Duration5Pot;
int Duration6Pot;
int Duration7Pot;
int Duration8Pot;

// calculate corresponding, divide by 13 as we have 77 pitches. 1023/77 ~ 13
int pitch1;
int pitch2;
int pitch3;
int pitch4;
int pitch5;
int pitch6;
int pitch7;
int pitch8;

int pitch1stored;
int pitch2stored;

int noteduration1 = Duration1Pot/8;
int noteduration2 = Duration2Pot/8;
int noteduration3 = Duration3Pot/8;
int noteduration4 = Duration4Pot/8;
int noteduration5 = Duration5Pot/8;
int noteduration6 = Duration6Pot/8;
int noteduration7 = Duration7Pot/8;
int noteduration8 = Duration8Pot/8;

int tempo = TempoPot;

//Get state of switches if HIGH or LOW
int switch1state=digitalRead(switch1);
int switch2state=digitalRead(switch2);
int switch3state=digitalRead(switch3);
int switch4state=digitalRead(switch4);
int switch5state=digitalRead(switch5);
int switch6state=digitalRead(switch6);
int switch7state=digitalRead(switch7);
int switch8state=digitalRead(switch8);

////////////////////////////////////////Sound generation code /////////////////////////////////

if(switch1state==HIGH)
  {
    Tone1Pot=analogRead(A0); // 0 – 1023
    pitch1=Tone1Pot/13;
  }

tone(speakerPin, notes[pitch1], 200);

//tone(speakerPin, 0, 200);}// make the tone mute

Serial.print("pitch1= ");
Serial.print(pitch1);
Serial.print("     ");
delay(tempo);

if(switch2state==HIGH)
  {
    Tone2Pot=analogRead(A0); // 0 – 1023
    pitch2=Tone2Pot/13;
  }

tone(speakerPin, notes[pitch2], 200);

Serial.print("pitch2= ");
Serial.print(pitch2);
Serial.print("     ");
delay(tempo);

if(switch3state==HIGH)
  {
    Tone3Pot=analogRead(A0); // 0 – 1023
    pitch3=Tone3Pot/13;
  }

tone(speakerPin, notes[pitch3], 200);

Serial.print("pitch3= ");
Serial.print(pitch3);
Serial.print("     ");
delay(tempo);
}

what causes this state?  switch1=HIGH

The description of your problem is unclear to me, please elaborate more. Also please provide the full code, not just a small part of it.

store that analog reading value when I press switch1 and keep it until switch1 goes HIGH again  ... what does that mean? ... what does switch1 goes HIGH again actually mean? ... i think that your main problem is that you do not actually know how you want the device to work

I cannot see, how your code would show the described behavior (assuming that, you have connected the buttons correctly with a pulldown resistor). But your code can be greatly simplified, which would make it less error prone.
You have 8 buttons, which screams for the usage of arrays (IMO you should always use arrays, if you have more than 2 or 3 equal buttons). First put the button pins into an array:
#define N_BUTTONS 8
int button_pins[N_BUTTONS] = {6, 7, 8, 9, 10, 11, 12, 13};

Then define an array to hold the measured pitches (here initialized with 0):
int pitches[N_BUTTONS] = {0};

In your setup() function you can loop over the button_pins array to set them as input:
for(int pin : button_pins) pinMode(pin, INPUT);

In the loop() function you again loop over the button pins, but this time you check, if the current button is pressed. If yes, you measure the analog voltage, calculate the pitch and save it into the corresponding element of the pitches array:
for(int button=0;button < N_BUTTONS;button++){
    if(digitalRead(button_pins[button])){
        pitches[button] = analogRead(A0)/13;
    }
}

This always works for multiple pressed buttons at once.
Also you should avoid calls to delay() in your loop() function. That is just time, that the Arduino cannot do anything, including checking your buttons. If you want to do something timed, you should use a non-blocking coding style, like in the BlinkWithoutDelay example, that comes with the Arduino IDE. Basically it uses the millis() function as a clock, checking regularily, if the needed time has passed and only doing something if it had passed; letting other code execute, if not. There are tons of tutorials about this on the web.
As you have seen above, I didn't include the tone() function in my answer. That is because you should decouple your input and output code. The code above is the input code. It saves the wanted pitches into the corresponding array. Then, after that code, you can write all the code you need for outputting the pitches as tones (however you actually want to output them). The only real logical connection between these 2 parts of code is the pitches array. That makes it easier to have more and different inputs (for example if you wanted to have a reset button, which sets all the pitches at onece to a predefined value). Also the function of the input code (which needs to very regularily check the buttons, to be responsive) is not disturbed by the output code.

Thank you so much for the support. I will change my code accordingly and will get back to you to show the results.

I am trying to compile your code but encountered a problem which I cannot resolve
for(int button=0;button < N_BUTTONS;button++){     if(digitalRead(button_pins[button])){         pitches[button] = analogRead(A0)/13;     } }
The above code gives me the following error:
"exit status 1
expected primary-expression before ';' token"
Any thoughts?

The bit of code, that you are showing, is ok. The error must lay in the rest of the code, most probably above

I cant seem to find where the error is. I have looked for the whole code, maybe I am missing something. Error code:
**Arduino: 1.8.10 (Windows 10), Board: "Arduino/Genuino Uno"
C:\Users\teclast\Documents\Arduino\Sequencer_Project_Version0.1\Sequencer_Project_Version0.1.ino: In function 'void loop()':
Sequencer_Project_Version0.1:105:36: error: expected primary-expression before ';' token
for (int button=0; button<N_BUTTONS; button++){
                                ^

exit status 1
expected primary-expression before ';' token**

I have been trying to get that bit of code to work and it doesn't let me use the code:
'for(int button=0;button < N_BUTTONS;button++){'
If I change N_BUTTONS to 8  the code gets accepted.
With this I can change the value of pitches[0] with the analog read and button[0], however I cannot change the value of pitches[1]  afterwards and so on.

Oh, f***, I forgot to set the define to 8, you are totally right. Of course it must be defined as 8. I changed the code in my answer, now it should work

Thank you. That fixed it. It is working now as expected.
Really glad I asked for help since I don't think I was getting there by myself.

So based on the information you provided I understand that the issue is that both the if(switch1state==HIGH) and the `if(switch2state==HIGH)' statements evaluate to true if either switch is flipped. That means one of the following things is happening:
1) Somewhere in your code you're mixing their values and assigning ones value to the other
2) Your configuration of the digitalRead pins is wrong (either wrong pins or wrong pupdr config as I've seen incorrect pull-up and pull-down resistors propagate unexpected behavior across the ground)
3) your wires are crossed. If you're using a breadboard make sure you know how it's connected internally. Some swap between horizontal and vertical rows.


text:
Why does my ATtiny85 blink program only work with 4 out of the 16 registers?
The following blink program runs fine on my Attiny85 SparkFun Tiny AVR programmer board. It produces 5 short blinks and then stops.
It also works fine when I change r16 to any one of the registers r17, r21 or r29. But trying with any other register gives either no blink at all (r19, r20, r23, r25, r26, r27, r28, r31) or indefinite blinks (r18, r22, r24, r30).
Can anyone explain?
int ledPin = 0;

void setup() {

  pinMode(ledPin, OUTPUT);

  asm("ldi r16, 5");
  asm("blink:");
  digitalWrite(ledPin, HIGH);
  delay(500);
  digitalWrite(ledPin, LOW);
  delay(500);
  asm("dec r16");
  asm("brge blink");
}

void loop() {
}

Why are you trying to mix assembly in there like that without first knowing what registers are already being used by the program for other purposes? Either use C or use assembly. Don't mix them like that.

I usually do not mix like this, but inserted the blink part for  a debugging reason. Why I use inline assembly is to speed up an inner loop.

As you discovered, calling a function may clobber some registers. To be precise, the avr-gcc documentation says:

Call-Used Registers
The call-used or call-clobbered general purpose registers (GPRs) are registers that might be destroyed (clobbered) by a function call.
R18–R27, R30, R31
These GPRs are call clobbered. An ordinary function may use them without restoring the contents. Interrupt service routines (ISRs) must save and restore each register they use.
Call-Saved Registers
R2–R17, R28, R29
The remaining GPRs are call-saved, i.e. a function that uses such a registers must restore its original content. This applies even if the register is used to pass a function argument.

Now, an interesting detail here is that according to the documentation, one would expect R28 to work. Maybe that's not clobbered by the called procedure, but by your local procedure (mixing assembly and C in nontrivial amounts is a difficult
task for precisely this reason).

Solved it myself! The high-level command "delay(500)" destroys the register contents. Saving the register (using push/pop) while doing delay() solves this issue. (Btw, is should be "brpl" and not "brge".)


text:
Calibrating Accelerometer Sensor
I'm working with an Adafruit LSM303DLHC Accelerometer Sensor hooked up to an Arduino.  I've downloaded the appropriate libraries to make it work and uploaded the example sketch "accelsensor.pde".  I then placed my sensor at rest on a flat surface and obtained the following acceleration vector values on average, in units of meters per second:
X: -0.24  Y: -0.71  Z: 10.47

At rest, each of these three values fluctuate approximately +-0.04 on average.
As I see it, the values are off a bit.  At rest, the X and Y components should hover closer to 0m/s^2 while the Z component should be closer to 9.8m/s^2.
What is the best way to compensate for this biased measurement?  Should I simply add back the average observed bias?  Or is there a more robust method to calibrate the sensor values?

To get rid of the fluctuation, you could always try a moving average. It isn't hard to modify the Smoothing example (under File->Examples->1. Analog->Smoothing) to accept accelerometer values.
As for the slight offset in the X & Y values, that is probably because your sensor isn't sitting perfectly flat.

Am i correct to assume that the z-axis should (ideally) give an acceleration value of approximately 9.8m/s^2? Or should it really read 0m/s^2 at rest?

@Paul - yes you are correct

there are varius calculation.
At the end of the day, if take a point in every position (under no acceleration), you should end up with a sphere, or matematically speacking, wthe lenght of the vector should be equal to gravity, so sqrt(x*x+y*y+z*z) = G or, to do less computing x*x+y*y+z*z = G*G (same apply for magnetometer, but using local magnetic force, or gyroscope, using a know-speed rotation like a LP player)
To create that spere you have to take many point, and find a multiplicator (or function) for each axes. That is particualary important when one axes has differnet precision of others, you are linearizing the axis output, and then normalizig its value relative to others axes.
Once you have corrected the vector lenght to have a spere, you should look at the offset of the sphere; if its center point is not on the origin point 0,0,0 then the differece between center and origin is the correction you talk about. This is offset correction.
Also many (well, all) sensor are affected on their temperature; many claim to be "thermocompensated", that means this difference is less evident due to some some sort of hardware and/or software filtering.

What do you mean by "take a point in every position"?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Switching a dual h bridge in parallel
I'm using a dual h bridge to control two dc motors on an inverted pendulum (cart-pole system).  At the moment, I have to send two different pulse width modulated signals to the two enable pins to control the two motor speeds and four digital write commands to control the directions.
Ideally, I want to switch the two motors simultaneously in the same direction and with the same speed.  So, I'd like to be able to control both motors' speeds with only one pulse width modulation signal and control both motor directions with only two digital write commands.
Is there a way I can do with with Arduino?  Can one PWM signal from a single arduino pin be sent to two enable pins at the same time? Can the same be done for a single digital output pin?  If so, how can I accomplish this?

How precisely do you need to match the speeds? A single PWM control will likely result in (slightly) miss-matched speeds.

You can connect a single output to as many input loads as you like, provided the current is sufficient to hold the output voltage within the input thresholds. See the datasheet for the H bridge to find out what the input load and thresholds are, and compare them with the output from the Arduino.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Serial communication between an Uno and an Esplora by connecting their usb ports together
I’m trying to send a character message from an arduino uno to an esplora by connecting their usb ports together.  The esplora has a micro usb port, while the uno uses a usb B port.  To hooked them up, I connected a micro usb to usb A cable to a usb A to usb B cable using a female to female usb A connector.  I even hooked up the uno and esplora grounds together.  But the two boards just don’t seem to communicate.  Ordinarily when hooking up the esplora to my computer, the tx light flashes whenever sending the message and the message appears as expected on the serial monitor.  I’ve also tested sending character messages from the computer to the uno and they seem to be read as expected.  But when connecting the esplora to the uno without going through the computer, those tx lights on the esplora do not seem light up at all and the uno rx lights don’t flash either.
Any idea what could be the issue here?

It will not work. USB communication is master/slave. There must be a 'host' and a 'device'. Uno and Esplora are two 'devices'.
Connect the boards over TTL Serial. Wire Rx and TX pins together, TX to RX and RX to TX. And ground of course.
Serial on Esplora is the USB interface. In 'core' I see the Esplora has a second serial interface called Serial1. According to schematics, the RX and TX pin of Serial1 on Esplora are on LCD header as DC_LCD (RX) and RESET_LCD (TX). Use this Serial1 to communicate with Uno.
On Uno side you should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.

Which pins on the esplora are the default tx & rx?

I edited the answer.

What do you mean by "In 'core' I see, it is Serial1"?  Could you explain what this means?

Arduino has core packages for different hardware architectures of MCUs and core packages have variants for boards. and boards have differrent software configurations matching the hardware

Juraj:  If i'm using serial communication a rate of 9600, does this mean that I need to use a Serial1.begin(9600) communication instead of the regular Serial.begin(9600) in the esplora code?

it is what I wrote in answer. use Serial1. Serial is USB

Thanks!  That may just solve my other question all together.

you asked about the core and didn't see the point of the sentence?

I wasn't quite sure that I understood it at first.  Thank you for explaining it.  I appreciate your help.


text:
variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type
I have a problem with lcd, I have  NUCLEO64 L746RG , I have Lcd Display and I2C connected to it.
When I verify code it gives me and long error and I can not find the solution or cause of this error:
In file included from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l4xx.h:149,
                 from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/stm32/stm32_def.h:48,
                 from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/stm32/clock.h:19,
                 from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/wiring_time.h:23,
                 from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/wiring.h:38,
                 from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/Arduino.h:36,
                 from C:\Users\User\AppData\Local\Temp\arduino-sketch-B028C48DF91C28F6EAA5B0CE34D27EE2\sketch\Displaylcd1.ino.cpp:1:
C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected identifier before '(' token
 1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
      |                             ^
c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
  169 | class LCD : public Print
      |       ^~~
C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
 1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
      |                              ~            ^
c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
  169 | class LCD : public Print
      |       ^~~
C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
 1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
      |                             ~             ^
c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
  169 | class LCD : public Print
      |       ^~~
C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected class-name before '(' token
 1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
      |                             ^
c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
   38 | class LiquidCrystal_I2C : public LCD
      |                                  ^~~
C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected '{' before '(' token
 1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
      |                             ^
c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
   38 | class LiquidCrystal_I2C : public LCD
      |                                  ^~~
C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
 1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
      |                              ~            ^
c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
   38 | class LiquidCrystal_I2C : public LCD
      |                                  ^~~
C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
 1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
      |                             ~             ^
c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
   38 | class LiquidCrystal_I2C : public LCD
      |                                  ^~~
C:\Users\User\Documents\Arduino\Displaylcd1\Displaylcd1.ino:2:22: error: variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type
    2 | LiquidCrystal_I2C lcd(0x27,16,2);  /*I2C scanned address defined + I2C screen size*/
      |                      ^
Multiple libraries were found for "LiquidCrystal_I2C.h"
  Used: C:\Users\User\Documents\Arduino\libraries\LiquidCrystal
  Not used: C:\Users\User\Documents\Arduino\libraries\LiquidCrystal_I2C
exit status 1

Compilation error: variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type

This is my code:
#include <LiquidCrystal_I2C.h>  /*include LCD I2C Library*/
LiquidCrystal_I2C lcd(0x27,16,2);  /*I2C scanned address defined + I2C screen size*/
void setup() {
  lcd.init();  /*LCD display initialized*/
  lcd.clear();     /*Clear LCD Display*/
  lcd.backlight();      /*Turn ON LCD Backlight*/
  lcd.setCursor(2,0);   /*Set cursor to Row 1*/
  lcd.print("I2C LCD Nano"); /*print text on LCD*/
  lcd.setCursor(2,1);   /*set cursor on row 2*/
  lcd.print("Linuxhint.com"); /*print message on LCD*/
}
void loop() {
}

I do not know why, I am not including anything else so why is it giving me this error?
PLEASE HELP, I AM WORKING ON IT for 8 hours AN I STILL COULD NOT FIGURE OUT WHAT IS THE PROBLEM, PLease help

WHY ARE YOU SHOUTING?

please format the error log same as code

Normally I wouldn't answer this, but the error is not exactly in your code but (seemingly at least) in two common things in the Arduino ecosystem.
Roughly speaking, the library you're trying to use is incompatible with the STM32 board support you're using.
The error message sort of tells this. It may help to read it backwards:
<sketchbook>\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
  169 | class LCD : public Print
      |       ^~~

So, it is in your installed LiquidCrystal library trying to process the definition of the LCD class, and having a problem with LCD, or rather in expansion of macro 'LCD'.  So, there's macro called LCD that it's trying to expand at that point, which should be a red flag.
The top part is where the compiler proper is having issues with the macro expansion where it causes a more fundamental error, error: expected identifier before '(' token  This is because it is trying to insert the macro definition directly into where it has found it resulting in this code effective after preprocessing:
class ((LCD_TypeDef *) LCD_BASE) : public Print

which is gibberish. It's pointing to the first open parenthesis there and saying expected identifier, the identifier being the class name it expected to see, not this cast and other stuff that follows. Whoever wrote your LiquidCrystal library did not expect LCD to already be defined as something via macro. This is one of a number of reasons why macros are hated.
The bulk of this is indicating the how the macro got to where it came from to where it wound up. The macro started in stm32l4xx.h in CMSIS and wound it's way into the LiquidCrystal header through Arduino.h and everything in between:
In file included from <Arduino15>\<STM32boardSupport>\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l4xx.h:149,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/stm32/stm32_def.h:48,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/stm32/clock.h:19,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/wiring_time.h:23,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/wiring.h:38,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/Arduino.h:36,
                 from <Temp>\arduino-sketch-B028C48DF91C28F6EAA5B0CE34D27EE2\sketch\Displaylcd1.ino.cpp:1:

To oversimply a bit CMSIS is the semi-standard header files that ARM chip makers are supposed to provide that among other things define hardware registers. Although I haven't investigated it, it seems likely that whatever chip you're using has a built in LCD driver, and so there are things, macros namely, that have "LCD" in the name. Unfortunately for you, one just called LCD.
You could try renaming all of the uses all of the uses of LCD within the LiquidCrystal library that you have to some other name. Or you could try inserting #undef LCD after the include of Arduino.h in the LCD.h header in an attempt to undefined the macro so that the LCD in the class definition is not expanded. But, I would be looking for different versions of the library and making sure the library is even the one you think it is, because everyone and their dog seems to have made some library called LiquidCrystal at some point or another. It would be a pity if you went through all trouble to find out you weren't even looking at the right library.


text:
Trying to use an Arduino Uno to control two slaves with one master but its not working
I am trying to use following code but its not working. Need a help in this regard.
#include <SimpleModbusMaster.h>
#define baudrate 115200
#define timeout 2000
#define polling 500
#define retry_count 5
#define Txenablepins 2
#define Led1 12
#define totalregs 9
enum{
  PACKET1,
  PACKET2,
  TOTAL_NO_OF_PACKETS
};
Packet packets[TOTAL_NO_OF_PACKETS];
packetPointer packet1 = &packets[PACKET1];
packetPointer packet2 = &packets[PACKET2];

unsigned int regs[9];
unsigned int write_regs[1];

void setup() {

    packet1->id = 1;
    packet1->function = PRESET_MULTIPLE_REGISTERS;
    packet1->address = 0;
    packet1->no_of_registers = 1;
    packet1->register_array = write_regs;

    packet2->id = 1;
    packet2->function = READ_HOLDING_REGISTERS;
    packet2->address = 0;
    packet2->no_of_registers = 1;
    packet2->register_array = regs;

modbus_configure(baudrate, timeout, polling, retry_count, Txenablepins, packets, TOTAL_NO_OF_PACKETS);
pinMode(Led1, OUTPUT);

}

void loop() {

unsigned int connection_status1 = modbus_update(&packets[PACKET1]);
unsigned int connection_status2 = modbus_update(&packets[PACKET2]);
if(connection_status1==1 and connection_status2==1){
digitalWrite(Led1, HIGH);
}
else{
digitalWrite(Led1, LOW);}
checkResponse();

}

This is my arduino slave code
#include <SimpleModbusSlave.h>

#define  ledPin  11

enum {
    ADC0,
    ADC1,
    ADC2,
    ADC3,
    ADC4,
    ADC5,
    LED_STATE,
    BUTTON_STATE,
    TOTAL_ERRORS,
    TOTAL_REGS_SIZE
};

unsigned int holdingRegs[TOTAL_REGS_SIZE];

void setup() {
 // put your setup code here, to run once:
   modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE, 0);

   pinMode(ledPin, OUTPUT);
   Serial.flush();
}

void loop() {
  // put your main code here, to run repeatedly:

  holdingRegs[TOTAL_ERRORS] = modbus_update(holdingRegs);

  int val = analogRead(ADC0);

  holdingRegs[0] = val;

  delayMicroseconds(50);

if(holdingRegs[0] == 1){
  digitalWrite(ledPin, HIGH);
}
else{
  digitalWrite(ledPin, LOW);
}

}

Using this library for modbus master and slave

what does not working mean? ... what actually happens? ... please update your post with a clear description

add some debugging code ... right now, you have no way of knowing what the programs are doing

"control two slaves with one master but its not working" You were able to get it to control one?

The library you are using uses Serial port for modbus communication, that means that you can't open the Serial Monitor and the only way to know whether it is working or not is by observing the LED. You should either take a look at the library SoftwareSerail examples or find a better Modbus library.