body:
I am trying to connect a DPS310 and an ADXL345 to my Arduino using 4 wire SPI. When the individually tested (i.e. each has its own script), the output is correct, however when the scripts are combined the ADXL output is garbage, but the DPS functions.

What we expect to see:
```
Temperature = 24.14 *C
Pressure = 857.88 hPa
X: -4  Y: 4  Z: 29
```
What we actually see:
```
Temperature = 24.14 *C
Pressure = 857.88 hPa
X: 0  Y: 0  Z: 0    // and does not change when tilted
```
When the DPS310 line is commented out, the ADXL works fine (this line is indicated in script)

The whole script (with the faulty line indicated):
```
#include <SparkFun_ADXL345.h>
#include <Adafruit_DPS310.h>

// ADXL obj
#define ADXL345_CS   9 // SPI pin
ADXL345 ADXL = ADXL345_CS; // Instantiate obj with CS pin
int x = 0, y = 0, z = 0;

// DPS obj
#define DPS310_CS   10 // SPI pin
Adafruit_DPS310 dps; // Instantiate obj (pin is set in setup)
sensors_event_t temp_event, pressure_event;

void setup() {
   Serial.begin(115200);
   while (!Serial) delay(10);

   // ADXL SETUP
   digitalWrite(ADXL345_CS, LOW); // START COMM
   Serial.print("ADXL345: ");
   ADXL.powerOn();
   delay(50);
   ADXL.setRangeSetting(16);
   ADXL.setSpiBit(0);
   ADXL.set_bw(ADXL345_BW_12_5);
   ADXL.setInterrupt(0x84, true);
   ADXL.setAxisOffset(0, 0, 5);
   ADXL.readAccel(&x, &y, &z);
   if(x != -1 && y != -1 && z != -1) {
     Serial.println("[PASSED]");
   } else {
     Serial.println("[FAILED]");
   }
   digitalWrite(ADXL345_CS, HIGH); // END COMM

   // DPS SETUP
   digitalWrite(DPS310_CS, LOW); // START COMM
   Serial.print("DPS310: ");
   if (! dps.begin_SPI(DPS310_CS)) { /////////////////PROBLEM LIES HERE//////////////////
      Serial.println(" [FAILED]");
   }
   Serial.println(" [PASSED]");

   dps.configurePressure(DPS310_64HZ, DPS310_64SAMPLES);
   dps.configureTemperature(DPS310_64HZ, DPS310_64SAMPLES);
   digitalWrite(DPS310_CS, HIGH); // END COMM
}

void loop() {
    digitalWrite(ADXL345_CS, LOW);
    ADXL.readAccel(&x, &y, &z);
    digitalWrite(ADXL345_CS, HIGH);

    digitalWrite(DPS310_CS, LOW);
    dps.getEvents(&temp_event, &pressure_event);
    digitalWrite(DPS310_CS, HIGH);

    Serial.print("Temperature = ");
    Serial.print(temp_event.temperature);
    Serial.println(" *C");
    Serial.print("Pressure = ");
    Serial.print(pressure_event.pressure);
    Serial.println(" hPa");

    Serial.print("X: ");
    Serial.print(x);
    Serial.print("  Y: ");
    Serial.print(y);
    Serial.print("  Z: ");
    Serial.println(z);

    delay(50);
}
```
I think the fault might lie in the classes written for these devices, for instance maybe they were written for single SPI device or have different frequencies/modes? (I'm probably wrong though XD). I have not yet tried to setup the SPI for each device manually (programming commandment: do no reinvent the wheel), so any help would be greatly appreciated.

title: My two slave SPI setup on arduino not working correctly

Answers: 1

body:
The ADXL345 uses SPI_MODE3 and DPS310 the SPI_MODE0. The libraries for these devices don't use [SPI transactions][1], but set the settings only in begin(), so they can't be used together.

Your options to solve this is either to put one sensor on software SPI or to put one or both sensors on I2C.

The ADXL345 can be used as I2C device. Its library supports I2C with the constructor when no parameters are provided. Does your module have an option to wire it to I2C?

The Adafruit library for DPS310 has built-in software SPI, so you can use it with any set of pins. And it too supports I2C.

  [1]: https://www.arduino.cc/en/Reference/SPIbeginTransaction


body:
first-time builder here.  I just got my Arduino Nano Every in the mail from Mouser, and I'm trying to upload a modified version of the blink example to my new brand-new board.  However, every time I try to upload a sketch, the IDE just spins its wheels for around 5 minutes before giving up.  I've been trying to look through similar questions and haven't found anything that has solved my issue.  My OS is Windows 10.

Here's a snippet of the log (I've turned on verbose reporting for compilation and upload):

    Arduino: 1.8.13 (Windows 10), Board: "Arduino Nano Every, None (ATMEGA4809)"
    …
    Forcing reset using 1200bps open/close on port COM1
    …
             Using Port                    : COM1
             Using Programmer              : jtag2updi
             Overriding Baud Rate          : 115200
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    An error occurred while uploading the sketch

Here are the settings I'm currently using:

 - Board is set to Arduino Nano Every, using Arduino MegaAVR Boards
   1.8.6
 - Registers emulation:  none (ATMEGA4809)
 - Port:  COM1 (there are no other options that appear for me, and no
   other port pops up in the device manager when I plug the board in)
 - Programmer:  Onboard Atmel    mEDBG (UNO WiFi Rev2)

Here's what I've tried so far:

 - Disabled antivirus
 - Uninstalled and reinstalled Arduino IDE
 - Turning on registers emulation
 - Restarting computer
 - Resetting board
 - Using different USB cables
 - Using different USB ports (3.0 and 2.0)
 - Manually installing Arduino drivers to Windows (Windows said the most
   up-to-date drivers were already installed after I specified the
   directory to search in)
 - Nothing is connected to the board.
 - The pin-13 LED blinks, so there's a bootloader on the board.
 - I've reset the board before uploading.

Any help would be very much appreciated.  I'm about to give up and just return the board and swap it for a different one.

title: Can't Upload Sketches to Arduino Nano Every

Answers: 2

body: Here is a trick I use on some boards but first be the baud rate is the same in the terminal as in the sketch (Serial.begin(115200). If so then remove everything then put a jumper between ground and reset. Then put a jumper between TX and RX (pin o and pin 1 on uno). launch the IDE and what you type in the console should be echoed back to you. If this works the hardware is connected fine.

body:
I was getting the same error when I got my brand new Nano Every.

I had Registers emulation: ATMEGA328

I changed it to None (ATMEGA4809) and it uploaded without problems.

I'm on ubuntu 18.04, and this is after the IDE prompted me to install the megaAVR boards library (1.8.7) of course.


body:
I have a simple setup with arduino Nano as slave and a arduino Mega as master
Can anyone explain how the function 15
FORCE_MULTIPLE_COILS
Works

i have been running some test on this
and cant figure out how to use the
local_start_address

is this the data to read from
or
is it a pointer to another File

modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 1021);

dec 8 = (no_of_registers = packet->data)  // number of coils

so frame 6 = 1 (frame[6] = no_of_bytes;) // number of bytes more

dec 1021 = (packet->local_start_address)
the dec 1021 and 65565 seams to work ????
but makes no sense to me in binary format ?

Here is
part of CPP file:

    enter code here

    unsigned char construct_F15()
    {
       // function 15 coil information is packed LSB first until the first 16 bits are completed
      // It is received the same way..
      unsigned char no_of_registers = packet->data / 16;
      unsigned char no_of_bytes = no_of_registers * 2;

      // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad
      if (packet->data % 16 > 0)
      {
        no_of_registers++;
        no_of_bytes++;
      }

      frame[6] = no_of_bytes;
      unsigned char bytes_processed = 0;
      unsigned char index = 7; // user data starts at index 7
       unsigned int temp;

      for (unsigned char i = 0; i < no_of_registers; i++)
      {
        temp = register_array[packet->local_start_address + i]; // get the data

    frame[index] = temp & 0xFF;

        bytes_processed++;

        if (bytes_processed < no_of_bytes)
        {
          frame[index + 1] = temp >> 8;
          bytes_processed++;
          index += 2;
        }
      }
       unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes
       return frameSize;
    }

title: Simple ModBus Master function 15

Answers: 1

body:
i found it

it is the

 temp = register_array[packet->local_start_address + i]; // get the data
 in the ccp file

register_array[packet->local_start_address + i]

its pointing to the wrong location... register_array??

supersized no one has noticed this as long as the simple modbus master for adruino
has been used ?

or i have a bad CPP file ?

i have temp corrected this by replacing with

    unsigned char construct_F15()
    {
        // function 15 coil information is packed LSB first until the first 8 bits are completed
        unsigned char frameSize = 10;
        unsigned char temp;
        frame[6] = 1;
        frame[7] = packet->local_start_address ^ 0XFFFF;
        return frameSize;
    }

works (0 = off / 255 = on)

modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 0); // 1 thru 8 = off

modbus_construct(&packets[PACKET2], 1, 15, 1, 8, 255); // 1 thru 8 = on


body:
I'm working in SIM800 for DTMF based project.

I want to know which kind of data are stored in the buffer during termination of call in SIM800.

How to find if call was disconnected in SIM800?

Also please suggest some AT-COMMAND tester software and DTMF codes for my reference.

title: which kind of data are store If i terminate the call in sim800?

Answers: 0


body:
I want my Arduino Nano to consume as little power as possible, so I have been lowering the clock frequency with `CLKPR` from the default 16 MhZ speed. I successfully ran the program at 8 Mhz by setting `CLKPR=0x01`, but am unable to see any output in the serial monitor or any sign of the program running successfully at 4 Mhz (`CLKPR=0x02`). My project involves transmitting data between Arduino and an Android via Bluetooth, and I can see the receive LED blink on the Nano at 4 Mhz. However, for some reason it does not step through the code, and Serial monitor wont print statements. My Nano is a cheap knockoff so it's possible the chip is not designed to run at 4 Mhz. I've also tried the same test on a knockoff Uno and got the same results. Please let me know if you have any suggestions. I've included the code I'm trying to run:

    int state = 0;
    int stateData = 0;
    int ultraPin = 10;
    int trigPin = 11;    // Trigger
    int echoPin = 12;    // Echo
    long duration, cm;
    unsigned char inches;
    unsigned long timer;

    void setup() {
      CLKPR = 0x80;
      CLKPR = 0x02; // 4 Mhz
      pinMode(ultraPin, OUTPUT);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      digitalWrite(ultraPin, LOW);
      Serial.begin(9600*4); // multiply baud rate by inverse of clock frequency factor
    }

    void loop() {
      if(Serial.available() > 0){ // Checks whether data is comming from the serial port
        stateData = Serial.read();
        if (stateData == 48){ // ON signal from phone
          Serial.write(50); // confirm signal received
          timer = millis();
          digitalWrite(ultraPin, HIGH);
          while (true){
              digitalWrite(trigPin, LOW);
              delayMicroseconds(2/4);
              digitalWrite(trigPin, HIGH);
              delayMicroseconds(10/4);
              digitalWrite(trigPin, LOW);
              pinMode(echoPin, INPUT);
              duration = pulseIn(echoPin, HIGH);
              cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
              inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
              Serial.write(inches);
              delay(50/4);
              stateData = Serial.read();
              if (stateData != 49){
                // receipt from android
                unsigned long timeElapse = millis() - timer;
                if (timeElapse > 5000/4) {
                  break;
                }
              }
              else {
                  // reset the timer
                  timer = millis();
                }
          }
        }
     }
     delay(200/4);
    }

title: Arduino Wont Run Program at 4 Mhz

Answers: 0


body: I'm writing the code for my Arduino board using Code::Blocks editor. When I create a new project, there is **AVR Project** and **Arduino Project** under Projects category. Which one do I select?

title: Arduino + Codeblocks C++

Answers: 1

body: You can select, what you want. If you want to build an Arduino Project, you should choose "Arduino Project". If you don't want to use the Arduino Framework, you can choose "AVR Project".


body:
I am new to the Arduino world and I hope I can find a solution here. The code below functionally works ok. The problem I have is, at line 45 I've inserted an `if` statement to change `dac_value`. It is very slow while serial and all that is outside `if` works fast/fine... What would be a solution to make it fast? Tried `if` - `else if` and also `while`... result is the same. Hope someone can help. Thank you.

    {
    #include <Arduino.h>
    #include <Wire.h>
    // #include <LiquidCrystal_I2C.h>
    #define MCP4725 0x61
    #define MCP4725B 0x60
    unsigned int val;
    byte buffer[3];
    byte buff[3];

    int ClockPinV = PB1;
    int ClockPinA = PA6;
    const int currsensPin = PA3;
    const int voltsensPin = PA2;

    void setup()
    {
      Serial.begin(115200);
      pinMode(currsensPin , INPUT_ANALOG);
      pinMode(voltsensPin , INPUT_ANALOG);
      pinMode(ClockPinV , INPUT);
      pinMode(ClockPinA , INPUT);
      Wire.begin();
    }

    int val0 = 1024;
    int val1 = 4096;
    volatile int dac_value = 0;

    void loop()
    {
      analogReadResolution(12);

      volatile int svolt = analogRead(ClockPinV);
      volatile int scurr = analogRead(ClockPinA);
      volatile int set_voltage = (3.3/4096)*svolt;
      volatile int set_curr =  (3.3/4096)*scurr;
      volatile int securr = analogRead(currsensPin);
      volatile int real_curr = (3.3/4096)*securr;
      volatile int sevolt= analogRead(voltsensPin);
      volatile int real_output2 = (3.3/4096)*sevolt;

    if(real_curr < set_curr){
        if(set_voltage > real_output2)
        {
          dac_value = dac_value + 1;
        }
        if(set_voltage < real_output2)
        {
          dac_value = dac_value - 1;
        }
      }
      else if(real_curr > set_curr)
      {
        dac_value --;
      }

      dac_value = constrain(dac_value, 0, 2673);
      buffer[0] = 0b01000000; //control byte
      buffer[1] = dac_value >> 4; //MSB 11-4 shift right 4 places
      buffer[2] = dac_value << 4; //LSB 3-0 shift left 4 places

      Wire.beginTransmission(MCP4725); //address device
      Wire.write(buffer[0]); //pointer
      Wire.write(buffer[1]); //8 MSB
      Wire.write(buffer[2]); //4 LSB
      Wire.endTransmission();

      // val1 = constrain(val1, 0, 2673);
      buff[0] = 0b01000000; //control byte
      buff[1] = svolt >> 4; //MSB 11-4 shift right 4 places
      buff[2] = svolt << 4; //LSB 3-0 shift left 4 places

      Wire.beginTransmission(MCP4725B); //address device
      Wire.write(buff[0]); //pointer
      Wire.write(buff[1]); //8 MSB
      Wire.write(buff[2]); //4 LSB
      Wire.endTransmission();

      Serial.println("=============================");
      Serial.println("=============================");
      Serial.println("========= Volt Test =========");
      Serial.println("test: " + String(set_voltage));
      Serial.println("      " + String(real_output2));
      Serial.println("======== Current Test =======");
      Serial.println("test: " + String(set_curr));
      Serial.println("      " + String(real_curr));
      Serial.println("=============================");
      Serial.println("=============================");
    }
    }

title: why is "if" slow?

Answers: 1

body:
The `if` statements (plural) you [posted on GitHub][1] are a lot different to the one you posted above. They contain a lot of of `print` commands to the LCD, so I think this is what is slowing your code down. It's a fair effort at nicely formatting the output on the display, but is rather convoluted.

Here is a simplified version which writes to the LCD as little as possible (2 cursor moves and 2 prints). The formatting of the string is done in Arduino memory before sending it out to the LCD as one complete string.

I couldn't understand your variable names, so I've renamed them.

setup()
=======
I moved the `analogReadResolution(12)` from `loop()` to `setup()` for a slight performance gain.
```c++
void setup()
{
  pinMode(currsensPin , INPUT_ANALOG);
  pinMode(voltsensPin , INPUT_ANALOG);
  pinMode(voltPin, INPUT_ANALOG);
  pinMode(currPin, INPUT_ANALOG);
  Wire.begin();
  lcd0.begin(20, 4);
  lcd0.backlight();

  analogReadResolution(12);  // Moved from loop(). Only need to call it once.

  Serial.begin(115200);
}
```
loop()
======
I've grouped the analogue reads together to give a smaller sampling window. Since it's for a control loop, these values should ideally be sampled at exactly the same time and synchronised to a clock (e.g. in hardware).
```c++
float real_current_offset = 0;

void loop()
{
  //
  // Obtain data samples as close together as possible with no interrupts.
  //
  cli();  // Disable interrupts.
  int svolt = analogRead(voltPin);
  int scurr = analogRead(currPin);
  int raw_voltage = analogRead(voltsensPin);
  int raw_current = analogRead(currsensPin);
  sei();  // Enable interrupts.

  // Calculate set voltage and current.
  float set_voltage = (3.3 / 4096) * svolt;
  float set_current =  (3.3 / 4096) * scurr;

  // Calculate real voltage and current.
  float real_voltage = (3.3 / 4096) * raw_voltage;
  float real_current = raw_current * (3.3 / 4096) - real_current_offset;
  float real_current_ma = real_current * 1000.0;

  int dac_value = dac_value
              + (real_current <= set_current) * (set_voltage > real_voltage)
              - (real_current < set_current) * (set_voltage < real_voltage)
              - (real_current > set_current);

  buffer[0] = 0b01000000;
  buffer[1] = dac_value >> 4;
  buffer[2] = dac_value << 4;
  Wire.beginTransmission(MCP4725);
  Wire.write(buffer[0]);
  Wire.write(buffer[1]);
  Wire.write(buffer[2]);
  Wire.endTransmission();

  DisplayDataOnLcd(set_voltage, set_current, real_voltage, real_current);
}
```
DisplayDataOnLcd()
==================
I created a new function for displaying the data on the LCD. It's good practice to break the code down into smaller functional blocks.
```c++
void DisplayDataOnLcd(const int set_voltage, const int set_current, const int real_voltage, const int real_current)
{
  Serial.println("\nLCD Data Display");

  // Define the formats for printing to the LCD.
  const char *data_format_set  = "Set : %s V %s mA";
  const char *data_format_real = "Real: %s V %s mA";
  char voltage_str[10];
  char current_str[10];
  char data_str[30];

  // Format the set voltage and current, and display on the LCD.
  dtostrf(set_voltage, 6, 3, voltage_str);
  dtostrf(set_current, 6, 3, current_str);
  sprintf(data_str, data_format_set, voltage_str, current_str);
  lcd0.setCursor(0, 0);
  lcd0.println(data_str);
  Serial.println(data_str);

  // Format the real voltage and current, and display on the LCD.
  dtostrf(real_voltage, 6, 3, voltage_str);
  dtostrf(real_current, 6, 3, current_str);
  sprintf(data_str, data_format_real, voltage_str, current_str);
  lcd0.setCursor(0, 1);
  lcd0.println(data_str);
  Serial.println(data_str);
}
```

  [1]: https://github.com/mariusdp/psu_test/blob/master/main.cpp


body:
I have a rotary encoder and 2 buttons to a. Store the encoder value b. Reset the encoder value to 0. The reset buttons work fine the issue is with the set/store button. Where the value changes without pressing the button as well. Any help is appreciated.

    int encoderPin1 = 2;
    int encoderPin2 = 3;

    volatile int lastEncoded = 0;
    volatile double encoderValue = 0;
    long lastencoderValue = 0;

    int lastMSB = 0;
    int lastLSB = 0;

    // buttons
    int resetPin = 43;
    int settPin = 22;
    int val = 0;
    int val2 = 0;

    //reset-set
    double setValue = 0.0;
    double resetValue = 0.0;

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

      pinMode(encoderPin1, INPUT);
      pinMode(encoderPin2, INPUT);

      digitalWrite(encoderPin1, HIGH);
      digitalWrite(encoderPin2, HIGH);

      attachInterrupt(0, updateEncoder, CHANGE);
      attachInterrupt(1, updateEncoder, CHANGE);

      //buttons
      pinMode(resetPin, INPUT);
      pinMode(settPin, INPUT);

      pinMode(LED_BUILTIN, OUTPUT);

    }
    void loop(){
      //Serial.println(encoderValue); //print
      delay(1000);

      //
    val = digitalRead(settPin);
    if (val == HIGH){
      set();
      digitalWrite(LED_BUILTIN, HIGH);
    }

    /*val2 = digitalRead(resetPin);
    if (val2 == HIGH){
      //reset
      encoderValue = resetValue;
      Serial.println(encoderValue);
      Serial.print("reset");
      delay(100);
    }*/

    }

    void set(){
      //set the value
      setValue = encoderValue;
      Serial.println(setValue);
      Serial.print("setValue");
      delay(100);
    }

     void updateEncoder(){
      int MSB = digitalRead(encoderPin1);
      int LSB = digitalRead(encoderPin2);

      int encoded = (MSB << 1) |LSB;
      int sum = (lastEncoded << 2) | encoded;

      if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
      if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

      lastEncoded = encoded;
      }

title: Saving a value with a click

Answers: 1

body: thank you for your suggestion. The issue isn't with the code but was with the button. I changed the button and it worked fine. Thanks for the help!


body:
I am trying to make a SAME51 variant of an arduino board, in the end I would like to have an arduino compatible board, BSP, and library for controlling canbus.

I have already gone through some things, but I believe I need a slight bit of guidance for the next step, mostly just reference files.

What I have done so far is fork the adafruit SAMD BSP and added a variant. Since the normal Bossa does not recognize my CPU ID I had to add it and recompile bossa. I also went ahead and made a UF2 style bootloader and a corresponding windows driver with matching PIDs/VIDs. At this point I had a working arduino board, but it still thinks it's a SAMD51, not a SAME51. Asking for anything to do with can leads to missing references, which makes sense since SAMD does not have CAN (but it's in DFPs?)

So finally I decided to edit boards.txt again and change the build flag from -D__SAMD51G19A to SAME51G19A. I also found SAME51 DFP online and added them to arduino/tools/CMSIS-Atmel, but this is just me guessing. I also used the DFP to build the UF2 bootloader previously. This breaks everything and if I had to guess from looking the compiler is missing the DFP and everything is very upset about that.

Earlier I had found a version of what I am after, except for a SAMC21 and not a SAME51. I thought the can peripheral was the same for each, so this should be an easy port besides maybe configuring the gclk since those are different from M0 to M4. If you compare DFPs, both are identical as far as CANBUS is concerned, at least at that level.

But, using this code and the SAMC21 BSP referenced in the readme will compile!

https://github.com/hugllc/samc21_can

Is it something to do with adafruit fork using CMSIS 5.4 and arduino using CMSIS-Atmel 1.2.0?

Thank you in advance for any and all tips!

title: Adafruit/Arduino SAMD BSP package and adding SAME51 compatibilty

Answers: 0


body:
i am trying to connect several arduinos to usb ports and have the abillity to define between them.

i added Firmata.attach function on the arduino board. how do i call it from my python script?
thank you

    #define BOARD_NAME '1'
    void readName() {
          Firmata.sendString(BOARD_NAME);
        }

    void setup()
    {
      Firmata.attach(READ_NAME, readName);
      Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);

      Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
      Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
      Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
      Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
      Firmata.attach(SET_PIN_MODE, setPinModeCallback);
      Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback);
      Firmata.attach(START_SYSEX, sysexCallback);
      Firmata.attach(SYSTEM_RESET, systemResetCallback);

      // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega,
      // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this:
      // Serial1.begin(57600);
      // Firmata.begin(Serial1);
      // However do not do this if you are using SERIAL_MESSAGE

      Firmata.begin(57600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101
      }

      systemResetCallback();  // reset to default config
    }

title: Connect and detect multiple arduinos using firmata

Answers: 0


body:
Running a DC motor(6.5A max input), motor driver (MD10C 7Amp peak output), and arduino Mega.
Basically, I am creating a stabilized object based on the accelerometer's input. It works great but all of a sudden, very randomly, it glitches and gets stuck in whatever mode it was in last, so if it was motor A HIGH and motor B LOW at speed 200, itll just do that and I have to unplug it, put in a blank code, then my code again, then start it, itll work great then do it all over again. The time it takes for it to glitch out is random, I can't seem to find any patterns to it.
here is my code

```
//Code for accelerometer controlling an encoded DC
#include <Encoder.h>
#include <Wire.h>
#include <MPU6050.h>
#include <QueueArray.h>

//Class to read the encoder
Encoder myEnc(19,18);

//I2C address of the MPU-6050
const int MPU_addr=0x68;

const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 200 Hz              = 1250
const uint16_t t1_comp = 1250;

// Buffered data for sending/receiving to/from the ISR
volatile bool isr_flag = false;  //Used to flag when the ISR when triggered
volatile unsigned long isr_time = 0;  //Input updated by ISR
volatile byte isr_motor_direction; //Output calculated and updated in loop()
volatile byte isr_motor_speed = 0; // Output calculated and updated in loop()

//initializing the MPU6050 (accel/gyro input)
MPU6050 sensor;

//accerleromter in the y direction
int16_t AcY;
//not using
int16_t AcX, AcZ, GyX, GyY, GyZ, Tmp;

//new varible for mapping the accelerometer to degrees
int yAng;

//Variables to create PID method
int currentTheta;
float error;
int dt = 5;
long integral=0;
long deriv;
int previousError;

//accel on light, always want it at 0
int setpoint = 0;

//change speeds of the motor
#define MOTOR_SPEED_PIN    3
//change direction of the motor
#define MOTOR_DIRECTION_PIN   2
#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //Disable global interrupt
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);

  Serial.begin(9600);

  pinMode(MOTOR_SPEED_PIN, OUTPUT);
  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);

  sensor.initialize();
}

void loop()
{
    //Begin critical section
    //

    cli();
    bool flag = isr_flag; //Copy the ISR flag
    isr_flag = false; //Reset the ISR flag
    sei();

    //
    //End critical section

    if (flag == true)
    {
      DebugMsgTime("PID algorithm begin");

      //Begin critical section
      //

      //Getting a copy of the data that has been modified by the ISR
      cli();
      unsigned long time = isr_time;
      sei();

      //
      //End critical section

      static unsigned long previous_time = 0;
      previous_time = time;

      //Wire reading

      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);

      //reading each of the 6 axis's of the MPU6050 and the temp
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      //Only using AcY
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();

      //mapping AcY to yAng from accel units to degrees
      yAng = map(AcY, -17000, 17000, -90, 90);

      //Calculate motor parameters locally
      long pos = PID(yAng);
      byte motor_direction = pos > 0 ? MOTOR_DIRECTION_CW : MOTOR_DIRECTION_CCW //make sure that this is correct
      pos = abs(pos);
      pos = constrain(pos, 0, 100);
      byte motor_speed = map(pos, 0, 100, 0, 200);

      //Begin Critical Section
      //

      // Update the ISR data ready for output at the next interrupt.
      // This keeps the outputs locked to each other and synchronised to the interrupt.
      cli();
      isr_motor_direction = motor_direction;
      isr_motor_speed = motor_speed;
      sei();

      //
      //End Critical Section

      DebugMsgTime("PID algorithm end");
    }
}

ISR(TIMER1_COMPA_vect)
{
  //Output
  digitalWrite(MOTOR_DIRECTION_PIN, isr_motor_direction);
  analogWrite(MOTOR_SPEED_PIN, isr_motor_speed);

  //Input
  isr_time = micros();
  isr_flag = true;
}

//PID loop to find error between setpoint and currentTheta
long PID(int currentTheta)
{
    error = setpoint - currentTheta;
    integral = integral + error*dt;
    deriv = (error-previousError)/dt;
    long output = 1.9 * error; + .8 * integral + 40 * deriv; //2.8,.7,70 //1.3,.8,40
    previousError = error;
    return output;
}

void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = micros();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}
```

title: My motor driver gets stuck in either high or low with a certain speed super randomly. Motor output stops going based on accelerometer input

Answers: 1

body:
What happens if the `while` condition fails? i.e. if `millis() - time` is greater than or equal to 20. Is this what you intended? If there's too much other stuff in the `while` loop, it may quit it **and never re-enter it**.

loop()
======
I've added a call to a function that prints debug information.
```c++
unsigned long time = 0;

void loop()
{
  DebugMsgTime("loop() begin");

  while (millis() - time < 20)
  {
    DebugMsgTime("while begin");

    time = millis();

    //delay(10);  // Short delay OK.
    delay(20);  // Long delay causes while loop to quit.

    DebugMsgTime("while end");
  }
  DebugMsgTime("loop() end");
}
```

DebugMsgTime()
==============
This function prints a message along with the current time and the delta time since it was last called.
```c++
void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = millis();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}
```

Debug Output
============

> It works great but all of a sudden, very randomly, it glitches and
> gets stuck in whatever mode it was in last

```none
Basic Encoder Test:
loop() begin
0
0
while begin  // It works great...
1
1
while end
2
1
while begin
12
10
while end
34
22           // but all of a sudden, very randomly, it glitches...
loop() end   // and gets stuck in whatever mode it was in last
54
20
loop() begin
74
20
loop() end
97
23
loop() begin
118
21
loop() end
```
As you can see, using this `while` loop is a very inaccurate way to generate regular sampling times.

loop() FIX
==========
As @FerryBig pointed out in the comments, you need to change the time comparison `<` at the start of the loop. You also don't need the `while` loop because `loop()` is already called cyclically. Instead, put the time comparison in an `if` statement, something like this which gives you a rough 20 ms:

```c++
void loop()
{
  static unsigned long previous_time = 0;
  unsigned long time = millis();
  unsigned long delta_time = time - previous_time;

  if (delta_time >= 20)
  {
    previous_time = time;

    // Do PID algorithm.
  }
}
```
However, for a PID controller you may need more accuracy.

Timer Interrupt
===============
A better method would be to use a timer interrupt to call an Interrupt Service Routine (ISR) at regular intervals. This ISR would do two simple things in this order:

 1. Output: `digitalWrite(motor_direction);` and `analogWrite(3, mtr2);`
 2. Input: set a flag that indicates that the gyro Wire needs reading.

Then, when the flag is set, the main `loop()` would read the gyro Wire, and calculate `motor_direction` and `mtr2` in readiness for the next interrupt.

```c++
const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 10 Hz              = 25000
const uint16_t t1_comp = 25000;

volatile bool isr_flag = false;       // Used to flag when the ISR has updated the data.
volatile unsigned long isr_time = 0;  // The data.

void setup()
{
  // Disable global interrupt
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Serial.begin(9600);
}

void loop()
{
  //
  // BEGIN CRITICAL SECTION (Atomic)
  //

  cli();
  bool flag = isr_flag;  // Copy the ISR flag.
  isr_flag = false;      // Reset the ISR flag.
  sei();

  //
  // END CRITICAL SECTION
  //

  Serial.println(flag);

  if (flag == true)
  {
    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Get a copy of the data that has been modified by the ISR.
    cli();
    unsigned long time = isr_time;
    sei();

    //
    // END CRITICAL SECTION
    //

    static unsigned long previous_time = 0;
    Serial.println(time - previous_time);
    previous_time = time;
  }

  delay(25);
}

ISR(TIMER1_COMPA_vect)
{
  //TCNT1 = t1_load;  // No need to reload here because it auto reloads.
  isr_time = micros();
  isr_flag = true;  // Indicate that new data is available.
}
```

PID Controller
==============
This is the full implementation of the PID controller. It should give you a solid foundation to develop the PID algorithm for your motor, and to filter the gyro inputs.
```c++
//Code for accelerometer controlling an encoded DC
#include <Encoder.h>
#include <Wire.h>
#include <MPU6050.h>
#include <QueueArray.h>

//Class to read the encoder
Encoder myEnc(19, 18);

//I2C address of the MPU-6050 idk if i need
const int MPU_addr = 0x68;

const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 10 Hz              = 25000
//const uint16_t t1_comp = 25000;

// If the PID algorithm takes less than 5 ms, it's possible to run Timer1 at a maximum of about 200 Hz.
// 16 MHz          / 64        / 200 Hz             = 1250
const uint16_t t1_comp = 1250;

// Buffered data for sending/receiving to/from the ISR.
volatile bool          isr_flag = false;            // Used to flag when the ISR has triggered.
volatile unsigned long isr_time = 0;                // Input updated by ISR.
volatile byte          isr_motor_direction = LOW;   // Output calculated and updated in loop().
volatile byte          isr_motor_speed = 0;         // Output calculated and updated in loop().

//initializing the MPU6050 (accel/gyro input)
MPU6050 sensor;

//accerleromter in the y direction
int16_t AcY;
//not using
int16_t AcX, AcZ, GyX, GyY, GyZ, Tmp;

//new varible for mapping the accelerometer to degrees
int yAng;

//Variables to create PID method
int currentTheta;
float error;
int dt = 5;
long integral = 0;
long deriv;
int previousError;

//accel on light, always want it at 0
int setpoint = 0;

//this is the enable pin (PWM) to run speeds to the motor
#define MOTOR_SPEED_PIN         3

//change direction of the motor
// TODO: Check whether LOW and HIGH are correct.
#define MOTOR_DIRECTION_PIN     2
#define MOTOR_DIRECTION_CW      LOW
#define MOTOR_DIRECTION_CCW     HIGH

void setup()
{
  // Disable global interrupt.
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);

  Serial.begin(9600);
  Serial.println("Basic Encoder Test:");

  //pinMode(MOTOR_SPEED_PIN, OUTPUT);  // Not needed for analogWrite().
  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);

  sensor.initialize();
}

void loop()
{
  //
  // BEGIN CRITICAL SECTION (Atomic)
  //

  cli();
  bool flag = isr_flag;  // Copy the ISR flag.
  isr_flag = false;      // Reset the ISR flag.
  sei();

  //
  // END CRITICAL SECTION
  //

  //Serial.println(flag);

  if (flag == true)
  {
    DebugMsgTime("PID algorithm begin");

    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Get a copy of the data that has been modified by the ISR.
    cli();
    unsigned long time = isr_time;
    sei();

    //
    // END CRITICAL SECTION
    //

    static unsigned long previous_time = 0;
    //Serial.println(time);
    //Serial.println(time - previous_time);
    previous_time = time;

    //
    // Read gyro Wire.
    //

    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true);

    //reading each of the 6 axis's of the MPU6050 and the temp
    AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    //Only using AcY
    AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read();

    //mapping AcY to yAng from accel units to degrees
    yAng = map(AcY, -17000, 17000, -90, 90);

    //
    // Calculate motor parameters locally.
    //

    long pos = PID(yAng);
    byte motor_direction = pos > 0 ? MOTOR_DIRECTION_CW : MOTOR_DIRECTION_CCW;  // TODO: Check whether defines are correct.
    pos = abs(pos);
    pos = constrain(pos, 0, 100);
    byte motor_speed = map(pos, 0, 100, 0, 200);

    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Update the ISR data ready for output at the next interrupt.
    // This keeps the outputs locked to each other and synchronised to the interrupt.
    cli();
    isr_motor_direction = motor_direction;
    isr_motor_speed = motor_speed;
    sei();

    //
    // END CRITICAL SECTION
    //

    DebugMsgTime("PID algorithm end");
  }

  //delay(1);
}

ISR(TIMER1_COMPA_vect)
{
  // Output.
  digitalWrite(MOTOR_DIRECTION_PIN, isr_motor_direction);
  analogWrite(MOTOR_SPEED_PIN, isr_motor_speed);

  // Input.
  isr_time = micros();
  isr_flag = true;
}

//PID loop to find error between setpoint and currentTheta
long PID(int currentTheta)
{
  error = setpoint - currentTheta;
  integral = integral + error * dt;
  deriv = (error - previousError) / dt;
  long output = 1.9 * error + .8 * integral + 40 * deriv; //2.8,.7,70 //1.3,.8,40
  previousError = error;
  return output;
}

void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = micros();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}
```
And I think there might be a typo in your PID controller:
```c++
long PID(int currentTheta)
{
    ...
    long output = 1.9*error; + .8*integral + 40*deriv;
                           |
                         typo?
```
This is equivalent to:
```c++
    long output = 1.9*error;
```
Which is not a PID controller.


body:
So I am trying to take GPS data with a Neo 6M gpsmodule (that is what is covered up by the square for privacy sake) and process it by adding/multiplying to get large integers representing the GPS data. This is using Arduino nano. When I try and convert the float numbers to integers, it gives me totally different numbers. 1242895 turns into -2289, and 611194 turns into 21370. I have tried so many things, but am stumped as to what is going on. Is it related to pointing? It's been awhile since I learned about pointers in my C++ class. X and Y are initialized as int global variables.

[![float to int issue][1]][1]

  [1]: https://i.stack.imgur.com/7ecjz.png

title: Converting from Float to Int yielding weird results. What am I doing wrong?

Answers: 1

body:
On an Arduino board with the 328 processor, an INT is stored as a 2 byte value, so the max number is 32,767.

You want to use a LONG which is a 4 byte number which has a max of 2,147,483,647.

When the variable you are using is not big enough, the number rolls over, which is why you end up getting a negative number.


body: I am making an arduino project with a single lithium ion battery, and want to be able to maintain a constant PWM voltage, even when the battery goes from 4.2-3.2v. I have been able to read the Vcc using the internal 1.1v reference, so I am wondering if I can make some sort of feedback system to increase the duty cycle when the battery discharges, in order to keep the same average voltage on the PWM. I want to be able to make it 3.2v constant, which should be attainable on Vcc from 4.2-3.2, with 100% duty cycle when the battery is at 3.2v.

title: Maintain constant PWM voltage with changing Vcc

Answers: 1

body:
Simple:
```duty =  (3.2 / vcc) * 255;```


body:
I have bought a Digispark ATtiny85 board to learn about that microcontroller. So I tried using internal register names in the code rather than using Arduino in built functions. I can get the board to work when comes just input and output operations. For example the below code works and I can get the on board LED to turn ON and OFF

    #include<avr/io.h>
    void setup()
    {
      DDRB |=(1 << PB1);  //set PB1 as output
    }
    void loop() {
     PORTB |= (1 << PB1);    // Turning ON LED connected to PB1
     delay(1000);            //Using Arduino IDE inbuilt delay function to generate delay of 1 second
     PORTB &= ~(1 << PB1);   //Turning the LED off
     delay(1000);
}

I have tried using Timer0 of ATtiny85 module to generate time delay of one second. But unfortunately I couldn't get it to work.

    #include<avr/io.h>
    #define F_CPU 16500000UL
    #include<util/delay.h>

    void timer_config()
    {
     DDRB =0b00000010; // set PB1 as output
     GTCCR|= (1<<TSM);      ///Halt the timer for configuration
     TCCR0A=0x00;             //Normal mode
     TCCR0B=0x00;
     TCCR0B |= (1<<CS00)|(1<<CS02);   //prescaling with 1024
     TCNT0=0;
     GTCCR&=~(1<<TSM); //Start the timer
    }

    void tmdel()
    {
     int i=0;
     while(i<=6)
     {
      while((TIFR & (1 << TOV0) )==0);        //Waiting for 0-255 and flag to raise
      TIFR|=(1<<TOV0);      //Clear the flag
      i=i++;                          //increment by one
     }
    }

    int main()
    {
     timer_config();
     while(1)
     {
      PORTB|=(1<<PB1);     //PortB1 high
      tmdel();                         //Delay of 1 second
      PORTB&=~(1<<PB1);     //PORTB1 low
      tmdel();
     }
    }

I have used the overflow flag to identify TCNT0 register status. I have uploaded the above code but the LED isn't responding as anticipated.

When searching the internet I have got few suggestions that this might be because Arduino IDE uses timer registers for delay function. When user attempts to access timer registers it might not work as intended.

But am not sure about the validity of above opinion. Can anyone help me with it? Since am learning this controller, practicing core programming is quite important. If I cannot program ATtiny85 using Arduino IDE this way, can someone suggest a way or alternate hardware setup to program ATtiny85 and access its registers without a problem.

title: Problem with programming digispark ATtiny85 board with Arduino IDE

Answers: 1

body:
>      i=i++;                          //increment by one

The result of the above statement is **not defined**. That is, it is not necessarily "i + 1".

See:

* http://en.wikipedia.org/wiki/Sequence_point
* http://c-faq.com/expr/seqpoints.html

Instead use:

    i++;

Or:

    i = i + 1;

A note about "undefined behavior":

http://en.wikipedia.org/wiki/Undefined_behavior

> When an instance of undefined behavior occurs, so far as the language specification is concerned anything could happen, maybe nothing at all.


body:
Good Morning
I'm trying to integrate with Azure IoT with Arduino Mega 2560.
I imported the AzureIoTHub and AzureIoTUtility lib.

I just created this part of the code

     #include <AzureIoTHub.h>

    void setup() {
      // put your setup code here, to run once:

    }

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

    }

however, when I compile, I get the following error message.

> In file included from
> C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/azure_c_shared_utility/platform.h:7:0,
>                  from C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/AzureIoTUtility.h:7,
>                  from C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTHub\src/AzureIoTHub.h:7,
>                  from D:\Documents\Dev\Pocos\Arduino\ArduinoSolution\ArduinoSolution.ino\WiFiPoco\RoboCore\azureHub\azureHub.ino:3:
> C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/azure_c_shared_utility/strings.h:8:10:
> fatal error: cstddef: No such file or directory  #include <cstddef>

I imported ArduinoStl and the problem continued.

what am i doing wrong in this case?

thanks

title: Error "cstddef: No such file or directory" on use AzureIoTHub

Answers: 1

body:
Azure IoT is only supported on ESP8266 and ESP32. As stated in the [README](https://github.com/Azure/azure-iot-arduino/blob/master/README.md) for the library:

> Currently supported hardware:
>
> - ESP8266 based boards with [esp8266/arduino](https://github.com/esp8266/arduino)
>
>   - SparkFun [Thing](https://www.sparkfun.com/products/13711)
>
>   - Adafruit [Feather Huzzah](https://www.adafruit.com/products/2821)
>
> - ESP32 based boards with [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
>
>   - Adafruit [HUZZAH32](https://www.adafruit.com/product/3405)


body:
I want my HC05 Bluetooth Module to trigger an interrupt when it receives a signal. So I've followed suggestions from the Arduino Forum and connected the Bluetooth TXD pin to the Arduino RX Pin and the Interrupt Pin (2), which I set to high. It is set to detect a `FALLING` voltage, presumably when BT transfers data. When I connected it this way a funny thing happens. I can clearly see that the interrupt is being called because power consumptions goes way up when Android sends a message to BT module, meaning the device wakes up. However the serial port no longer appears to work on the Nano. I think I narrowed down the possible cause to me damaging the board by removing lineage regulator or damaging serial port somehow with the interrupt. Is the way I wired up the interrupt pin as described correct? Your help would really help me narrow down my problem.

    #include <avr/sleep.h>

    #define ledPin 7
    #define intPin 3
    int state = 0;
    int stateData = 0;
    int ultraPin = 10;
    int trigPin = 11;    // Trigger
    int echoPin = 12;    // Echo
    long duration, cm;
    unsigned char inches;
    unsigned long timer;

    void setup() {
      pinMode(ultraPin, OUTPUT);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(intPin, INPUT);
      digitalWrite(intPin, HIGH);
      attachInterrupt(digitalPinToInterrupt(intPin), interrupt, FALLING);
      digitalWrite(ultraPin, LOW);
      Serial.begin(9600); // Default communication rate of the Bluetooth module
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      sleep_cpu();
    }

    void interrupt(){
      Serial.println("interrupted");
      sleep_disable();
      Serial.write(50);
      delay(500);
      timer = millis();
      digitalWrite(ultraPin, HIGH);
      while (true){
          digitalWrite(trigPin, LOW);
          delayMicroseconds(2);
          digitalWrite(trigPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(trigPin, LOW);
          pinMode(echoPin, INPUT);
          duration = pulseIn(echoPin, HIGH);
          cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
          inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
          Serial.write(inches);
          delay(50);
          stateData = Serial.read();
          if (stateData != 49){
            // receipt from android
            unsigned long timeElapse = millis() - timer;
            if (timeElapse > 5000) {
              break; // exit and SLEEP
            }
          }
          else {
              // reset the timer
              timer = millis();
            }
          }
        sleep_enable();
        sleep_cpu();
    }

    void loop() {

    }

title: Will Setting Interrupt Pin High Damage Bluetooth Module?

Answers: 1

body:
I'm not sure, if you can rule out the hardware damage (you wrote, that you removed the linear voltage regulator, but didn't explain more there). But with that code you won't get what you want.

I see multiple issues, all boiling down to the same problem: You cannot do that inside of an ISR:

- `delay()` relies on interrupts to happen during its execution. As of my knowledge this leads to `delay()` never ending, blocking your code. Also it is very bad design to have a long running ISR. So much is depending on interrupts to work and when you have something long running, you can just easily do that inside the main code, triggered by an interrupt flag variable.
- `millis()` will not increment during the run of the ISR.
- `delayMicroseconds()` will work, but you still should keep the ISR very short. Reading an ultrasonic sensor is a no-go.
- `Serial.write()` will fill the libraries internal TX buffer, but the actual transmission of the data also relies on interrupts. You won't get your data that way.

Instead of doing all that inside the ISR, you should just let the Arduino wake up, then set a (single byte) flag variable. In your main code you need to check for that flag with an if statement. In that if statement, you are doing all what you need to do and at the end you are resetting the flag and going to sleep again.


body:
I would like to read the output of an on-off-on switch with my Leonardo board, but I have very little knowledge of electronics and don't know how to wire it up.

This is the switch in question: [E-Switch 200MSP4T1B1M1QE][1]

The switch has three pins. Generic three-pin SPDT wiring diagrams I've found suggest that the two outer pins should be connected to separate lights and the middle pin should be connected to the power source. Those lights also have a ground connection.

I don't want to power anything in a literal sense, I only want to have the Leonardo read the output of the switch. The end goal is to have the two ON positions read as separate button presses (eventually using a joystick library, in case that changes how the switch needs to be wired).

My questions are:
1. Is the above wiring example correct for my use case?
2. Is the output of the switch considered digital or analog?
3. Is a wire from the switch to GND not required?

One final note - I'm not using a breadboard, but connecting the wires directly from the switch to the board.

  [1]: https://www.digikey.ca/en/products/detail/e-switch/200MSP4T1B1M1QE/3777910

title: How to wire a three-pin on-off-on switch for reading input?

Answers: 3

body:
You talk about wiring a switch to control lights directly. Instead, you want to use your switch to send information to your Arduino.

You link to an SPDT (single pole, double throw) switch. When flipped one way, it connects the center pin to one of the outside pins, and when flipped the other way, it connects the center pin to the other outside pin.

If you want the Leonardo to read the state of the switch as 2 separate switches/button presses, wire the 2 outer pins of the switch to 2 separate digital inputs on the Arduino.

You need to force each input to either ground or +5V when it's not connected to anything, or it will "float" and you'll get semi-random high and low readings.

I suggest setting the Arduino input pins to INPUT_PULLUP mode. That connects the inputs internally through a resistor to +5V. If you don't connect anything to the pin, it reads as HIGH. When the button is pressed/switch is closed, it reads LOW. That might seem a little confusing, but it means you don't need external resistors.

You'd then attach those to pins to the two outer pins of your switch, and attach the center pin to ground (GND).

If you flip the switch one way, it would connect one outer pin to the center pin. That would connect that Arduino pin to ground, and the reading on the pin would drop from HIGH to LOW. Flip the switch the other way and it would connect the other pin to ground, at that other pin would drop from HIGH to LOW.

It is also possible to wire your switches using INPUT mode, not INPUT_PULLUP, and have them read LOW when the switch is open, and HIGH when closed, but to do that you'll need external pull-down resistors. (And wiring it will be a little painful without a breadboard or PC board.)

To answer your questions:

1. Is the above wiring example correct for my use case?

You don't show a wiring example. You talk about how to wire a switch to switch power to a pair of lights directly, without using a microcontroller. That's not relevant here.

2. Is the output of the switch considered digital or analog?

It would make sense to use it as a digital input, since you need it to give you 2 states, open and closed.

3. Is a wire from the switch to GND not required?

You need to connect the center pin to either ground +5V, as discussed above.

body:
I suggest this simple circuit:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/qzj4K.png)

<!-- End schematic -->

Set both inputs to `INPUT_PULLUP`. If the input reads `LOW`, that means it has been grounded by the switch.

---

**Edit**: Per Duncan’s request, here is the alternative circuit with the polarities inverted. With the switch’s common connected to Vcc, the inputs should be set to `INPUT_PULLDOWN`. However, most Arduinos do not support this mode, for lack of internal pull-downs. Then one has to use external pull-downs instead, and set the pins to `INPUT`.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/nMBOZ.png)

<!-- End schematic -->

With this circuit, a pin reads `HIGH` when it is connected to +5V by the switch.

body:
# Alternative Circuit

For the on-off-on switch, the MSP-3 and MSP-4 operate as follows:

[![Operation of MSP-3 and MSP-4 switches][1]][1]

*Figure 1 – Operation of MSP-3 and MSP-4 switches.*

| POS | Connection | MSP-3 | MSP-4 |
|:---:|:---:|:---:|:---:|
| 1 | Terminal 2 to Terminal 3   | ON | (ON) |
| 2 | Terminal 2 to open circuit  | OFF | OFF  |
| 3 | Terminal 2 to Terminal 1   | ON | (ON) |

Here is an alternative way to connect the SPDT to the MCU which is useful when running out of pins because it only requires one input pin. It does however require more complicated software to interpret the input e.g., hysteresis and debounce could be implemented with thresholds such as:

 - > 90% Vcc for > 50 ms means high.
 - < 10% Vcc for > 50 ms means low.
 - > 45% Vcc and < 55% Vcc for > 50 ms means OFF.
 - anywhere in between means no change.

[![Connecting SPDT switch to MCU][3]][3]

*Figure 2 – Connecting SPDT switch to MCU.*

# Throw vs Stop vs Contact

In normal parlance, a throw describes a physical action that moves a mechanism to a new mechanical stop; and throws are distinct from stops and contacts. As such, a switch is a transducer that converts physical movements (throws) to an electrical signal via a system of mechanical stops and electrical contacts.

From Figure 1, the totals are 2 throws, 3 positions, 2 contacts and 1 pole.

However, matters have been confused by a minority of people erroneously metamorphosing the term “[throw][4]” to mean “mechanical [stop][5]” or “electrical [contact][6].”  As you can see in this example—as is often the case—the number of throws equals the number of contacts, but that is not *always* the case. For example, if there were a centre contact for the centre stop, there would be three contacts, but still only two throws. Perhaps the fact that throws and contacts are often equal in number has led some people to conflate and confuse the separate entities. And perhaps that the number of stops can sometimes equal the number of contacts has led some people to conflate and confuse them too. For this kind of switch, the number of throws is always one less than the number of stops.

Matters are not helped by the [E-Switch 200MSP4T1B1M1QE datasheet][7] showing an incorrect schematic for the MSP-3, 4 and 5 that omits the centre mechanical stop that should be labelled OFF.

I’ve re-annotated the datasheet, Figure 3, and modified the following prose to comply with the common-sense approach of Figure 1, being mindful that a minority of people use “throw” to mean “contact,” and added the correct schematic for MSP-3, 4 and 5. (The original annotated version and prose was an attempt to use the datasheet’s own erroneous nomenclature and schematic.)

[![Annotated datasheet v2][8]][8]

*Figure 3 – Annotated datasheet.*

MSP-1, 2 and 6 are actually single-throw switches despite what the datasheet implies which conflates its description of its SPST with its SPDT switches (which caused some confusion in the comments about the intent and variety of the switch).

The switch required for the above example is the MSP-3 on-off-on. Or to simulate momentary button presses, the MSP-4 (on)-off-(on). Both of these are single-pole double-throw switches (SPDT), not because they have 2 electrical contacts, but because they have 2 physical throws.

In the context of the erroneous datasheet, throws and contacts are erroneously synonymous. In normal parlance, neither throws nor positions are electrical contacts/terminals/pins (though the datasheet has conflated them as well). However, each mechanical stop does have an associated electrical connection/disconnection that should be explained in the datasheet. Unfortunately, in this case, the table in the datasheet has conflated SPST with SPDT and used the term “NONE” to indicate that a position doesn’t exist for the SPST types (MSP-1, MSP-2, and MSP-6). For MSP-3, 4, and 5, notice how POS 2 doesn’t have an associated contact/terminal/pin in the green schematic, Figure 3.

From experience, the only way to be sure is to buzz out the switch with a multimeter (continuity test). So, keep Figure 1 in your mind and a multimeter in your hand, and you won’t go far wrong.

# Conclusions

 1. Throws are physical.
 2. Stops are mechanical.
 3. Contacts are electrical.
 4. Claims such as, “My contact is a throw.” are delusional.
 5. Conclusions can be lyrical.

# Phantom Scroll-By Downvoter

This answer has a attracted a phantom downvote with no comment expressing why this is warranted.

Does the phantom think:
 1. the alternative circuit is wrong?
 2. the thresholds are wrong?
 3. the errant use of the English language and dodgy schematics in the datasheet are acceptable?

Bear in mind that the terms “throw,” “stop,” and “contact” (their meanings and usage) are taught by schoolteachers to millions of school children every year; and used by billions of English speakers every day. Is the global education system (which isn’t perfect) wrong on this particular point? On what grounds and exceptional circumstances is a datasheet allowed to use such terms in an inappropriate manner?

 [1]: https://i.stack.imgur.com/2xflQ.png
 [2]: https://i.stack.imgur.com/bz6nx.png
 [3]: https://i.stack.imgur.com/3vbZQ.png
 [4]: https://www.google.com/search?q=throw english meaning
 [5]: https://www.google.com/search?q=stop english meaning
 [6]: https://www.google.com/search?q=contact english meaning
 [7]: https://sten-eswitch-13110800-production.s3.amazonaws.com/system/asset/product_line/data_sheet/131/200.pdf
 [8]: https://i.stack.imgur.com/PCyl9.png


body:
I am trying to connect my wireless playstation 2 remote up to my arduino but I am facing one problem. Whenever I restart my program (by clicking the red button) the PS2 remote's dongle blinks at the exact same times as the blink light on the arduino blinks. But as soon as the arduino's light stops blinking, the RX light on the PS2 dongle (which was blinking), stops blinking. I saw a guide out there on potential ways of fixing this and one type of way of fixing it according to the documentation for the PS2 libary (which no longer exists on a website) was by doing some type of pull-up resistor (I am not 100% too sure what this is). I have checked the wiring and its fine. This was the website that I followed that shows the step by step instructions on how to program the controller with the arduino and how to wire it: https://create.arduino.cc/projecthub/electropeak/how-to-interface-ps2-wireless-controller-w-arduino-a0a813. Here is the schematic that I followed for the concept with the pull-up resistor:
 [![enter image description here][1]][1]

I have just tried removing the clock pin from pin 13 (which is already connected up to the clock pin of the PS2 controller).This got rid of the blinking of the dongle blinking directly at the same time as the arduino when restarting the program. The reason why I did this was because it seemed to get rid of the RX blinking issue. Here is a few images that might solve the confusion with the problem.[![enter image description here][2]][2]

[![enter image description here][3]][3]
[![enter image description here][4]][4]

This is how my dongle is wired up to my arduino :

[![enter image description here][5]][5]

This is the PS2 dongle. The RX light is what keeps blinking synchronous to the arduino pin 13 light (This is the light that blinks each time you re-compile or restart the program).

[![enter image description here][6]][6]

This is the LED that I am referring to when I mention the LED on pin 13 of the arduino.

So when pin 13 on the arduino is blinking the RX light on the PS2 dongle is blinking synchronous to it.

The reason that I removed the clock pin from pin 13 on the arduino was because I knew that the pin 13's blinking LED connects up to pin 13 itself (which is wired up to the clock pin on the arduino), this did nothing.

What I am trying to aim to get is that the PS2 dongle

[![enter image description here][7]][7]

  [1]: https://i.stack.imgur.com/wQV8a.png
  [2]: https://i.stack.imgur.com/JPT2b.jpg
  [3]: https://i.stack.imgur.com/1RvQK.png
  [4]: https://i.stack.imgur.com/Ua05j.png
  [5]: https://i.stack.imgur.com/JC9X3.jpg
  [6]: https://i.stack.imgur.com/JhagN.jpg
  [7]: https://i.stack.imgur.com/FAqT1.jpg

Is for it to be like this and for it to just stay on and NOT blink :

One final thing I forget to mention was that when the LED finished blinking (when restarting). the RX LED on the dongle went off.

title: Wireless playstation 2 remote not connecting up to arduino

Answers: 0


body:
I'm trying to log reconnections and disconnections of a network. For that I've created 2 `time_t` arrays to store such occurances:

    const int logSize = 10;
    time_t conLog[logSize];
    time_t disconLog[logSize];

Now, down the road, I have some manipulation and time calculation to do, and for that I wish to pass those log as a variable.

For example - zeroing its values:

    void initLog(time_t log[], time_t init_val = 0)
    {
            int sizeLog = sizeof(log) / sizeof(log[0]);
            Serial.print("size: ");
            Serial.println(sizeLog);
            for (int i = 0; i < sizeLog; i++)
            {
                    log[i] = init_val;
            }
    }

in order using it in a simple way : `initLog(conLog);`
But unfortunately this is wrong.

I've tried to replace `time_t log[]` with `time_t &log` - but still no luck.

What do I do wrong ?

title: Passing a time_t array as a function parameter

Answers: 1

body:
When you pass an array to a function it "collapses" the array into just a pointer. All the receiving function knows is the type of the contents of the array (`time_t`) and where it starts in memory - it knows nothing about the size of the array.

The `sizeof()` call just gives you the size of that pointer, not the size of the memory it points to.

`sizeof()` is not actually a function, it's a compile-time construct. It can't know anything about runtime values, only what is there at compile time.

Instead you must pass the length of the array with the array as a separate parameter, which can only be calculated in the same scope as where the array is defined, and then only by using the original name of the array.  It is typical to create a macro to do this for you at the time you make the array:

```
time_t conLog[logSize];
#define CONLOG_SIZE (sizeof(conLog) / sizeof(conLog[0]))
```

Then pass that to your function:

```
initLog(conLog, CONLOG_SIZE);
```

Alternatively, since you already have the size in a constant in this case, you could just use that:

```
initLog(conLog, logSize);
```


body:
I'm having issues with a DS3231 RTC connected to an ESP8266. I can write to it to set the time (`Wire.write` returns 1), but anytime I try to read from it, `Wire.requestFrom` always returns 0.
I've tested my circuit with another DS3231 and it works correctly. So I guess it's faulty hardware and I can throw it to the bin. Or is there something I can do with it?

Update:
In fact, `endTransmission` returns 2, which if I understand well means the address is not found, so this is not a read issue. I guess that means it's dead.

title: Cannot read from DS3231

Answers: 0


body:
I am attempting to play a wav file from an SD card using a Teensy 3.5. I am using [this buzzer][1] and I have the following code currently:

    #include <Audio.h>
    #include <Wire.h>
    #include <SPI.h>
    #include <SD.h>
    #include <SerialFlash.h>

    // GUItool: begin automatically generated code
    AudioPlaySdWav           playSdWav1;     //xy=557,157
    AudioOutputPWM           pwm1;           //xy=889,184
    AudioConnection          patchCord1(playSdWav1, 0, pwm1, 0);
    AudioConnection          patchCord2(playSdWav1, 1, pwm1, 0);
    // GUItool: end automatically generated code

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(4800);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println("Play");
      playSdWav1.play("sound.wav");
      delay(100);
      while (playSdWav1.isPlaying()) {
        delay (100);
      }
    }

I don't know which pin is supposed to be outputting the PWM signal. I tried searching "patchCord1" to see what the parameters for it are, but was unsuccessful. The code was generated by [The Audio System Design Tool.][2]

As for the hardware configuration, I am attempting to wire the `I/O` pin to various PWM pins (to check for output) with no success. I have `GND` to Analog Ground and `VCC` to 3.3V (250 mA max). This is according to [this diagram][3].

Which PIN is the Teensy supposed to output the pulses to?

Edit:

I can get the buzzer to work by using manual PWM (analogWrite), so I know that it functions.

  [1]: https://www.amazon.com/gp/product/B085XQM69Z/
  [2]: https://www.pjrc.com/teensy/gui/index.html
  [3]: https://cdn-shop.adafruit.com/970x728/3267-04.jpg

title: Wave file will not play with Teensy 3.5

Answers: 1

body:
The documentation implies you have to combine pins 3 and 4.

Here is a circuit diagram:

https://www.pjrc.com/teensy/gui/img/pwmdualcircuit.jpg

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/41zMc.jpg

Source:

https://www.pjrc.com/teensy/gui/?info=AudioOutputPWM


body:
I'm connecting an LED strip that takes 12V input to an `Arduino Uno R3`'s `5V` VCC using a `B547` transistor.

Here's my circuit:

    Base -> 1K ohm resistor -> DO13
    Collector -> -ve of LED strip
    Emitter -> GND
    VCC 5V -> +ve of LED strip
Nothing happens when I try to turn on the LED strip. However if I remove the 1K resistor and turn on the LED, Arduino's built in LED gets dimmer but the LED strip does not turn on.

What am I doing wrong?

TIA!

title: BJT - BC547 not working with LED strip

Answers: 1

body:
Ok. First off, if you have a 12V LED strip then you have to power it from 12V. Powering the Arduino from 12V and then powering the LED strip from the 5V pin of the Arduino is *not* powering the LED strip from 12V, it's powering the Arduino from 12V and the LED strip from 5V.

The LED strip's anode (+) must be connected to the + of the 12V supply or, if it's only a very short LED strip then you can use VIN on the Arduino.

LED strips typically have a number of LEDs (eg 3) in series with a resistor to make one "segment", and many "segments" in parallel. This gives a total forward voltage of typically 9V or more - so you must provide *at least* that to get the LEDs to light.

Secondly the BC547 is not a good transistor to use for switching an LED strip.  It has a maximum continuous collector current of 100mA. That means that you can only have a maximum of 100mA going through your LED strip before the transistor blows.

For reference, 100mA is the equivalent of 5 "normal" (5mm, of the kind you'd use in a breadboard) LEDs at full current and brightness. A typical LED strip (depending on length) can use many hundreds or thousands of mA.

Really you should be using an N-channel MOSFET that is rated for *at least* as much current as your LED strip requires to run. For safety, and to reduce heat dissipation, you ideally want it to be many times more powerful than the LED strip needs.

A common choice is the IRF530, which is rated at 10A with a switching voltage (the "threshold" voltage) that is low enough for a 5V Arduino to control (there are more suitable ones, but these seem to be the "go-to" component for many Arduino users - they're adequate for most uses).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/hSkWC.png)

<!-- End schematic -->


body: I am using a 10 IR sensor array and they use analog pins. I am using a motor shield for the Uno. So I cannot use the Mega. I have only five analog pins I need 8. How can I do it?

title: How to turn the digital pin to analog pin?

Answers: 1

body: You can use an external A/D converter, there are a lot of varieties in a lot of price ranges for the Arduino. Check your favorite online source. That will require two of your existing analog pins for the I2C interface but you will gain back many more depending on your choice. If you choose to use SPI that will take 4 pins.


body:
I am just trying to set up the U8g2 library to use an OLED. I read through the documentation and tried copying and pasting the code block example for the constructor, but switched out their information for my OLED's information. After trying to verify, the IDE returned this error:
exit status 1
expected ')' before ',' token
```#include <Arduino.h>
#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C(U8G2_R0,A5,A4);```

I saw a similar post about this problem from four years ago, but the only suggestion on there was to capitalize the "A" in the analog pins. I tried this and nothing changed. Any help would be much appreciated!

title: I am getting an error while trying to set up the U8g2 library

Answers: 1

body:
I figured out what I was doing wrong. I was copying the name from the Constructor Reference and immediately inputting the arguments in parentheses. I needed to put u8g2 after the constructor name and then put the arguments. Thanks!

The corrected code is as follows:
```
#include <Arduino.h>
#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0,A5,A4);
```


body:
dear member.
I have 4 ESP-12 averything OK but one chip behave weird.
always return 1024 on analogRead(A0);
once use ADC_MODE(ADC_VCC) and reflash using ADC_MODE(ADC_TOUT); and never back to normal, is my Chip Error..?

FM 4MB

ArduinoIDE 1.8.13

BR 115200

PS 80MHz

    int iVal = 0;
    void setup() {
      Serial.begin(115200);
      delay(999);
      pinMode(A0,INPUT) ;
      pinMode(LED_BUILTIN, OUTPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      iVal=analogRead(A0);
      Serial.println(iVal);

      if (iVal > 900) digitalWrite(LED_BUILTIN,HIGH);
      else   digitalWrite(LED_BUILTIN,LOW);
      delay(720);
    }

title: 8266 analogRead(A0) always 1024

Answers: 1

body: First be sure your voltage on the analog input is less then 1V and greater then zero, that is the range for the input. If nothing connected no guarantee what you will get. Just guessing, no circuit or definition.


body:
I am currently trying to power my esp8266 with a battery, but I want to decrease the power consumption (current mostly). I understand there are different sleep modes, but I do not understand what can I use for each sleep mode. I want to know what functions are still enabled during each sleep mode.

Example: Can I use ADC pins in modem sleep?

My biggest question:
I am sending beacon frames to my phone, I want to know if I can use one of these sleep modes while sending my beacons at the same time? Do I need my CPU or do I need my Clock to send frames?

title: How are the different sleep modes used for esp8266?

Answers: 0


body:
I will be brief. There is as windows PC running a program. This program has live updating data on it. Without modifying the PC or adding any programs to the PC, is it possible to program an Arduino to read specific data from this program. In other words the Arduino would be connected to the PC via a USB port and it would need to actively read specific data from this program without having to modify the PC in any way, software or otherwise. I do have access to the PC and can learn almost anything I need to about the program during the development of this system, however in practice, I need the Arduino to simply be plugged into this PC and begin reading its data. Is this possible?  I am not asking for a tutorial however if you could point me in the right direction that would be great.
Thanks

title: Make the Arduino read data from the PC

Answers: 1

body:
As the comments already stated: No, not possible. For multiple reasons:

- USB is a master/slave protocol. The slave (here the Arduino) cannot do anything without the master. It can just expose it's data endpoints and hold data ready to read at these endpoints for the master or wait for data from the master on these endpoints. When the application on the PC is not programmed to speak over USB, you cannot get the data over USB.

- Even directly on the PC you cannot simply extract data from a different program. That would be a very huge security risk. Even more, when just initiated via an USB device. There are USB devices, which use certain behaviors of some OS's (like auto execution of specific types) to install a virus on the PC. But even then you cannot "just read" the data. It would be way more elaborate and not possible with a simple Arduino, thus off topic here. (And you might frown upon hacking your own PC this way)

From our point of view (means leaving the hacking off limits), I would aggree with Majenko in the comments. Using the visual output is the most viable and easy solution, though your results might vary.

For that you would need a camera pointing at the screen (check if you get a good image. It might be distorted due to slow refreshing...) and use a Raspberry Pi or similar to connect it. On the Pi you can then take pictures of the screen and use an OCR tool, which will read the text from the image. Then you need to extract and structure the relevant information. (Maybe it will be easier to create subimages in your program and let the OCR tool run over these to distiguish between the different data parts). Results will hardly depend on the quality of the image. If you can live with an additional program running the PC, you could instead make the images of the screen as screenshots, which will be way better quality. Though at that point you can also put the rest of the logic on the PC and just remove the Pi.

This way will still be hard to do for a beginner, but possible.


body:
I am building a timing system that has a start, split and finish beams with this I am using a start gate that will drop when the race starts. when it drops it will trip the 1st sensor starting to count the millis which I am using to calculate the time. I am using IR sensors to that give me the 3 times based on the millis and then I do a calculation in excel that will give me the split and finish time.

Where I am running into issues is that after the person goes through the 3 timer sensors I have to close the start gate which trips the first sensor which messes up my times for the next person.

So I need to adjust my sketch so it takes this into consideration when it starts counting the millis. Basically I am thinking it needs a line of code to have the 1st sensor == LOW once and do nothing and then on the 2nd time that same sensor is == LOW it records the millis from that point.

Below is the sketch I am working on.

    //timer
    unsigned long start, reaction, push, elapsed;

    void setup()
    {
      Serial.begin(115200);
      pinMode(2, INPUT); // start switch
      pinMode(3, INPUT); // split sensor
      pinMode(4, INPUT); // finish sensor
    }

    void loop(){

    if (digitalRead(2) == LOW)
      {

        start = millis();

      }

      if (digitalRead(3) == HIGH)
      {

        reaction = millis();
     //   delay(200); // for debounce

      }

         if (digitalRead(4)==HIGH)
          {

           push=millis();
           delay(500); // for debounce

        Serial.print(start);
        Serial.print(",");
        Serial.print(reaction);
        Serial.print(",");
        Serial.print(push);
        Serial.println();

      }

    }

title: how to ignore a sensor being tripped the first time and start recording millis on the 2nd time it is tripped

Answers: 1

body:
The start time will default to zero, so you could change it to:

    if (digitalRead(2) == LOW && start == 0)
      {

        start = millis();

      }


body:
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

What does this mean?

https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino

The above link contains the full example program of that line.

This line is from tinygps++ library for extracting the coordinates and displaying in a table format. I'm using arduino uno, GSM module and GPS module to extract the coordinates and transmit it as message. Can anyone explain what dies this constant value mean and why do we use this?

title: Why do we declare constant lat and lon value

Answers: 2

body:
It's a good idea to declare variables the strictest possible way. So if you don't intend to change the value of LONDON_LAT at runtime, declare it as **const**.

This allows the compiler to alert you if your code tries to modify it, and it often allows the compiler to optimize the code.

body:
Static variables are allocated storage only once in a program lifetime
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it and you can't change const variable's value
and i guess you know double is a data type that can save floating point numbers
that line declare two variables with names `LONDON_LAT` and `LONDON_LON` and both of them are in one line
and because london's latitiude and longtitude doesn't change the `const` keyword is used

also i guess because those variables are constants you can use `#define` visit https://www.arduino.cc/reference/en/language/structure/further-syntax/define/


body:
I am trying to read the values from a simple EMG circuit (with an INA122P) using the analogRead() and plotting in the plotter using an Arduino nano v3. I am powering the ina1222p from the 5v pin of the Arduino. But no matter what I do, the signal comes out very noisy most of the time(i can rarely make out the EMG). The bandpass filter is also not really helping. I am using regular solid core wire and alligator clips to connect to the electrodes.

Can someone please tell me what I am doing wrong? or tell me how to make a simple EMG circuit that uses the Arduino's analogRead().

I am also getting ac sine waves when my laptop is plugged to power, so I tried removing the power. The distinguishable sine wave wasn't really showing up, but it was still just as noisy...

**I am a beginner to both Arduinos and designing Analog circuits.**

[![enter image description here][1]][1]

I found this design from here: https://greenhecktech.wordpress.com/2016/09/19/improving-the-emg-amplifier/

  [1]: https://i.stack.imgur.com/ID0Ct.png

title: Noise in Analog Read Serial from an instrumentation amplifier(ina122p)

Answers: 1

body:
"noisy most of the time" - good news: if it's not all the time, that's a sign it can be fixed.

"bandpass filter is also not really helping" - *INA122P circuit likely has something wrong.  check any resistors involved.* Edit: if this was about U2.2, see below as that doesn't look like a band pass...

"regular solid core wire and alligator clips to connect to the electrodes" -
basically 0 shielding with mini-rabbit ears at each end and a big loop area between the wires.
Eventually you will want something better than gator clips.
My main recommendation is that as far as wire goes, if you *form twisted pairs* they tend to be pretty darn good at rejecting noise at least for that part of the wire.  You will want to twist a signal along with its reference (such as a +V and a ground).

Some explanation of the circuit:

U2.1 is creating a 2.5V source that it uses as the reference 'ground' for U1.  Reason for this is to treat 0 as "-2.5" and 5 as "2.5" as op amp math is generally done on a +V, -V basis.  (Personally, I prefer to use voltage regulators to make power buses instead of this. As a result, I give a stink eye to circuits that use the op amp method and claim something about reducing part count.)

U2.2 is a capacitor shy of an active band pass.  It's a high pass filter that is helping preserve and even promote some of the high frequency noise you are picking up. So yes, you may wish to modify or even ditch it until you have high frequency noise under control.

If possible, you may also wish to look into operating at a higher voltage.  This can help improve your signal to noise ratio.  If your signal is essentially +/-2.5V, 250mV of noise would be 10:1, but if you can run at +/-5 V, that same 250mV noise contribution gets dwarfed 20:1.


body:
Multiple MFRC522 Connections (https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi)
I only get from each slave with an ID card; I want to print a defined barcode on the slave address. Briefly; The MOSI line does not matter! Is the 2nd case daisy chain method in this link suitable for me? would like to ask you, dear friends, how should I go about it?
<Regards[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/QKI4S.png

title: Multi MFRC522 Slave AND only mifare read

Answers: 0


body:
I have found a number of other posts from people with the same problem but I can't find an answer.

I have a small batch of ESP-01 boards, sold by Inland, and I wish to use deep sleep mode on them.

I soldered a small copper wire from pin 8 (i.e. GPIO 16) to RST.  On one board I soldered it directly, on another I soldered pin 8 and RST to two sides of a 2 pin header so I could use  jumper in case I wanted to disconnet GPIO 16 from RST.

I am flashing the following simple code (using Arduino IDE 1.8.12), which is about the simplest test of the deep sleep mode that I can think of.

    void setup()
    {
       Serial.begin(74880);
       Serial.setTimeout(2000);

       while(!Serial) { }

       Serial.println(
         "I'm awake, but I'm going into deep sleep mode for 15 seconds");

       ESP.deepSleep(15e6);
    }

    void loop() {
    }

 On starting the serial monitor shows

    ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x4010f000, len 3664, room 16
    tail 0
    chksum 0xee
    csum 0xee
    v39c79d9b
    ~ld
    I'm awake, but I'm going into deep sleep mode for 15 seconds

After 15 seconds the serial monitor shows

    ets Jan  8 2013,rst cause:2, boot mode:(3,6)

and nothing else. After that the thing hangs and nothing further happens.

So,  it appears that the setup runs, the serial monitor prints the message, the mc goes into deep sleep, after 15 seconds it wakes up by a reset, but doesn't go through set up again, hence doesn't print the message or go back sleep.

Here are some comments.    The problem has nothing to do with Wifi, MQTT etc, I have tried many fancy sketches using all of these, I have same problem no matter what, the above sketched is my distillation to the simplest demonstration of the deep sleep problem.

I have flashed the program with Arduino IDE, Platform IO, and esptool.py from a command line.  It doesn't make a difference.

There may be a problem with my soldering job, but I'm pretty good at soldering and SMD rework, and I have repeated the job on a number of these ESP-01 modules, inspected and tested with multimeter, etc.  all with the same outcome.

I don't see a problem with my code or IDE, I have a batch of Lolin Nodemcu boards, and this sketch works perfectly on all of those.  In that case I simply connect GPIO 16 to RST with a jumper wire, the program prints the message, sleeps for 15s, wakes up, prints it again, goes back to sleep for 15s more, etc. etc.

Are these just bad boards?  I have read some things that say the flash chips might be lousy, and if I replace those it might help? I'm tempted to trash these boards and buy some D1 mini's, but I've seen a number of posts from people who say they've had the same problem with D1 minis.   If the board is the problem, are there any recommendations for manufacturers or vendors that sell better quality?

title: ESP-01 wakes up from deep sleep and then hangs

Answers: 2

body:
I have come to the conclusion that these boards are bad.    I wrote a simple sketch that turns an LED on for 3 seconds, then goes into deep sleep for 12 seconds, then wakes up.   I have a batch of 3 Lolin ESP8266 nodemcu boards and the sketch works fine on all of them.   The LED goes on for 3s, then goes off for 12s, then goes back on, etc. Furthermore using an ammeter I measure a current draw of around 80 mA while the LED is on, and around 4 mA while it's off, repeatedly.

However --- I have another batch of five ESP-01 boards.   I soldered a fine copper wire to GPIO 16 and to the reset pin, used the same code, same set up, power supply, LED, etc.
The light goes on for 3s then goes off for 12s,  then comes back on and stays on and then there is no further change.  Furthermore, the current draw during the first 3s is around 80 mA, but when the light comes back on and the controller hangs, the current draw is around 40mA.

Incidentally, I tested the nodemcu boards,the ones that work fine, with this sketch but disconnecting the jumper from GPIO 16 or RST, and it behaves exactly the same as the ESP-01 boards, including the 40mA current draw in  the zombie state.   So it would appear that the problem on the ESP-01 boards is that the GPIO 16 pin is just not connected to RST.  However I have soldered all five of these things multiple times, and I have become pretty darned proficient at soldering that little pin, and I am 99.999999% sure that I have the wire soldered to the pin, with no bridges, didn't fry anything, etc.

body:
Not necessarily an answer, but something to look at: check the Manufacturer ID of the Flash on your board.  My suspicion is that when some Flash chips come out of suspend, they're in lower drive mode than on initial power-up.  At least one person fixed his 'zombie mode' by replacing the Flash with a different vendor.  Nobody else has attempted it yet.

I have an Inland ESP-01S that's reporting MID = 0x5E (supposedly Zbit) and it comes out of Deep Sleep repeatedly.  Here's all of the Manufacturer IDs I know of or have seen:

Winbond EF
GigaDevice C8
Puya 85
Bright Moon 53
BergMicro E0
XMC 20
XTX 0B
Eon 1C
Shanghai Fundan A1
Macronix C2
Hua Hong Zhixin 68
ISSI 9D
Paragon E0 (same as Berg - oopsie or clone?)
Zbit 5E
Zetta BA

esptool.py --port /dev/ttyUSB0 flash_id   (linux)
esptool.py -p COMx flash_id    (Windoze)

Note: the cheap D1 Mini boards with no-name ESP-12F modules flooding eBay, Aliexpress and other places report XTX Flash, and they have a 5.6K pull-up on EXT_RSTB which will shorten the RST pulse from GPIO16, as well as making it hard to hit the level to be detected as a LOW due to the series 470 ohm resistor.  We're unsure whether it's the Flash or the low value pull-up (typically 10 or 12K on other boards/modules) that's causing issues with those boards.  Normally if RST isn't seen as LOW after Deep Sleep then you'll get an "ets_main.c" message at boot before it hangs.

I have a clone D1 Mini Pro that has a Flash that reports MID = EF (Winbond), although the marking on the Flash is nothing I can find on Winbond's site, only on places selling cheap Flash.  Luckily the D1 Mini Pro also exits Deep Sleep successfully.


body:
I am using arduino Uno/Mega.

I am trying to output a range of 0-5v volts using PWM.

Is it possible to do it?

It’s would be nice to see some code or instructions, as far I have seen, they used external Module to get that voltage range, maybe I am wrong or I didn’t understand them well.

Thanks!

title: Output voltage range between 0-5v

Answers: 2

body:
The Arduino is a digital device; each output pin is either HIGH (+5v) or LOW (0v = GND), not in between.

For certain types of devices (motors, LEDs) there is a technique you mentioned called PWM, pulse width modulation, which turns the output on and off rapidly. It's still just a square wave alternating between 0 and 5v but it's doing it really fast. So for an LED for example, your eye will make you think it's at half-brightness even though it is flashing on and off very quickly.

To do this you need to use a pin that has "analog" ability and use the "analogWrite" command.

body:
Short answer: No.

Arduino Unos and Megas have PWM (Pulse Width Modulation) output, which rapidly turn the output on and off with a varying "duty cycle" (The ratio of on time to off time.) That is not the same thing as an analog output voltage.

If you have a constant load you can build a low pass filter that will smooth the output to a slightly dirty DC output based on the PWM output.

You're better off using an external DAC (Digital to Analog Converter.) You send that a digital value and it converts it to a clean, filtered analog output. Most modern DACs are fast enough to output complex waveforms like music.

## Edit:

The Arduino zero apparently has a built-in DAC with up to 10-bit resolution. you could use that to output a low current DC voltage. However the zero is a 3.3V device.


body:
What am I missing that this is happening?
Used to use a laptop (with Create Agent installed on hard drive) which never had this problem.
Now using a Windows 10 desktop and the On-line Create Agent.
Unless I reload the Arduino Create Agent, I always get the 'No Plug-In Connection' error message, please see screen capture. [![enter image description here][1]][1] Device manager recognizes the Arduino Uno and assigns COM3 to the USB connection, please see screen capture.[![Screen Capture from Device Manager][2]][2]

  [1]: https://i.stack.imgur.com/HglKv.png
  [2]: https://i.stack.imgur.com/SztqJ.png

title: Why must I reload ArduinoCreateAgent-1.1-windows-installer-chrome every time I restart my computer?

Answers: 1

body: Thank you to all who have suggested corrective action for my posted communication problem.  After trying all of the suggestions, I threw up my hands and deleted all evidence of Arduino Create Editor.  Next I installed the Arduino Create Editor as a fresh/new install.  Magically, all of my communication issues with the Arduino Uno have been corrected.  Apparently, something in the communication code was corrupted during my first attempt install on my desktop PC.


body:
In my attached screen capture the Arduino Editor appears to be performing the upload, however it never finishes. Completes three steps, the last being the sketch up-load and then states that it is busy.  Sorry that I can't submit a short video. [![Up-Loader Busy][1]][1]Please suggest ideas to solve this issue.  Maybe this is related to my first question?

  [1]: https://i.stack.imgur.com/m4EeV.png

title: Sketch is not being received by Arduino even though Arduino Editor acts like it is finished?

Answers: 2

body: I would suggest you start with a simple blink example sketch and be sure it works. I believe it will. Your picture is almost impossible to read but i caught you have multiple libraries and several other problems. Look at the errors and resolve them one at a time. Until you do it will never load, that is the way it was designed. Be SURE there is only one file with the .ino extension unless it is also part of your sketch.

body: Thank you to all who have suggested corrective action for my posted communication problem. After trying all of the suggestions, I threw up my hands and deleted all evidence of Arduino Create Editor. Next I installed the Arduino Create Editor as a fresh/new install. Magically, all of my communication issues with the Arduino Uno have been corrected. Apparently, something in the communication code was corrupted during my first attempt install on my desktop PC.


body:
I need to count the number of bytes appearing in the serial (UART bus) bus, how to count bytes in Arduino with Arduino Serial functions? is this possible?

Application -
RS485 communication with multiple boards **without slave ID**

slave boards will send data to the master board when,

1st 10 bytes = masters send a 10byte message to all slaves

slaves listening to the bus always until it is the turn to send the data

when byte count is 10, slave 1 sends data 5 bytes to master

when byte count is 15 (10+5), slave 2 sends data 5 bytes to master

when byte count is 20 (15+5), slave 3 sends data 5 bytes to master

max count is 25 known value

title: How to count number of bytes appearing in the Arduino serial?

Answers: 1

body:
`Serial.available()` returns the number of bytes available for reading in the buffer.

    int nBytes=Serial.available();
    if (nBytes > x) {
    ............
    ............
    ............
    }