text:
How to change a code for an I2C 16x2 to a 20x4?
I have found a sketch that someone wrote for a rotary encoder controlled LCD menu.
The code is for an I2C that is 16x2 and I have an I2C that is 20x4. With the code that I found, the layers are all 3 lines, so when they appear on the LCD, it is on 2 "pages".  Since my LCD is 20x4, I don't need to scroll to a second page.
How do I get that third line on the same page as the first two?  I am also still looking at other sketches people have posted for LCD menus, but most of them seem to have outdated libraries or are for 16x2 screens.
#include <OneButton.h>
#include <Encoder.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C  lcd(0x27, 2,1,0,4,5,6,7);

// ROTARY ENCODER
long oldPosition  = 0;
int encoderDTpin = 34;
int encoderCLKpin = 30;
Encoder myEnc(encoderDTpin, encoderCLKpin);

int buttonPin = 26;
OneButton button0(buttonPin, true);

// MENU ARRAY
// First number in array = amount of menu items in root layer. Same goes for next layer.
//(Example: first value in array is 4. This means Layer 0 has 4 menu items. Layer 1 has only 2 menu items.)
// First number infront of menu text is the layer number that item points to. (Example: 1_Rotation points to Layer 1)
// Second number infront of menu text is the number of the value connected to that menu item in the values array.
//(Example: 15Direction points to position 5 in the values array)

String menu[] = {"4","1__Rotation","056Active","3__Watches","4__Item4",       // Layer 0
                 "3","100Rotations","105Direction","109Speed",                // Layer 1
                 "3","256Active","2__Item2.2","2__Item2.3",                    // Layer 2
                 "4","4__Watch 1","3__Watch 2","3__Watch 3","3__Watch 4",     // Layer 3
                 "2","4__Item3.1.1","4__Item3.1.2"};                          // Layer 4

// VALUES ARRAY
// TYPES, 1 numeric / 2 character value range
// 1 - type,value,increments,min,max
// 2 - type,starting value in options array,lowest value options array,max value options array
int values[] = {1,11,25,50,1450, //0-4 WATCH1
                2,2,0,2,         //5-8
                1,600,25,75,600, //9-13

                1,11,25,50,1450, //14-18 WATCH2
                2,2,0,2,         //19-22
                1,600,25,75,600, //23-27

                1,11,25,50,1450, //28-32 WATCH3
                2,2,0,2,         //33-36
                1,600,25,75,600, //37-41

                1,11,25,50,1450, //42-46 WATCH4
                2,2,0,2,         //47-50
                1,600,25,75,600, //51-55

                2,4,3,4,         //56-59 WATCH1 ACTIVE
                2,4,3,4,         //60-63 WATCH2 ACTIVE
                2,4,3,4,         //64-67 WATCH3 ACTIVE
                2,4,3,4};        //68-71 WATCH4 ACTIVE

String options[] = {"CW","CCW","MIX",
                    "No","Yes"};

// Custom character for LCD.
byte cursor[8] = {
  0b10000,
  0b10000,
  0b01000,
  0b00110,
  0b01000,
  0b10000,
  0b10000,
  0b00000
};

byte watch[8] = {
  0b01110,
  0b01110,
  0b11011,
  0b10001,
  0b10001,
  0b11011,
  0b01110,
  0b01110
};

int currentType = 0;
int value = 0;
int numIncr = 0;
int Min = 0;
int Max = 0;

int currentLayer = 0;
int lastLayer = 99;
int currentLength = menu[0].toInt();
int currentPosition = 0;
int currentSelect = 1;
int currentChange = 0;
String currentPress = "";
float currentlcdLayerFloat = 0;
int currentlcdLayer = 0;
int lastlcdLayer = 0;
int lcdUpdated = 0;
int currentLine = 0;
int cursorLayer = 0;
int cursorPosition = 0;
int valueLength = 0;

/*
int homeScreen = 1;

String currentTime = "00:00:00";
String lastTime = "00:00:00";
String temptime = "00";
String currentDate = "";

int watch1active = values[56] - 3;
int watch2active = values[60] - 3;
int watch3active = values[64] - 3;
int watch4active = values[68] - 3;
int watch1rotations = 0;
int watch2rotations = 0;
int watch3rotations = 0;
int watch4rotations = 0;
int watch1left = values[1];
int watch2left = values[15];
int watch3left = values[29];
int watch4left = values[43];
String temprotationsleft = "";
*/

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

  // Map rotary button to actions single and doubleclick.
  button0.attachClick(singleClick);
  button0.attachDoubleClick(doubleClick);

  lcd.begin (16,2);
  lcd.setBacklightPin(3,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home();

  // Create the custom character.
  lcd.createChar(0, cursor);
  lcd.createChar(1, watch);

  lcd.setCursor (2,0);
  lcd.print("Watch Winder");
  delay(1000);
  clearLine(0);

  // Set the select cursor on the first line.
  cursorLayer = 0;
  lcd.setCursor (0,cursorLayer);
  writeCursor();

}

void loop() {

    // Listen to button presses.
    button0.tick();

    // Listen if the rotary encoder moves.
    rotary_check();

    // Print the LCD menu.
    lcdMenu();

}

void singleClick() {

  // IF current layer number is the same as redirect layer number, we stay on the same layer
  // AND no item is selected in the menu
  // AND the selected item has a redirect to another layer
  if(currentLayer == menu[currentPosition + currentSelect].substring(0,1).toInt()
      && menu[currentPosition + currentSelect].substring(1,3) != "__" && currentPress == ""){

    currentPress = menu[currentPosition + currentSelect].substring(3);
    currentChange = menu[currentPosition + currentSelect].substring(1,3).toInt();

    Serial.println("Currentpress: " + currentPress);

    currentType = values[currentChange];
    value = values[currentChange + 1];

    // Type select change is numeric
    if(currentType == 1){
      Min = values[currentChange + 3];
      Max = values[currentChange + 4];
      numIncr = values[currentChange + 2];

      Serial.println("Currentvalue: " + String(value));
      Serial.println("Increments: " + String(numIncr));
      Serial.println("Min: " + String(Min));
      Serial.println("Max: " + String(Max));

      valueLength = String(value).length();

    // Type select change is character range
    } else if(currentType == 2){
      Min = values[currentChange + 2];
      Max = values[currentChange + 3];

      Serial.println("Currentvalue: " + options[value]);
      Serial.println("Options: ");

      for (int i=Min; i <= Max; i++){
        Serial.println(options[i]);
      }

      valueLength = options[value].length();

    }

    clearSelect();
    cursorPosition = 15 - valueLength;
    lcd.setCursor(cursorPosition,cursorLayer);
    writeCursor();

  // ELSE IF something is selected in the menu, and the button is pressed again. We deselect the item.
  } else if(currentPress != ""){

    currentValues();
    currentPress = "";
    currentChange = 0;

    clearChar(cursorPosition,cursorLayer);
    lcd.setCursor(0,cursorLayer);
    writeCursor();

  // IF nothing is selected and nothing will be deselected, move to the redirect layer listed in the first position of the array.
  } else {

    currentLayer = menu[currentPosition + currentSelect].substring(0,1).toInt();
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;
    lcd.setCursor (0,cursorLayer);
    writeCursor();

  }

}

// Reset to layer 0.
void doubleClick() {
  if(currentLayer == 0){
    currentLayer = 0;
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;

    lcd.clear();
    lcdUpdated = 0;
  }
  if(currentLayer != 0){
    currentLayer = 0;
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;
    lcd.setCursor (0,cursorLayer);
    writeCursor();
  }
}

void rotary_check(){

  // Constantly read the position of the rotary encoder
  long newPosition = myEnc.read() / 4;

  // IF the new position of the encoder is different then the old position
  if (newPosition != oldPosition) {

    // IF nothing has been selected in the menu
    if(currentPress == ""){

      if(newPosition > oldPosition && currentSelect < currentLength){
        clearSelect();
        currentSelect++;
        currentlcdLayerFloat = currentlcdLayerFloat + 0.5;
        currentlcdLayer = currentlcdLayerFloat;

        cursorSelect();

        lcd.setCursor (0,cursorLayer);
        writeCursor();
        Serial.println("> " + menu[currentPosition + currentSelect].substring(3));

      } else if (newPosition < oldPosition && currentSelect != 1){
        clearSelect();
        currentSelect--;
        currentlcdLayerFloat = currentlcdLayerFloat - 0.5;
        currentlcdLayer = currentlcdLayerFloat;

        cursorSelect();

        lcd.setCursor (0,cursorLayer);
        writeCursor();
        Serial.println("> " + menu[currentPosition + currentSelect].substring(3));

      }

      if(lastlcdLayer != currentlcdLayer){
        lcdUpdated = 0;
      }

      lastlcdLayer = currentlcdLayer;
      oldPosition = newPosition;

    // IF something has been selected in the menu, we are going to change the value of a menu item.
    } else if(currentPress != ""){

      lcd.setCursor(cursorPosition + 1,cursorLayer);
      // IF the new position is HIGHER then the old position
      if(newPosition > oldPosition){
        clearChar(cursorPosition,cursorLayer);

        // IF the selected item has a change type that is NUMERIC.
        // AND the MAXIMUM of the selected item has not been reached.
        // We change the value UPWARDS with the icrements listed in the array.
        // SAME applies for next ELSE IF, just for the change type character. And the next ELSE IF we just go down.
        if(currentType == 1 && value < Max){
            value = value + numIncr;
            values[currentChange + 1] = value;
            Serial.println(value);

            clearValue();
            valueLength = String(value).length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(value);
          }

        if(currentType == 2 && value < Max){
            value++;
            values[currentChange + 1] = value;
            Serial.println(options[value]);

            clearValue();
            valueLength = options[value].length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(options[value]);
          }
          lcd.setCursor(cursorPosition,cursorLayer);
          writeCursor();

      } else {
        clearChar(cursorPosition,cursorLayer);

        if(currentType == 1 && value > Min){
          value = value - numIncr;
          values[currentChange + 1] = value;
          Serial.println(value);

          clearValue();
          valueLength = String(value).length();
          cursorPosition = 15 - valueLength;
          lcd.setCursor(cursorPosition + 1,cursorLayer);
          lcd.print(value);
        }

        if(currentType == 2 && value > Min){
            value--;
            values[currentChange + 1] = value;
            Serial.println(options[value]);

            clearValue();
            valueLength = options[value].length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(options[value]);
          }
          lcd.setCursor(cursorPosition,cursorLayer);
          writeCursor();

      }

      oldPosition = newPosition;
    } else {
      oldPosition = newPosition;
    }

  }
}

void lcdMenu(){
  if (lastLayer != currentLayer || lcdUpdated == 0){

    currentLength = menu[0].toInt();
    currentPosition = 0;

    for (int i=0; i < currentLayer; i++){
      currentPosition = (menu[currentPosition].toInt() + 1) + currentPosition;
      currentLength = menu[currentPosition].toInt();
    }

    clearMenu();
    int tempPosition = currentPosition;

    if(currentlcdLayer != 0){

      currentPosition = currentPosition + (currentlcdLayer * 2);
    }

    Serial.println("LCD-------------");

    for (int i=1; i <= 2; i++){
      lcd.setCursor (1,i - 1);
      lcd.print(menu[currentPosition + i].substring(3));

      currentType = 0;
      value = values[menu[currentPosition + i].substring(1,3).toInt() + 1];
      String tempvalue = "";

      if(menu[currentPosition + i].substring(1,3) != "__" && menu[currentPosition + i].substring(1,3) != ""){
        currentType = values[menu[currentPosition + i].substring(1,3).toInt()];
        if(currentType == 1){
          lcd.setCursor (16 - String(value).length(),i - 1);
          lcd.print(value);
          tempvalue = " "+ String(value);
        }else if(currentType == 2){
          lcd.setCursor (16 - options[value].length(),i - 1);
          lcd.print(options[value]);
          tempvalue = " "+ options[value];
        }

      }

      Serial.println(menu[currentPosition + i].substring(3) + tempvalue);
    }
    Serial.println("----------------");

    currentPosition = tempPosition;
    lastLayer = currentLayer;
    lcdUpdated = 1;

    /**
    Serial.println("Layer " + String(currentLayer + 1));
    Serial.println("Layer length " + String(currentLength));
    Serial.println("Layer position " + String(currentPosition));
    **/

  }
}

void currentValues(){

  Serial.println("Currentpress: " + currentPress);

  if(currentType == 1){
      Serial.println("Currentvalue: " + String(value));
      Serial.println("Increments: " + String(numIncr));
      Serial.println("Min: " + String(Min));
      Serial.println("Max: " + String(Max));

    } else if(currentType == 2){
      Serial.println("Currentvalue: " + options[value]);
      Serial.println("Options: ");

      for (int i=Min; i <= Max; i++){
        Serial.println(options[i]);
      }
    }
}

void clearChar(int charPosition, int line){
  lcd.setCursor (charPosition,line);
  lcd.print(" ");
}

void clearLine(int line){
  lcd.setCursor (0,line);
  lcd.print("                ");
}

void clearMenu(){
  lcd.setCursor (1,0);
  lcd.print("               ");
  lcd.setCursor (1,1);
  lcd.print("               ");
}

void clearSelect(){
  lcd.setCursor (0,0);
  lcd.print(" ");
  lcd.setCursor (0,1);
  lcd.print(" ");
}

void cursorSelect(){
  switch (currentSelect){
          case 1:
            cursorLayer = 0;
            break;
          case 2:
            cursorLayer = 1;
            break;
          case 3:
            cursorLayer = 0;
            break;
          case 4:
            cursorLayer = 1;
            break;
          case 5:
            cursorLayer = 0;
            break;
          case 6:
            cursorLayer = 1;
            break;
        }
}

void writeCursor(){
  lcd.write(byte(0));
}

void clearValue(){
  for (int i = 16 - valueLength; i <= 16; i++){
        lcd.setCursor (i,cursorLayer);
        lcd.print(" ");
      }

}

or use and existing menu library https://github.com/search?utf8=%E2%9C%93&q=arduino+menu&type=

Change line
lcd.begin (16,2);

to
lcd.begin (20,4);

then position cursor as you did for lines 0 & 1.


text:
Pushing sketches to pro mini with Uno 101
So I just bought a Pro Mini the other day, however, I didn't get an FTDI cable or a USB/Serial converter board.
From what I understand from this article I can use my Arduino Uno 101 to push sketches onto the Pro Mini.
The wires are all hooked up (grounded reset on the Uno) and I have uploaded the sketch to disable the serial communication port on the Uno, however, when I try to push a sketch to the Mini it errors out with the following message
Arduino: 1.8.3 (Windows Store 1.8.6.0) (Windows 10), Board: "Arduino Pro or Pro Mini,
ATmega328 (5V, 16 MHz)"

Sketch uses 928 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM3": The system cannot find the
file specified.

Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

The only part of the suggested troubleshooting guide that maybe applicable is the drivers section.

Drivers
The Arduino Uno and Mega 2560 use standard drivers (USB CDC) provided by the operating system to communicate with the ATmega8U2 on the board. Other Arduino boards use FTDI drivers to communicate with the FTDI chip on the board (or in the USB-serial convertor).

I could be wrong but to me it doesn't seem like the second sentence applies to this situation since the the Uno sits between the pc and the mini. However, when I check the windows device manager I can see that the Uno is connected on a COM port, but nothing about the Mini. Though I am not sure that it should show up.
I am using the IDE(1.8.3) to program and "Arduino Pro or Pro Mini" as the board. Though Tools>Port is greyed out when I have this board selected.

There is no "Arduino Uno 101" there are only "Arduino Uno" and "Arduino 101".
101 uses completely different hardware, and tricks to use an Uno as an USB to UART adapter won't work on an 101.
101 has also separate serial interfaces for USB serial (Serial) and hardware serial (Serial1).
If you have have an Arduino 101 you can solve this by software means.
The board needs to be able to change the baud rate and use DTR for reset.
There is a sketch from PaulStoffregen on GitHub that does that.
/* USB to Serial - Teensy becomes a USB to Serial converter
   http://dorkbotpdx.org/blog/paul/teensy_as_benito_at_57600_baud

   You must select Serial from the "Tools > USB Type" menu

   This example code is in the public domain.
*/

// set this to the hardware serial port you wish to use
#define HWSERIAL Serial1

unsigned long baud = 19200;
const int reset_pin = 4;
const int led_pin = 13;  // 13 = Teensy 3.X & LC
                         // 11 = Teensy 2.0
                         //  6 = Teensy++ 2.0
void setup()
{
  pinMode(led_pin, OUTPUT);
  digitalWrite(led_pin, LOW);
  digitalWrite(reset_pin, HIGH);
  pinMode(reset_pin, OUTPUT);
  Serial.begin(baud);       // USB, communication to PC or Mac
  HWSERIAL.begin(baud);     // communication to hardware serial
}

long led_on_time=0;
byte buffer[80];
unsigned char prev_dtr = 0;

void loop()
{
  unsigned char dtr;
  int rd, wr, n;

  // check if any data has arrived on the USB virtual serial port
  rd = Serial.available();
  if (rd > 0) {
    // check if the hardware serial port is ready to transmit
    wr = HWSERIAL.availableForWrite();
    if (wr > 0) {
      // compute how much data to move, the smallest
      // of rd, wr and the buffer size
      if (rd > wr) rd = wr;
      if (rd > 80) rd = 80;
      // read data from the USB port
      n = Serial.readBytes((char *)buffer, rd);
      // write it to the hardware serial port
      HWSERIAL.write(buffer, n);
      // turn on the LED to indicate activity
      digitalWrite(led_pin, HIGH);
      led_on_time = millis();
    }
  }

  // check if any data has arrived on the hardware serial port
  rd = HWSERIAL.available();
  if (rd > 0) {
    // check if the USB virtual serial port is ready to transmit
    wr = Serial.availableForWrite();
    if (wr > 0) {
      // compute how much data to move, the smallest
      // of rd, wr and the buffer size
      if (rd > wr) rd = wr;
      if (rd > 80) rd = 80;
      // read data from the hardware serial port
      n = HWSERIAL.readBytes((char *)buffer, rd);
      // write it to the USB port
      Serial.write(buffer, n);
      // turn on the LED to indicate activity
      digitalWrite(led_pin, HIGH);
      led_on_time = millis();
    }
  }

  // check if the USB virtual serial port has raised DTR
  dtr = Serial.dtr();
  if (dtr && !prev_dtr) {
    digitalWrite(reset_pin, LOW);
    delayMicroseconds(250);
    digitalWrite(reset_pin, HIGH);
  }
  prev_dtr = dtr;

  // if the LED has been left on without more activity, turn it off
  if (millis() - led_on_time > 3) {
    digitalWrite(led_pin, LOW);
  }

  // check if the USB virtual serial wants a new baud rate
  if (Serial.baud() != baud) {
    baud = Serial.baud();
    if (baud == 57600) {
      // This ugly hack is necessary for talking
      // to the arduino bootloader, which actually
      // communicates at 58824 baud (+2.1% error).
      // Teensyduino will configure the UART for
      // the closest baud rate, which is 57143
      // baud (-0.8% error).  Serial communication
      // can tolerate about 2.5% error, so the
      // combined error is too large.  Simply
      // setting the baud rate to the same as
      // arduino's actual baud rate works.
      HWSERIAL.begin(58824);
    } else {
      HWSERIAL.begin(baud);
    }
  }
}

Then you need to connect:
Arduino 101  |  Arduino Pro Mini
-------------+------------------
VCC          |  VCC
GND          |  GND
TX           |  RX
RX           |  TX
PIN 4        |  DTR

After that you can use the port as a Arduino Pro Mini programmer.

I tested that code on a Pro Micro and was able to program a Pro Mini.

source: Stack Exchange

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

sort: votes


text:
Trying to map a room with Arduino controlled bot

What you see above is a map of my room. The boxes in black are obstacles and the box in red is my bot.
Now I want my bot to go around the room, avoiding all obstacles, but at the same time, covering the entire floor. Think of it like the robot is painting the floor and it has to paint the entire floor avoiding all obstacles.
Now my first approach was to put 3 HC-SR ultrasonic sensors on 3 sides and listen to them in a sequence, deciding which path is best and then going there. But this method leaves out quite a lot of floor area uncovered.
So how can I cover the entire floor area here?
 Presently I am working with Arduino UNO and HC-SR04 but wouldn't hesitate to throw my Pi3 or a few more sensors in there...-

This is more of a robotics question and not really about Arduino,

This is actually quite a complex thing to achieve. I'll give some suggestions, though this is not something I have attempted (yet).
The main thing to do is divide the room up into a grid. The resolution you choose (X and Y dimensions) depends on how small your robot is, how big the room is, and how much memory your have available (on an Uno that's not much at all).
The second thing you need to do is work out a way of determining exactly where in the room you are. That could be done by trying to get as close to the bottom-left corner as possible before starting to map.
Now you can work from square to square (you could do with some encoders to know how far you have driven, and a magnetometer so you know which direction you are facing) using whatever method you like to decide which way to go, and in each square you look to see which of the squares around you are accessible. From that you can work out which way you can go from that square.
As you go you maintain a map in memory of all the squares you have been to, and the squares that you cannot get to. Note that it may not be enough to say "You can't get to square 4,3" - instead you may to keep a more detailed list (depending on what your obstacles are). "You can't get to square 4,3 from square 4,2, nor 3,3, but you can get to it from square 5,3" for example (e.g., a thin obstacle that only blocks entry to that square from certain sides).
Since your sensors cover longer ranges than just one square (unless you have big squares) you can work out how far away an obstacle is, and mark the square it's in before you even get close to it. The square immediately preceding it on a path between it and you would be the "you can't get there from here" square.
Now you can work out paths and routes to get to the squares you need to so you can cover all the available floor.

I must say... That was much more complex than I thought it would be.. But I'm gonna give it a shot for sure

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


text:
Avoid a Pro Micro waking up a PC?
I have an Arduino Pro Micro mimicking as a HID, connected to a PC.
The PC BIOS is configured to wake from keyboard events - it is switched on by hitting a key on the regular keyboard. This is a wanted feature and should stay.
Unfortunately, it also wakes when the Arduino sends HID events, which is understandable and pretty obvious, but to be avoided.
Is there something in the USB protocoll, or even in the Arduino HID libraries, that lets me tell the chip to either not wake up the host (unlikely, I guess); or so that I can detect when the PC has shut down, so I can tell the Arduino to go sleeping as well until the PC wakes up again?
EDIT: I am using the "HID-project" USB library (HID 2.4.3) from https://github.com/NicoHood/HID.

You should be able to detect if the host is sleeping. Which USB library are you using?

@Gerben, I use the library at https://github.com/NicoHood/HID .

you can simply disable the "wake on keyboard" feature of your pc, if that helps

No, @dandavis, I would like just this one device to "behave".

maybe there is a key or two that doesn't wake up the pc. i always used pause to wake, but one laptop i had ignored that and a few other keys. it might also be possible to interrogate the locks without toggling, which hopefully wouldn't wake the PC.  i think it's possible because i thought i've plugged in a keyboard to a sleeping PC, had the caps lock light come on, but still had to press space to actually wake up the PC... Also, i wonder if those lock interrogations would time out  were the PC sleeping; a way to detect sleep.

There are many doubtful points in here. Your PC is powering USB ports when sleep or completely shut down? And why you send HID events with your Arduino if you don't want to do?

@user30878, it's nothing mysterious. PCs powering USB ports when off is pretty standard (else, "wake on USB" would be hard to implement); and my device must send HID events (it is a HID device). This questions asks about selectively avoiding the "wake on USB/HID" functionality for a single device by either telling the PC so (which is likely impossible as we are talking about BIOS/close to hardware-level functionality), or having the device detect when the PC is sleeping (more hopeful, but nobody came forth with a suggestion, and I didn't find anything about it anywhere else).

Ok but do you need send HID events always (continuously)?

Unfortunately, yes. The device sends HID events when some analog input changes; this can happen if someone bumps against the table or something like that.

We need to know your exact aim. You can send sleep command to your pro mini with PC just before sleeping. You want to don't wake up the PC from hid but your hid device is always active. It's meaningless

@user30878, I'm sorry if my question offends you. I believe it is pretty meaningful and precisely formulated. If you know a way to send a sleep command form the PC to the device, I'm all ears - just keep in mind that there is no dedicated OS driver for it, as it uses the default HID protocol.

Yes you can send commands to your pro mini from PC easily. You can use virtual serial com  ports with c#, c, Java etc... And you look like already know Arduino programming. But you maybe will need a push button or something like that for waking up the pro mini again.

@user30878, writing a program on the PC, and adding a push button is exactly what I wish to avoid with this question. If I went to that direction, then I would just have an on/off switch on the device and be done with it (which is what I've done meanwhile, anyways).

Look answers below

https://superuser.com/q/596758/697394

Assuming you are using windows, on the device manager you can access each device's properties (power management tab), where you can allow or not each device to wake your system up.

Check your BIOS for an option to wake up on a particular key combination, rather than "any key".
Another option is to configure a particular USB port to be powered down when the computer is asleep (or discover which ports are powered down if no such option is available). If that doesn't help, you can try to put a USB hub between the Arduino and the PC: many hubs don't cope with sleep modes very well, so there's a chance they won't re-transmit anything your Arduino is sending unless the PC wakes up. If your computer has USB3, you can try a USB3 hub, which has an even higher chance of exhibiting this behavior since BIOS often lacks USB3 hub support.

Any bios have this particular key option?


text:
Error using Crypto Library for Arduino: Speck
I'm trying to encrypt a string in my Arduino Uno using the following library:
https://github.com/rweather/arduinolibs/tree/master/libraries/Crypto
And I'm getting this error:

In function 'void setup()':
TESTING_SPECK_LIB:27: error: request for member 'setKey' in
  '(byte)(& cipher)', which is of non-class type 'byte {aka unsigned
  char}'
cipher->setKey(*key,keySize);
exit status 1 request for member 'setKey' in '(byte)(& cipher)',
  which is of non-class type 'byte {aka unsigned char}'

This is the code I'm using:
#include <Crypto.h>
#include <Speck.h>
#include <SpeckSmall.h>
#include <SpeckTiny.h>
#include <string.h>

Speck speck;
SpeckSmall speckSmall;
SpeckTiny speckTiny;

byte buffer[16];
byte cipher[16];
size_t keySize = 32;

void setup() {

  const uint8_t key[32]={0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
  byte plaintext[16]={0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
  byte ciphertext[16]={0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                    0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};

  Serial.begin(9600);

  cipher->setKey(*key,keySize);
  cipher->encryptBlock(buffer, plaintext);

}

void loop() {

}

I know that I'm doing something wrong, but I don't understand what the error means, someone knows what it means and how to fix it?

byte cipher[16]; declares cipher as an array of 16 bytes.  As such, cipher has no methods, much less ones called setKey() or encryptBlock().
Note, setKey() and encryptBlock() look like method names one would find in Crypto or Speck library code; however, I don't find them in the Crypto and Speck headers I looked at on github sites.  Also, buffer, cipher, and keySize look like variables and parameters one would use in creating an object for use with encryption methods.
In short, it appears your code fails to set up an appropriate class of objects that have setKey() and encryptBlock() methods.
Note, while I am not familiar with their details, I question whether all of the header files Speck.h, SpeckSmall.h, and SpeckTiny.h should be included in your code.  It seems more likely that you would choose one of them as appropriate to your needs.

Edit 1:  Looking at TestSpeck.ino as mentioned in per1234 6's comment, one sees a function perfCipher(), with its first argument declared as BlockCipher *cipher.  That is, cipher is declared as an object of a class that has setKey() and encryptBlock() methods.
The TestSpeck.ino sketch includes all three of the header files Speck.h, SpeckSmall.h, and SpeckTiny.h because it runs performance tests that compare results using different Speck implementations.  In practice you usually won't need more than one of those headers.

See https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/examples/TestSpeck/TestSpeck.ino indeed it does include all three of those files. I'm guessing each adds an additional layer of functionality. That example declares an array named ciphertext, not cypher. I suspect OP confused the two, thus the error.

@per1234, thanks, have edited a note about that


text:
Arduino autorestarts when powered externally
I'm trying to finish  building an alarm system with relays, leds  and bluetooth. I finally made it working but when externally powered (12v source) after about 10 seconds it starts to reboot continuously.
This issue comes with no pc connection.

And how toasty does the 5v regulator get...?

Very much, could be this a sort of heat protection?

Most regulators have thermal protection, yes. You will need a better power supply arrangement.

https://www.arduino.cc/en/Main/ArduinoBoardUno
Majenko has a good lead,
12V is just within spec of the voltage regulator.
Though this may be different per manufacturer or different in your environment.
To battle overheating you can:

Create beter airflow
Add a heatsink
Draw less current

But you should try a 9V source, that can deliver enough current (not the 9V "block" batteries).
Also check if the system draws excessive current, maybe the circuit has a low resistance or power hungry part (on the 5V rail)
If nothing works, you could try and use another Arduino board, maybe the regulator is faulty/damaged.

I added an additional power supply 5v for the sensors, relays, etc. Now the arduino regulator is cooler and I don't experience reboots anymore.
Thank you Paul


text:
No code, but Fatal exception (0): epc1=0x402066ac, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 in Serial Monitor
I have a Wemos d1 mini, and when I upload nothing or anything to it, the built-in LED always lights up and the serial monitor gets a lot of garbage at every baudrate.  I have supplied it with 4 AA batteries and the board has a built in voltage regulator of 3.3V at the 5V pin.
The Wemos d1 mini contains the esp8266 chip.
Please help me!  I have searched everywhere.  This just happened all of a sudden, the board was working perfectly fine before too.

do you have anything hooked up to the pins?

No, nothing is hooked up besides the power cables.

Garbage on the serial port when you power the board up or otherwise reset it is normal. It's the bootloader boot messages at a strange baud rate. You can ignore them.

@NathanRamanathan - You have power cables and USB?  It will draw power from the USB, you don't need external power too.  Like Majenko says ESPs always dump garbage on start-up, so it might be OK.  Have you checked you have the Reset switch in the correct place?  Have you grounded GPIO-0 (not D0) during boot up and corrupted the firmware?

Yes, Code Gorilla.  You figured it out!  I might have accidentally grounded pin d3, GPIO-0, during boot up.  What do I do?  I never heard of reflashing a wemos D1 mini.

Three words.  "You Bricked it"
Before you go surfing on the web for days and days, I'm just going to say the module is bricked.  I've been there and found out that you should never use these devices on breadboards and with funky power sources.  There is this chip within the module called eFuse,  which is basically an electronic fuse that's really easy to destroy.  Just use the Arduino YUN or other certified or Chinese clonable modules. Those Italians are smarter than you think. That's probably more reliable because you won't have any power issues or frying issues.
I'm also assuming that you are getting a fatal exception (0) in the Serial Monitor.  In that case, your module's death sentence is officially sealed.
Congrats. :(

For me, this was not true! I was able to "revive" the ESP-01 by simply flashing it again using Arduino IDE. I was getting the same message from the Serial Monitor prior to this, after I've tried flashing new firmware.


text:
Accidentally plugged in Arduino Uno before installing software, now it's not recognized by Windows 10, only powered by usb port
Just got a new Arduino Uno, accidentally plugged it in before installing the IDE and windows installed its drivers and had it under ports as a generic device on COM3 (it wasn't named Arduino Uno on device manager).
When I installed the IDE, I couldn't upload sketches to the board because it wasn't recognized. So I uninstalled the device from device manager and also the IDE. I pressed the reset button on the Uno, restarted my PC, reinstalled the IDE, then plugged in the Uno. Since then however, the device isn't read by Windows at all; device manager doesn't show it anywhere, nor does it even refresh when plugged in.
I tried this restarting/reinstalling process multiple times, it's also not a cable issue because I checked for that as well. The power LED is still on, and the pin 13 LED is blinking, but the Arduino isn't being recognized.
I've also tried using the Hardware Install Wizard, but that gives me

This Device Cannot Start (Code 10)

I've been trying to run this for a while now.

I'm running Windows 10, and Arduino IDE for more than  6 months now, 2 different systems, and, for me, UNOs always show as a generic USB device, and everything works just fine.

Last time something similar happened to me, it was caused by a crappy USB cable.

If it shows up as a COM port, you can select/program it through the Arduino IDE, what is the problem here?

you won't see the word "uno" in device manager. do you hear a "ding" when you plug in the Uno?

Also try another USB port.

Check serial communication device on the development board, sometimes the drivers it needs are not installed by default while installing IDE as clones come with different varieties of USB to serial ICs. Try to use different Arduino if you have.

You should not need to install drivers in Windows 10. Windows 10 has its own CDC/ACM drivers built in. What you had before you installed the drivers was correct - it was probably just the settings in the IDE breaking it (wrong port selected?)

There was another post on here recently that was showing error code 10.  I think it is still unresolved though.

You do not need to install drivers in Windows 10 (unless you have a CH340G based Chinese clone, in which case it wouldn't have detected before installing the drivers).
Windows 10 has its own CDC/ACM drivers built in - something every other operating system has had for years and Windows has only just caught up with them. That is why it detected COM3 fine before.
It should have worked fine without installing drivers. It may have been the IDE with the wrong port selected or something else interfering with the port that was stopping you using it.
Uninstall the Arduino drivers and revert to using the Windows built-in ones and work on diagnosing why it wasn't working with those.

You can always remove a unknown device in device manager (yellow exclamation point), reinstall the software, then plug the device in.

If you go to device manager and right-click the Arduino (it will probably have a yellow exclamation mark next to it). You can click update drivers. This fixed the problem for me.

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


text:
How to read Negative number with serial.read
how i can read negative number with command Serial.read()?
beacouse i with  this
    char tmpChar = Serial.read(); //read incoming character from serial port
    if (isDigit(tmpChar)) { //check if the in character it's a number
        setpoint =  (setpoint  * 10 ) + tmpChar - '0'; // convert from ascii code to it's corresponding number; '0' == DEC 48
      }
if (tmpChar == '\n' || tmpChar == '\r') { //if CR or LF was received
    if (setpoint > 0) {
      tmpChar = "";
      Serial.print(setpoint);
      Serial.println(" NUMERO STEP IN AVANTI");

    }

im using an encoder motor, i want to move for N steps the motor forward (positive number) or backward (negative number) , i insert the number of step in serial input
i can read only positive number. Thanks for help
how suggest Majenko i made a partial solution :
char buf[8];
int valore = 0;

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

void loop() {
  if (Serial.available() >= 8) {
    for (int i = 0; i < 8; i++) {
      buf[i] = Serial.read();

    }
    String str();
    if (buf[0] == "-") {
      valore = (atoi(buf)) * -1;
      Serial.println(valore);

    }
    else {
      valore =  atoi(buf);
      Serial.println(valore);
    }
  }
}

but the problem now it's the static array ,
unpleasant to use

Personally I would read the data into a char array then use either atoi() or strtol() to convert that char array into a number.
Using those functions is more robust that parsing the data yourself since they identify where the number ends and discards any trailing garbage. It also skips any white space before the number. For instance it will interpret all these as the number -32: "     -32", "-32 Degrees", "   -32+4  " and "-32-2".
strtol() has the additional advantage that it can work in other bases than 10, so you could interpret hexadecimal data, binary data, sexagesimal data, etc.
atoi() and strtol() are standard C functions.
E.g.:
int val = atoi(mycharbuffer);

or
long val = strtol(mycharbuffer, NULL, 10);

can make an example please

Of what - the reading into the char buffer, or the converting to integer?

to convert readed char in a negative int , thanks for help

Done. See my edit.

im tryng with this without succes, where im wrong? `void loop() {
char tmpChar = Serial.read();
long val = strtol(tmpChar, NULL, 10);
Serial.println(val);
}`

That's because you're trying to convert one single char. You need to read the whole string of characters into a character array first. Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

You could do something like this:
static int setpoint;      // the partially read setpoint
static bool isNegative;   // whether it should be negative
void applySetpoint(int);  // apply the setpoint when fully read

char tmpChar = Serial.read();
if (isDigit(tmpChar)) {
    setpoint =  (setpoint  * 10 ) + tmpChar - '0';
} else if (tmpChar == '-') {  // minus sign
    isNegative = true;
} else if (tmpChar == '\r') {  // line terminator
    if (isNegative) {
        setpoint = -setpoint;
        isNegative = false;  // reset for next read
    }
    applySetpoint(setpoint);
}

Note that this is not very robust: it will happily interpret "3-2" as
meaning "-32". Note also that I assumed your terminator to be '\r', you
may be using another one.

The parseInt can read negative numbers (I think it does, the reference is very cryptic). The parseInt has a timeout so it does not wait forever.
Can you tell what kind of data you are reading ? Is it part of more data ?

im using an encoder motor, i want to move for N steps the motor forward (positive number) or backward (negative number) , i want to insert the number of step in serial input

Just a number then ? When parseInt has a timeout, it returns 0, that means you can't send a 0. If that is okay, then check for Serial.available and do a Serial.parseInt.


text:
How to pulse a signal at 100ms to 500ms?
Based on this PDF I need to pulse between 100ms and 500ms to record a video (the description is apparently wrong according to this guy). How would I generate such a pulse? The small module has 3 wires I can use, which are positive, ground, and a yellow wire. I assume I need to pulse the yellow wire.
I don't want to hook anything up wrong, but my guess would be using pulseIn(). However, I am not sure at all. Any help appreciated.

According to the pdf you need > 500ms for video...  100 - 500 is photo.

@Majenko That is wrong according to some guy, but that doesn't really matter anyway.

Okay, so pulsing is apparently easy enough. If I just do:
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);

It will start recording, then turn off about a second later, start again about a second later, and then repeat. I somehow managed to get a 5 second recording as well. I'm not really sure how this is supposed to work. I need to test some more.
EDIT: Turns out the schematics were right. If I do something as simple as:
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(1000);

It will turn on the video recording and turn off whenever it gets HIGH again.


text:
Where to declare timer interrupt variables?
I have a situation where the majority of the code is residing inside timer interrupt functions.
Setup() does what it has, loop() basically reads ADCs and then all the code is inside timer interrupts.
void loop()
{
  //Read the ADCs
  while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);   // wait for ADC 0, 1, 8, 9, 10 conversion complete.
  in_ADC0=ADC->ADC_CDR[7];                  // read data from ADC0
  in_ADC1=ADC->ADC_CDR[6];                  // read data from ADC1
  POT0=ADC->ADC_CDR[10];                    // read data from ADC8
  POT1=ADC->ADC_CDR[11];                    // read data from ADC9
  POT2=ADC->ADC_CDR[12];                    // read data from ADC10
}

void TC4_Handler()
{
 if (effect==0)       {/*HERE THE CODE FOR EFFECT 0*/}
  else if (effect==1)  {/*HERE THE CODE FOR EFFECT 1*/}
    else if (effect==2){/*HERE THE CODE FOR EFFECT 2*/}
      else             {/*HERE THE CODE FOR EFFECT 3*/}

  // We need to get the status to clear it and allow the interrupt to fire again
  TC_GetStatus(TC1, 1);
}

The user selects the effect he wants via a button and a hardware interrupt.
What happens when the timer interrupt function ends? Do we go back to loop(), or the timer function is re-run?
In this example, all the vars needed inside each functino of the timer interrupt are declared globally.
I was considering if i can declare variables inside each function in the Timer Interrupt function.
Therefore, we would save space, by not declaring variables that are not run at the moment. And we would only initialize variables for the effect we want.
Is this possible? Because if the effect i have just selected just re-loops, maybe its not wise for vars to get re-initialized  (and their values re-set) each and every time it is looped.
So ultimately, variables taht will be used inside a timer interrupt function, globally or locally?

If they are only used in the interrupt then yes they can be declared in the interrupt. If you want them to retain their value from one call to another they must be declared static, and then they will be the same as global variables as far as memory allocation is concerned.


text:
Can't reset Arduino Pro Micro
I'm trying to reset an Arduino Pro Micro with a new code and it is not allowing me to. I'm using an empty sketch to upload to the pro micro but I get different error messages every time. I think the reason why it doesn't allow me to upload code is because it is programmed to start on boot. As soon as it's plugged in to a USB port the code runs, and causes this issue.
Some of the errors I get is
Arduino: 1.8.2 (Linux), Board: "Arduino/Genuino Micro"

Sketch uses 3602 bytes (12%) of program storage space. Maximum is 28672 bytes.
Global variables use 147 bytes (5%) of dynamic memory, leaving 2413 bytes for local variables. Maximum is 2560 bytes.
avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy
Problem uploading to board.`

Does anyone know how I can fix this?

Did you try pressing the reset button twice?

Sounds like ModemManager is locking the port.

https://hackingmajenkoblog.wordpress.com/2016/08/24/diagnosing-arduino-problems-in-linux/

@IgnacioVazquez-Abrams Yeah I have tried pressing the reset button twice and then uploading the empty code quickly as soon as the port is identified but no luck

@Majenko That blog post seems like it's about accessing ports, I have access to my COMPORT and I can get my board info from the ide, so the ports aren't the issue.

Trust me. Look at the modem manager part.

You plug the board in (or it is reset to enter the bootloader). Immediately modem manager opens the port and tries to configure it, which means you can't since it's busy. It fails, since it isn't a modem, and releases the port. From that point you can access it, but it's too late for programming by then.

@Majenko I plug the board in and within 500 miliseconds it starts typing several strings onto the computer which is I programmed it to be. Now from my understanding to completely reset the board I need to have an empty sketch on the ide, press the reset button on the board and click on upload on the ide but by the time It resets and connects to a port it's already typing things onto the computer so it's almost impossible to click reset before 500 miliseconds.

It typing things won't make the port be busy. Only software running in Linux can do that, and the only software that is normally doing that is ModemManager.

@Majenko I will try to reset it on MacOsx see if I get the same error.

managed to fix it @Majenko using the Mac OSX Arduino IDE even after my code executed it seems it is modernmanager on Linux, every time I would hit upload on Linux it would rerun my code on the board almost as if it it was hitting the reset button. But on mac all I did was wait until the code finished running, and then I hit upload and it worked!

@Majenko: you should have mentioned modemmanager, save the poor guy some time...

@dandavis You think? ;) Maybe I should have mentioned modemmanager instead.

haha post an answer I will accept it


text:
How to create a library from scratch?
Good morning. I have a problem that I hope you understand. I'm trying to create a library from scratch. I've read and watched most videos and documentation that are on the internet. I can not understand and I'm not able to make one.
I hope someone can help me create a library that only shows a message that says "Hello World" in the serial port and give me the code if they are so kind. Also, it would be good if they could explain it to me.
I insist I know of many programming languages and realize this has made me a problem. I just need the code of the 3 parts so I can analyze it and understand it. I wait for your help.

A library is just c and c++ source files that contain code. What part of that do you not understand?

Think of a library as a class and you are calling that class with its subclasses, methods, and attributes from your script.

It complicates me to create the files with the code

Also, giving out code won't help someone learn it. You should learn about what algorithms are and learn how to plan out certain codes. No one goes into programming with a cold turkey. When you create a library, you need to think about what needs to get done and how you're going to get it done. You need to plan out on a piece of paper or chalkboard, write flow diagrams of particular objectives and methodology and write some pseudo code before you actually starting writing a program. If you do this, I guarantee it will help. Syntax is the hardest part about programming but you can research that.

I know C ++ but in Arduino there are very few clear references to help that can create a library

For actually learning how to use the Arduino IDE to create a library, check out this video. Sorry if that's what you were asking in the first place.

Is it possible to change some colored words?

A simple example...
Create a folder named My_Library, and place it in the Arduino/libraries folder
Create a sketch named My_Library.h and add the following:
#ifndef __My_Library_H__
#define __My_Library_H__
#include "Arduino.h"

//example 1
#define myhello1() ( { \
   Serial.println(F("Hello World"); \
Serial.println(F("Hello World again"); \
} )

//example2
void myhello2() {
 Serial.println(F("another Hello World");
Serial.println(F("another Hello World again");
}

#endif

Place the the sketch in the "My_Library" folder
In the beginning of your sketch, add
#include <My_Library.h>

Then, wherever you want, add the following:
//example 1
myhello1();

//example2
myhello2();

I have not tested the above, but it should work fine.  Regardless, this gives you a reasonable starting point.
For your last question concerning word colour, research "Arduino Libraries" regarding the "keywords.txt" file.


text:
Simple 2 Servo Synch
I have two servos connected to an Arduino, They work fine if i write to them one by one so the wiring is all correct. I have seen a lot of examples here but none are facing the same issue. I have a simple for loop with Servo.write() on two servos (Facing each other) one going clockwise and the other going counterclockwise. I just want them to rotate at the same time and i cannot connect them to the same signal line since their movement is opposite.
My Code Is:
 for(int pos = 0; pos < 90; pos += 2)
 {
     delay(200);
     int pos7 = 90-pos;
     pos7 = pos7*(-1);
     myservo6.write(pos);
     myservo7.write(pos7);
 }

What Is Happening
Both the servos go to the "same position" (if one is at 90 the other is at 0 etc.. ) Yet one goes there slow and the other goes super fast(not affected by delay). Even though my delay should affect both servos.
If i remove the delay they both go to the same position yet very fast. What i need is for them to move together slowly to the position.

Like most Arduino libraries, the documentation for Servo is horribly, inexcusably incomplete.   You might try splitting your delay to put say 3 or 4 milliseconds of it in between the servo writes - if there is an undocumented interaction in how the pulses are actually generated, that should accommodate it.

Servo's limited documentation does however say that it accepts values in the range of 0-180; your attempt to write negative numbers to it seems improper, and may be causing an odd outcome, either horribly mistimed pulses, or perhaps no valid pulse until you reach 0 at the end and finally generate a position the "reversed" servo can begin moving to.

That was it ... i hadnt realized until u said "negative numbers" that i had it reversed ... instead of int pos7 = 90-pos; its int pos7 = pos-90; ... thank you @ChrisStratton

The Arduino Servo class is intended to accept positive values only, in the range of 0-180.
In addition to reversing the values for one servo by subtracting from 90, your code is also negating the values by multiplying by negative one.
That results in an invalid argument to the Servo function.  It's unclear exactly what happens, but likely possibilities include an invalid pulse, or no pulse at all.
At the end of your for loop, you subtract 90 from 90 producing zero, and invert it to still zero.  Zero is a valid input to the Servo function, so a valid output is produced and the "reversed" servo finally has a position it can seek to.


text:
Communicating with I2C DAC (LTC2631)
Firstly, let me say that I'm new to using I2C devices, especially with Arduino. I have an 8-bit DAC (LTC2631) that I'm trying to control with an Arduino Uno. I thought I would be able to use the standard Wire library protocol to talk to it, but I'm not getting any response. Here's what I've tried:
#include <Wire.h>

void setup() {

    Wire.begin();
}

void loop() {
    Wire.beginTransmission(0x11); //specify device's address

    Wire.write(150); //send a test value

    Wire.endTransmission();
}

Am I missing something obvious? Or are not all I2C devices compatible with  Wire?

did you check pins with here >

Start with a i2c scanner. This one: https://playground.arduino.cc/Main/I2cScanner or the one on this page: http://www.gammon.com.au/i2c Get the pins and wiring correct so the i2c scanner detects the chip. Only if it is detected by the i2c scanner, then you can try to talk to the chip.

@Jot Thanks! That sketch was really helpful. I was admittedly a bit afraid that I had the address wrong, but it shows up exactly as I had thought. So now I just have to figure out what's wrong with how I'm trying to communicate with it.

When the i2c scanner detects the chip, then the I2C is working. Read the datasheet, you need to send three bytes (not just one). The first byte has the C1,C2,C3,C4 in the highest bits, the other two bytes have the data.

Software:  Wire should be fine.  Of course, you usually will want libraries for each device.  This particular ADC is designed for automotive use and I could not find a specific library for it so you are correct that you will need to speak with it directly.  Here is the DATASHEET
I2C Hardware:  On the Arduino Uno, SDA is A4 and SCL is A5.
One thing you almost always have to do with I2C is to provide a 10K pull-up to +5 on each pin (SDA and SCL) - I use a small breadboard whenever I use I2C, so I have power, ground, A4 and A5 available for pullups and multiple devices.
The reason for this is that the I2C bus is active-low.   It signals by pulling the pins low in sequence to communicate.
If you already had the DS3231 RTC module on the same bus, which apparently you do not or you would not be asking this question, then you do not need your own pull-ups because the RTC includes them internally.

It might be easier for you to use a different I2C ADC such as the ADS1115.
Here is a generic search that shows the module:
https://smile.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=i2c+adc
Here is a generic search which shows the software side:
https://www.google.com/search?q=arduino+ads1115+ADC+library+download

When you say talk to it directly, do you mean send it the data in the format outlined on page 22 of the datasheet, byte by byte?

Yes.    For instance, think about how you use the serial port.   Serial.begin(); then Serial.println(x);  The Serial library is handling all the byte-by-byte and bit-by-bit stuff.  I searched a lot and couldn't find an Arduino library that would make it easier for your device like that.  Back to the OP, though,  I suspect your only problem was the lack of proper pull-ups on the A4 and A5 lines - 10K to +5 on each.  Armed with the datasheet that explains how the thing communicates, byte-by-byte might not be so bad.  If you really want to make this thing work.

I agree that the first step (after adding pull-ups), is to run the IP Scanner program and make sure it responds.  When it does, then you can go from there, with confidence that you are using the correct address..

Even with the pull-ups connected, I couldn't get a response from it. :(
I think I'll just find a similar DAC that's documented with Wire. Thanks for the help though!

Darnit.    Anyway, look at my answer where I recommend the one I would use.


text:
Hardware interrupts for buttons not directly assigned to pins
The Adafruit LCD shield offers an LCD and access to 4 button, using only a two wire connection with the Arduino.
This is achieved with the MCP23017 I2C port expander IC.
These buttons are not directly assigned to pins, since only two pins are required for the whole communication, via the I2C protocol.
Can i use a hardware interrupt with any of the 4 buttons?
If not, is there any workaround to trigger an interrupt when one of these buttons is pressed?
PS: I am using Arduino Due

The MCP23017 has two interrupt outputs. The Adafruit shield however doesn't bring out either of those two pins. You could solder a wire between one of these pins and one of the unused arduino-header pins.

No, you can not while keeping the shield intact but it's possible I think.
https://learn.adafruit.com/rgb-lcd-shield/downloads
Here if you see the schematic and fabrication print, you will see that buttons are connected to MCP23017 I/O port. Now if you can connect to the MCP23017 pin corresponding to button you may detect the voltage change. This can be used to trigger interrupt.


text:
Using ESP8266 to send email. However "HELO" responds with "ERROR". Possible cause?
I am developing a sketch that uses an Uno and an ESP8266 to send email via smtp2go.  However "HELO" responds with "ERROR".  What might be the source of the problem?
To explore this, I created another sketch that simply sends commands to the ESP8266, and displays the results.
The wifi connection seems fine, as does the SMTP Server connect to mail.smtp2go.com.
However, the next command issued "HELO 10.1.0.35" provides a response of "ERROR".
The ESP8266 is  mounted on an ESP-01 board, and set @ 9600 baud.  have tested with different chip sets.
I have also tried using Gmail [smtp.gmail.com,465 ], but results are the same.
[I know that an ESP8266 can be used stand-alone.  However the final sketch requires 13 data pins.]
Output from sketch:
"ESP8266_ATcmdtest", compiled on: Jun  8 2017 at 17:58:18
Running on: Arduino UNO: ATmega328P

__________[ Disable echo (Echo sends back received command before response) ]__________
__________[ ATE0 ]__________
Response buffer:
OK

__________[ Delete server ]__________
__________[ AT+CIPSERVER=0 ]__________
Response buffer:
no change
OK

__________[ Restart the module ]__________
__________[ AT+RST ]__________
Response buffer:
OK
0,CLOSED
WIFI DISCONNECT
bB׆QR⸮⸮⸮ȤRN⸮ɥRL⸮H⸮⸮N⸮⸮d#@⸮⸮
WIFI CONNECTED

__________[ Check Firmware type [Responds with: AT version:1.2.0.0(Jul  1 2016 20:04:45) ]__________
__________[ AT+GMR ]__________
Response buffer:
AT+GMR
AT version:1.2.0.0(Jul  1 2016 20:04:45)
SDK version:WIFI GOT IP

__________[ Lists available APs ]__________
__________[ AT+CWLAP ]__________
Response buffer:
AT+CWLAP

+CWLAP:(0,"KCTcircuit2",-47,"08:bd:43:ff:6a:0c",1,21,0)
+CWLAP:(3,"49KHC",-88,"70:f1:96:66:29:ef",1,11,0)
+CWLAP:(3,"KCTstudy",-49,"04:a1:51:bf:6b:30",5,-11,0)
+CWLAP:(3,"Linksys05761",-75,"b4:75:0
e:64:54:b1",11,21,0)
+CWLAP:(3,"Pccd_main",-91,"14:91:82:83:f8

__________[ Get local IP address, e.g., 192.168.4.1 ]__________
__________[ AT+CIFSR ]__________
Response buffer:
AT+CIFSR
+CIFSR:STAIP,"10.0.0.4"
+CIFSR:STAMAC,"5c:cf:7f:34:

__________[ Set Station mode ]__________
__________[ AT+CWMODE=1 ]__________
Response buffer:
AT+CWMODE=1
OK

__________[ Set current multiplex mode ]__________
__________[ AT+CIPMUX=1 ]__________
Response buffer:
AT+CIPMUX=1

OK

__________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTstudy","[pw redacted]" ]__________
Response buffer:
AT+CWJAP="KCTstudy","[pw redacted]"
WIFI DISCONNECT
WIFI CONNECTED

__________[ Prints the SSID of Access Point ESP8266 is connected to. ]__________
__________[ AT+CWJAP? ]__________
Response buffer:
AT+CWJAP?
busy p...
WIFI GOT IP

OK

__________[ Get IP address of ESP8266 station, e.g., 10.0.0.4 ]__________
__________[ AT+CIPSTA? ]__________
Response buffer:
AT+CIPSTA?
+CIPSTA:ip:"10.0.0.4"
+CIPSTA:gateway:"10.0.0.1"

__________[ SMTPServer connect ]__________
__________[ AT+CIPSTART=0,"TCP","mail.smtp2go.com",2525 ]__________
Response buffer:
AT+CIPSTART=0,"TCP","mail.smtp2go.com",2525
0,CONNECT

OK

+IPD,0,70:220 mail.smtp2go.com ESMTP Exim 4.87 Fri, 09 Jun 2017 00:59:07 +0000

__________[ Get information about connection ]__________
Response format  is:
STATUS:stat [ 2: Got IP, 3: Connected, 4: Disconnected]
+CIPSTATUS:id,type,addr,port,tetype [type: TCP, addr: IP address]
OK
__________[ AT+CIPSTATUS ]__________
Response buffer:
AT+CIPSTATUS
STATUS:3
+CIPSTATUS:0,"TCP","173.255.233.87",25

__________[ HELO ]__________
__________[ HELO 10.0.0.8 ]__________
Response buffer:
HELO 10.0.0.4
ERROR

Sketch code
#include <SoftwareSerial.h>

// _______________________________
#define sendit(x) ( { \
    Serial.print(F("__________[ ")); \
    Serial.print(x); \
    Serial.println(F(" ]__________")); \
     esp8266.write(x); \
   esp8266.write("\r\n"); \
     delay(300); \
     Serial.println(F("Response buffer: ")); \
     for (int i=0; i <= 99; i++) { \
         memset(buffer, 0, sizeof(buffer)); \
         delay(10); \
       bcount = esp8266.readBytes(buffer, sizeof(buffer)); \
           if (bcount == 0)  i = 100; \
           else { \
    if (bcount > 1) Serial.println(buffer); \
    delay(300); \
      } \
    } \
  } )

// _______________________________
#define desc(x) ( { \
    Serial.println(); \
    Serial.print(F("__________[ ")); \
    Serial.print(F(x)); \
    Serial.println(F(" ]__________")); \
  } )

// _______________________________
SoftwareSerial esp8266(11, 12); // RX, TX
char buffer[200];
String SerialReadBuffer = "";
char SerialByteIn; // Temporary variable
boolean SerialEnd = false;
int bcount;

// _______________________________
void setup()
{
    Initialise();
}

// _______________________________
void loop()
{
}

// ____________________________________________________________________________________________________
void Initialise()
{
    SerialReadBuffer.reserve(64);
    esp8266.begin(9600);
        // esp8266.begin(115200);
    Serial.begin(9600);
    CommandList2();
}

// ____________________________________________________________________________________________________
void CommandList2()
{
    desc("Disable echo (Echo sends back received command before response)");
    sendit("ATE0");
    desc("Delete server");
    sendit("AT+CIPSERVER=0");
    desc("Restart the module");
    sendit("AT+RST");
    desc("Check Firmware type [Responds with: AT version:1.2.0.0(Jul  1 2016 20:04:45)");
    sendit("AT+GMR");
    desc("Lists available APs");
    sendit("AT+CWLAP");
    desc("Get local IP address, e.g., 192.168.4.1");
    sendit("AT+CIFSR");
    desc("Set Station mode");
    sendit("AT+CWMODE=1");
    desc("Set current multiplex mode");
    sendit("AT+CIPMUX=1");
    desc("Connect to AP");
    sendit("AT+CWJAP=\"KCTstudy\",\"[pw redacted]\"");
    desc("Prints the SSID of Access Point ESP8266 is connected to.");
    sendit("AT+CWJAP?");
    desc("Get IP address of ESP8266 station, e.g., 10.0.0.4");
    sendit("AT+CIPSTA?");
    desc("SMTPServer connect");
    sendit("AT+CIPSTART=0,\"TCP\",\"mail.smtp2go.com\",25");
    desc("Get information about connection");
    Serial.println(F("Response format  is: "));
    Serial.println(F("STATUS:stat [ 2: Got IP, 3: Connected, 4: Disconnected]"));
    Serial.println(F("+CIPSTATUS:id,type,addr,port,tetype [type: TCP, addr: IP address]"));
    Serial.println(F("OK"));
    sendit("AT+CIPSTATUS");
    //
    // Problems start here
    //
    desc("HELO");
    sendit("HELO 10.0.0.4");
    Serial.println(F("__________________"));
}

in my (limited) experience, anything beyond pushing and fetching http transactions is flaky and difficult on the AT firmware. You can run a nice custom sketch on the ESP and still use serial to talk to the ardunio, using your own commands instead of the AT ones. The debugging differences are extreme; total flexibility and intermediate logging vs a "black box" with cryptic returns. that also lets you use the pins on the ESP if needed, store 3mb of data locally, etc etc...

Most commercial SMTP servers will not accept email from machines not DNS registered. This is to avoid receiving/distributed spam from bot infected PC. I doubt they will accept mail from a 10.x.x.x IP address, because they are not routable. If you are going thru a NAT router, your Internet address will be other. Are you using a local, private SMTP server that you can control?

@Look Alterno, I am not very savvy on this subject, but no NAT router or private SMTP server.  I have this problem only when using with the ESP8266.
I have 3 other Arduino systems using  Ethernet shields instead and accessing the same network.  These work fine for sending the same kind of Email.
For the ESP8266 system, there is simply no Ethernet cable connect available.  I have still not sorted this out yet.

I think @majenko has the right answer already. My comment is for others thinking about sending mail. As you are using a comercial paid service (smtp2go.com) that expressly allow that, my comment doesn't applied to you. You get it right.

You're sending the word "HELO" to the ESP8266 and the ESP8266 is, quite rightly, saying "What?!?! I don't know the command HELO!"
You have opened a connection in multiple connection mode with ID 0. You then have to send data through that connection.  For instance:
AT+CIPSTART=0,"TCP\","mail.smtp2go.com",2525
OK
AT+CIPSEND=0,15
> HELO 10.0.0.4<CR><LF>
SEND OK

Using a protocol like SMTP in this mode is not easy. Better would be to use "unvarnished" mode:
AT+CIPSTART="TCP","mail.smtp2go.com",2525
OK
Linked
AT+CIPMODE=1
OK
AT+CIPSEND
> HELO 10.0.0.4<CR><LF>
250 mail.smtp2go.com Hello 10.0.0.4 [23.114.28.226]
MAIL FROM: "Foo Bar" <foo@bar.com>
250 OK
... etc ...
QUIT
221 mail.smtp2go.com closing connection

Note that just sending commands and blindly printing the responses isn't really the best way to go about it. You should be actively interpreting the responses that you get back and making decisions based upon them. Especially when you're in SEND mode. The SMTP protocol is two-way. You need to know what the responses are saying and what that means for your SMTP session.

Before sending "HELO 10.0.0.4" ... you should send a CIPsend command with the length of your sentence + 2
Here is the right command sequence:
AT+CIPSEND=4,15
HELO 10.0.0.4

Best regards


text:
DHT11 not giving correct value if I attaching a servo motor
So I am using a servo motor and 2 DHT11s in my Uno, when I attach them separately it works well. But when I try to attach both, servo working correctly but DHT11 giving weird number(DHT11 was side by side, one gives 22oC and another gives 30oC sometimes -999).
I am powering both devices by using 5V and GND from arduino to a breadboard and then DHT11 and Servo power pin to the breadboard. All signal pin are direct from devices to arduino.
Am I power both devices wrong? or is there's a way to solve this?
Thanks
EDIT:
this is the code
#include <Servo.h>
#include <dht.h>

dht DHT;

#define DHT11_PIN 7
#define DHT11_PIN2 6
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

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

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

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

  int chk = DHT.read11(DHT11_PIN);
  Serial.print("Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("Humidity = ");
  Serial.println(DHT.humidity);
  int chk2 = DHT.read11(DHT11_PIN2);
  Serial.print("Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("Humidity = ");
  Serial.println(DHT.humidity);
  delay(1000);
}

For the servo, I used GWServo S03N STD.

Maybe the moving servo drains too much the power, so the DHT are underfed. Try powering the servo separately, or at least add a capacitor on the 5V on the breadboard (maybe 100nF in parallel to a 100+ uF)

It could be a code error, but my crystal ball isn't working today and I can't see your code.  It could be a circuit issue, but as you know my crystal ball is down so I don't know.  It could be a power problem, but the force is not with me and I don't know what servo model you have so I don't know.  The more complete the information you supply is, the faster and more accurate the answers will be.

@frarugi87 ah yeah, I will try that,thanks for the suggestions

@CodeGorilla sorry, I added the code and servo model.

@NaufalB - sorry to be a pain, but what DHT library are you using, it doesn't look like the AdaFruit one.  Is it this one http://playground.arduino.cc/Main/DHT11Lib ?

@CodeGorilla no problem, I use the one from this site http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/

Your code looks like there is no bug in there.  You might want to look at using a library that lets you assign a pin in the constructor, so you don't need to read from a specific pin.  There might be something internal going on that you don't know (or want to know) about.  As for the movement of the servos do you realise you a rotating 181 degrees int p = 0; p <= 180 is 181 degrees, drop the = if you wanted 180.  Also pos++ is the same as pos += 1 but requires less of those tiring key presses :)
You say that the DHT11s work on their own.  The servo works on its own.  So it not a hardware fault.  I assume its not a wiring fault, but please double check.  That means it has to be something to do with the power.  If you are powering the servo from a digital pin then this is unlikely to work, try powering it from the 5V output pin on the other side of the board.
However if you are powering it from the 5V output pin and it doesn't work then you need to power it from a external source, a mobile phone charger will do (if you have one you can chop the plug off).  The problem with using external PSU is you must tie the grounds together.  Doing this means the Arduino and the external device agree what zero volts is and things work.  This is easily done by taking the gnd of the PSU and putting it in the GND connector of the Arduino and the taking the GND for the servo from the other GND on the Arduino.
I hope that all makes sense, if not tell me what you need clarifying.

Yeah, I will try to power it from external source. Thank you for the suggestion, really help me :)


text:
PCA9685: how "unset" PWM signal?
I use my Arduino with Adafruit PCA9685 servo controller. To set PWM signals I use the provided library: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
It allows easily set PMM signal and works good. But how can I "unset" PWM signal for a certain pin?
If a PWM siganl is active, the servo stucks on the current position and can't be moved by hand, but only by setting other pulse length. So I need to move servo and then "free" it.

I'm not really into servos... do they "release" when just the duty cycle is 0% or 100% (this can easily be done with your PCA9685)? If not, the only way is switching off the power supply for that servo.

Did you find a solution? I'm having the same problem.

You can try to send no "ON" time to your output pin on the PCA9685.
So, you start the "ON" at 0 and stop the "OFF" at 0.
void freeServo(uint8_t servoIdx)
{
  pwm.setPWM(servoIdx, 0, 0 );
}

You could try changing the corresponding pin from output to input.
To be sure not to disturb other comfigurations you could do direct port manipulation.
void servo_off() {
  DDRD &= ~(1<<PD5);
}

void servo_on() {
  DDRD |= (1<<PD5);
}

This assumes you use pin PD5 for the pwm signal. Adjust the "D" in DDRD and PD5 so it matches the port in use as well as the pin number.
Of course, you need some additional user input like a button to trigger calls to those functions.

PCA9685 is controlled over I2C and the question is about the Adafruit library for the PCA9685 module

Are your servo's control pins active high or active low?
From the library code at https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library/blob/d265f74fc0e66632e6dafc787c95b008f3245550/Adafruit_PWMServoDriver.cpp#L242  it looks like there are special on&off values of setPWM(pin,on,off) that turn the servo fully on or fully off, and how they work they depends on whether the servo pin is active high or active low.
unsigned byte idle = CertainPin;

servoController01.setPWM(idle, 0, 4096); // fully off Active high
// servoController01.setPWM(idle, 4096, 0); // fully off Active low

or with the better documented setPin():
servoController01.setPin(idle,0,false); // Active high
//servoController01.setPin(idle,0,true); // Active low

Unluckily, AFAIK, the servo powers the motor even when the PWM signal is not applied. So "removing" the PWM is useless.
You will have to "turn off" the servo by removing the power. To do this, use a transistor (usually servos are more current-hungry than arduino can bear). When you want to "free" the servo, remove the power and it will be "free".

you are wrong
if I connect servo to my assembly it is "free" until I havent PWM set
aslo I can free all servos by sending reset command to PCA9685
but my task is to "free" just one particular servo: there is the problem

I got same problem, searched around but found no answer, so I looked into the source code and found that you simply have to set the angle of the servo to 'None' to stop sending PWM pulses to the servo. For example, if your servo uses channel 14 on the PCA9685 board:
kit.servo[14].angle = None

It sounds like you're talking about python, or something like it, and maybe some other library and not anything to do with the question.


text:
Compilation issues on Arduino Due
I wrote an code on Arduino and I getting compilation errors. I am using Arduino Due . I wrote the following code :
void setup() {
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit

}

void loop() {

  // code
}

But compiler gave me the following errors :
'analogReadResolution’ was not declared in this scope
‘analogWriteResolution’ was not declared in this scope
‘DAC0’ was not declared in this scope

I'm using Arduino 2:1.0.5 (on Linux). The board list doesn't show Arduino Due (USB programmable).And I don't have Board Manager option. How do I install Arduino SAM Board to compile the program ?

Did you try to update the Arduino library/IDE? Afaik the analogRead/WriteResolution functions should be known.

I installed it today itself and it v2:1.0.5. If I have to update the it through terminal how do i go about it ?

In case you installed it, it is not needed to update.

According to the Arduino - ReleaseNotes,

ARDUINO 1.5 BETA - 2012.10.22

First release for the unified IDE for both AVR 8-bit and ARM 32-bit   (SAM3 CPUs) architectures.
This release include the SAM Arduino Core used in the Arduino Due   Board.

So your 1.0.5 version does not allow for Due compilation. Download the most up-to-date version and you will be fine (you will be able to install SAM support).
Then you will be able to at least compile. If you have other problems with your code, please open another question here (in order to keep the one-question-per-post behavior of this website).
Don't install arduino from the debian repository, since that version is not updated regularly. Use the website version

I updated it to the latest version but I still can't find the Arduino Due board. When I select the board manager option it throws an error saying Error downloading http://downloads.arduino.cc/packages/package_index.json

@SamThornton did you try google? Most of the times other users report this is 1) a spyware, 2) a connection issue, 3) a JAVA misconfiguration. I think 1 is not applicable to linux. Try accessing the file from a browser (if you can't it is an internet issue). Or verify if you are behind a proxy. As a last resource, purge the old arduino install, clean the new one and then reinstall, reboot and try again

I finally found the error. It was due to the fact that the Linux was set on Automatic Proxy.

@SamThornton good to know ;) Glad you managed to fix it


text:
Differential voltage measurement with Arduino UNO
EDITED:
I bought a very sensitive (and expensive) pressure sensor which requires differential analog measurement. I am an amateur hobbyst and a total beginner in Arduino so I would like to ask some advice on how to connect the device so nothing would be damaged.
In the figure below is the scheme which I've got form the manufacturer along with schematic on how I am going to connect that:

the wire colours are as in the provided device,
the symbols are as they were attached to the wires,
the resistor was provided and connected by the manufacturer.

As far as I understood the sensor manual I should connect the device to analog pins as in the schematic below, and read the A0 and A1 and subtract the signal values. Is that fine? Should I connect the wire going to A1 to Arduino GND as well?

Or should I connect the GND instead of A0 line in the image below?

EDIT: Original connection scheme from the DS and link to the CL1A sensor www and  link to the sensor datasheet (only in Polish)
Yeah, possibly I misunderstood something.

I have a very detailed (and impressive) answer, but I'm not going to tell you what it is.

I'm a bit puzzled about the reason why you connected ground to the + terminal and +24 to the - terminal of the power supply... And why the A1 pin is connected to ground... I think you'd better search the datasheet better before flipping the switch

@frarugi87 that is from the connection scheme which was provided by the manufacturer. I only added the Arduino to what i've got from the device provider

Either the manufacturer is clueless or you misinterpreted what they were telling you. Either way I sense a Smoke Event on the horizon.

@Misery well, I'm a bit suspiciuos about this... maybe you read it in a wrong way, maybe the DS is wrong, or who knows. We don't have the datasheet or even just the sensor part number, since you did not provide any info... Majenko anticipated me but, as you can see, the reasons we thought of are the same... You should either provide more infos or... Well, Smoke Event is pretty easy to understand

Notice how your schematic doesn't match the original?

@EdgarBonet Instead of A1 there should be GND pin? Lol, I get it! Now

Supply + goes to "+24V", supply − goes to GND, the white sensor wire is labeled "+S" (S like "signal"), not "+5V".

Please avoid editing your original post  by deleting the older parts, otherwise the answers become useless. If you have to add something, edit at the bottom part of the questio (modifying what you have already written can be done only for improving the question, not for correcting it)

if you have an expensive sensor, it's kind of silly to use such a low res ADC on it, when you can get a full-range 16-bit (64k levels vs 1k) ADS1115 for under $5 that go rail-to-rail, up to 5.5-ish volts

@dandavis You're absolutely right. But now I am using Arduino for testing. If everything works properly I will switch to proffesional ADC

I'd suggest first using a multimeter to measure the signal voltage you get out of the sensor. Less chance of getting things wrong, that with a power Arduino.

Is there a question here?

According to the update, which shows the datasheet, you have one BIG mistake and one smaller mistake.
The big mistake is that you inverted the polarity! Look carefully. The +24V wire goes to the + pin of the supply, while the ground to the - pin.
Moreover the DAQ board has a differential one, but one of them is tied to ground.
So I suggest you to attach the wires in this way:

Thanks, that seems reasonable. I will check that on Monday, and if there is no "Smoke Event" I will let you know.

You do not need to do any kind of differential measurement here. The
Arduino analog input measures voltages relative to ground. Then, as long
as the Arduino and the power supply share a common ground, you should be
fine.
On the other hand, you may need a voltage divider. I have seen a few
sensors interfaced the same way (GND, +24V and signal), which output a
voltage between 0 and +10 V. That could fry the Arduin, and maybe
also the sensor. Check the datasheet to see the maximum voltage the
sensor can output, and use a voltage divider to get that safely into the
0 – +5 V range.

The output of that sensor is an industry standard "4-20mA" (known as a current loop). That means that the current output from the +S wire varies between 4mA and 20mA depending on the pressure. You need to convert that current into a voltage so that the Arduino can sample it.
Note that your attempt at a schematic is completely backwards. You must connect the +24V pin to +24V on a power supply. GND must be connected to GND on the power supply, and also GND on the Arduino.
Now for the signal. Yes, a resistor is the simplest way of converting a current into a voltage. Simply pass the current through the resistor to ground and a voltage will be dropped across it.
According to Ohm's Law, V=IR. Or, to turn it around, R=V/I.
Your maximum current is 20mA (0.02A) and your desired maximum voltage is 5V. So you can put those values into Ohm's Law and get a resistance:

R=V/I = 5/0.02 = 250Ω.

Now 250Ω resistors aren't that common, but 220Ω ones are. So what would that give us?

V = IR = 0.02 * 220 = 4.4V

Perfect. And at the lower (4mA) end of the range?

V = IR = 0.004 * 220 = 0.88V.

So with a 220Ω resistor you would get a voltage reading of between 0.88 and 4.4V on the Arduino.
(Note: the datasheet recommended 100Ω would be more suitable for a 3.3V Arduino - it would give between 0.4V and 2V).
For safety I would also include a small inline current limiting resistor and 5.1V zener diode. If the 220Ω resistor should fail or become disconnected you would get the full 24V (or somewhere about there) across the Arduino's A0 pin. It's limited to 20mA so may not be a problem, but you can't be sure, so best to add that to clamp the voltage to a maximum of 5.1V. After all, a zener diode is cheaper than a new Arduino.
And to clarify - the schematic:

simulate this circuit – Schematic created using CircuitLab

Which pressure transducer is it really ? The "CL 1A" can be made as version "R1" with strain gauge output of 10mV or with a processing unit inside for version "3I4" (4-20mA output), "3U1" (1V output), "3U5" (5V output), "3U10" (10V output).

@Jot Well, the circuit provided can only be for the 3I4 4-20mA version. It makes no sense with any of the others. Plus that will be the most common variant since it's industry standard.

We need a photo of the pressure transducer to be sure (assuming the type is written on the pressure transducer).


text:
Creating a sine wave with a DAC and feeding it back
I want to produce a digital sine wave, send it to DAC0, and then receive it back as input on A0 and plot the graph. I am using an Arduino Due. I wrote the following code:
#define maxSamplesNum 120
#define Sample 50000000/maxSamplesNum  // sample for the 50Hz signal expressed in microseconds

static int Table[maxSamplesNum] =                        // lookup table  for sine wave table
  {
    0x7ff, 0x86a, 0x8d5, 0x93f, 0x9a9, 0xa11, 0xa78, 0xadd, 0xb40, 0xba1,
    0xbff, 0xc5a, 0xcb2, 0xd08, 0xd59, 0xda7, 0xdf1, 0xe36, 0xe77, 0xeb4,
    0xeec, 0xf1f, 0xf4d, 0xf77, 0xf9a, 0xfb9, 0xfd2, 0xfe5, 0xff3, 0xffc,
    0xfff, 0xffc, 0xff3, 0xfe5, 0xfd2, 0xfb9, 0xf9a, 0xf77, 0xf4d, 0xf1f,
    0xeec, 0xeb4, 0xe77, 0xe36, 0xdf1, 0xda7, 0xd59, 0xd08, 0xcb2, 0xc5a,
    0xbff, 0xba1, 0xb40, 0xadd, 0xa78, 0xa11, 0x9a9, 0x93f, 0x8d5, 0x86a,
    0x7ff, 0x794, 0x729, 0x6bf, 0x655, 0x5ed, 0x586, 0x521, 0x4be, 0x45d,
    0x3ff, 0x3a4, 0x34c, 0x2f6, 0x2a5, 0x257, 0x20d, 0x1c8, 0x187, 0x14a,
    0x112, 0xdf, 0xb1, 0x87, 0x64, 0x45, 0x2c, 0x19, 0xb, 0x2,
    0x0, 0x2, 0xb, 0x19, 0x2c, 0x45, 0x64, 0x87, 0xb1, 0xdf,
    0x112, 0x14a, 0x187, 0x1c8, 0x20d, 0x257, 0x2a5, 0x2f6, 0x34c, 0x3a4,
    0x3ff, 0x45d, 0x4be, 0x521, 0x586, 0x5ed, 0x655, 0x6bf, 0x729, 0x794
  };

int i = 0;
int sample;
int sensorPin = A0;
int sensorValue = 0;

void setup() {
  Serial.begin(9600);
  analogWriteResolution(12); // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12); // set the analog input resolution to 12 bit
}

void loop() {
  sample = 50;

  analogWrite(DAC0, Table[i]); // write the selected waveform on DAC0

  i++;
  if (i == maxSamplesNum)  // Reset the counter to repeat the wave
    i = 0;
  delayMicroseconds(sample); // Hold the sample value for the sample time
  sensorValue = analogRead(sensorPin);
}

I want to create a 3.3 V (P-P) sine wave but I don't how to set the amplitude in this wave.
Also I would like to redirect the sine wave output from DAC0 to the A0 Pin and plot the graph to check if generating the sine wave was successful.
How do I plot the graph ?
I uploaded the program but there was no result. I tried to read data from A0, but there wasn't any output. What am I doing wrong?

You just have to Serial.print() the ADC reading, either immediately (which will slow your signal generation), or after the fact (buffer the values, then print them all).

Possible duplicate of No Voltage output on DAC0

I ran your code unmodified and plugged in an oscilloscope to look at DAC0 (looks an OK sine wave) and A0 (looks flatline). Hope this helps.

Further to @Edgar's suggestion there is more information about the Arduino IDE [Serial Plotter] [https://arduinogetstarted.com/tutorials/arduino-serial-plotter#:~:text=Serial%20Plotter%20is%20one%20of,and%20visualizes%20data%20as%20waveforms]. Which I think resolves the "How do I plot the graph" part of your question. The oscilloscope test shows that your wave generation is working OK. If you would like further help about a loopback on A0, I suggest you show your wiring. Regards.

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


text:
Wiring an IR blaster+receiver board
I've salvaged this small IR blaster+receiver board from an old computer toy:

As you can see the board was connected to the main unit via a 4-wire cable labelled like this:

LED (yellow) (I guess this is the IR LED/blaster)
IR (white) (I guess this is the IR receiver)
VCC (red)
GND (black)

I'd like to use this board with an Arduino library like IRremote, but I am not sure about the VCC voltage and whether I need to add more components on the Arduino side.
UPDATE:
I've checked the LED with a multimeter and indeed it is a visible bicolor LED, so there is no IR blaster in this board. At this point, is there any good reason to keep the IR receiver on the board rather than just cutting it and reusing as a standalone component?

The receiver (the 3 pin part inside the metal case) appears to be a common IR receiver.  It is likely you can pull that part and use it as the IR receiver in many of the Arduino examples found on line.  The LED (3 pin part made up of only plastic???) is unexpected.  Most of the time IR LED are only 2 pin devices.  As IR LED are inexpensive it might be better to simply buy a new IR LED.

it should be ready to go, that the same stuff you find on new modules

I think the led on the left is just a (visible) indicator led. Since it's a three pin package, it's probably a bi-color one. Could you add a photo of the board, where the wires aren't obscuring part of the PCB? The MELF-diode is puzzling to me, as I was expecting it to be near the top/Vcc side.

5V is most likely fine. I've only seen datasheets for IR-receiver  that  accept a voltage of  5V or more.

You solved your problem.
You said

I checked the LED with a multimeter and indeed it is a visible bicolor
  LED, so there is no IR blaster in this board.

So, be kind, accept this answer so we can close your question.
I'm posting, not comment, only to get this out of the "unanswered".


text:
Bootloader and Boards Definition for Atmega2560V-8AU at 8 MHz / 3.3v
I am working on a home made project,where i am using Atmega2560V-8AU (note the suffix, this part has an 8 MHz maximum clock rate) as my main controller, supplying 3.3V to this chip.
I want this controller to work exactly same as standard Atmega2560-16AU like on Arduino Mega(perhaps at a slower baud rate on account of the slower clock)
Does there already exist a suitable bootloader image and board definition for an ATmega2560 operating from an 8 MHz crystal?
If not, what changes would need to be made to the usual 16 MHz bootloader and boards definition to support 8 MHz operation, both for the bootloader and for correct time functions and serial buad rates in sketches?

@Gerben - how do you propose the lower clock speed be handled?  If you are suggesting there is already an option for it, mentioning that would be clearer.

@Gerben - you seem to be ignoring the whole point of the question - the poster wants to use an atypical chip which cannot operate at the normal clock rate.  It either needs a custom bootloader to operate at a usual baud rate, or programming support for a slower baud rate.   Your responses so far have been the exact opposite of helpful.

In actual fact, the ordinary bootloader will work, but the problem will come when then trying to talk to it - it will be operating at half the expected baud rate due to the 8 MHz vs expected 16 MHz clock, so the usual board definitions won't allow the IDE to talk to it.  What the poster needs is a good board definition package for an 8 MHz Arduino Mega.

There is a fair amount of coverage here and elsewhere for 8 MHz / 3.3v usage of the ATMega328p - the situation with the 2560 will be similar enough that those solutions could be used as a model for the necessary modifications or workarounds, but of course an ATMega328p board package won't actually work on a 2560.

Hello,
I am sorry for not providing enough information my task! I am using 8Mhz crystal and the chip runs on 3.3V, I cannot upload bootloaders of Atmega2560-16AU which runs on 16Mhz cystal.
Yes! the ordinary boorloaders should work! but i need to change 16Mhz set to 8Mhz set somewhere in some files of ARduino IDE
How do i dot that.? and is there any more things i have to do like Fuses etc.?
and I am using my Arduino UNO as "Arduino as ISP" programmer in the list, which will have +5V on the SPI lines and I am running my target chip on 3.3V,
Does it hurts to my chip.?
Thank you

Sparkfun used to sell a board with this chip, and seems to still have downloadable resource at https://www.sparkfun.com/products/retired/10744 however, the way the Arduino IDE does things has changed over time, and those files may not work with a current one.  I believe there is now some drop-down menu support for various clock options for some boards, so that may be an alternate route.

thank you for reply,
I have tested with the above mentioned Sparkfun board with the files on bootloaders, But the board is not showing in the boards section.
Is there any chance of customising stock Arduino Mega bootloaders with this chip.?
Thank you

As I said, the way the Arduino handles board definitions keeps changing, so it unsurprising that the old one doesn't work with a recent IDE.  You'll need to find our figure out how to make a definition for a modern IDE (perhaps using the old one and new ones for an 8 MHz ATmega328p as guides), or (less preferably) use an old version of the IDE.

Thank you very much for reply, which version of arduino ide should I try?

If you want to use the old sparkfun files, one contemporary with them.  If you want to create something new, figure out what the latest stable version is, and combine what you can learn from the old sparkfun files and current guidelines for 8 MHz ATmega328p solutions to develop a configuration for an 8 MHz ATmega2560v.  You may also need to set brownout fuses appropriately for 3.3v operation.

hello, I have used this Megacore and it solved my problem
https://github.com/MCUdude/MegaCore

@MudassirHussain, then post your solution as answer (yes you can self-answer!), and accept it. This way, 1) The question won't be marked as unaswered anymore b) other users will benefit from you useful information. c) you'll gain reputation.

I have used megacore bootloaders, and it solved the problem


text:
Arduino Controlling a stepper motor
How can I get an Arduino to do the following to a Stepper Motor installed on a "Lead-screw" attached to my table-saw's Fence?

Turn the "lead-screw" clockwise when I press a given button, UNTIL I release the button.
Turn the same "lead-screw" counter-clockwise, when I press another button, UNTIL I release the button.
Adjust a "speed" knob, to control the motor's speed when the fence is moving; from very fast to very slow; and even stop when the control is completely counter-clockwise.
Turn a switch off, which will remove all control to the motor; so I can turn the shaft manually without resistance, whenever I do not want the fence to be under control of the motor.

That is ALL I need.
It is that simple. So what do I need? What do I need to purchase? I am a novice.

First you need to figure out the mechanical requirement, ie, how big a motor and what drive voltage which is determined largely by speed, and even if you want to directly couple the shafts or use timing belts for reduction and to ease mounting tolerances - none of which are really an Arduino questions. 3d printer parts are applicable to a certain light load range and readily available to get a tactile sense of. For more substantial tasks the are a lot of more expensive solutions for CNC machine tools. The Arduino part sounds like a simple combination of a stepper sketch and an analog read one.

patdee, I edited your question and removed an irrelevant paragraph.  You can post such paragraphs on arduino.meta.stackexchange.com if you wish.

I've got to ask here.  Why use a stepper?
This would be fairly easy with two button switches and a regular DC motor.  One switch provides power to drive the motor CW the 2nd motor drives it CCW.
You would still need to choose a motor with the right torque but IMHO this method would be WAY easier than using a stepper, and arduino, writing code, etc.

We can't tell you what to buy. We can help you understand how it will work, though, and what you should look for.
First off you need a suitable stepper motor. We can't help you with that. You need one that will a) connect to your lead screw in some way, and b) have enough power to drive the screw.  Maybe the robotics stack-exchange can help you better with that.
Once you have identified your stepper motor you need a driver that can control it. There's two kinds of stepper motor - "unipolar" and "bipolar" and the type of stepper motor you have chosen will determine the type of driver you need. Suffice it to say if you have a "unipolar" stepper motor you need a "unipolar" driver.
In brief: a bipolar stepper motor usually has 4 wires and needs a pair of H-bridges to drive it. A unipolar stepper driver normally has 5 or 6 wires and just needs beefy MOSFETs to drive it.
Your driver will, of course, need to be able to provide enough current to drive your stepper motor. For the finer details of the driver the electronics stack-exchange will most likely have the most expertise.
One further thing you will need is a potentiometer (and fancy knob etc) to set the speed.
Then it's just a matter of "gluing" everything together through the Arduino and writing the software.
How you write the software for the Arduino depends on  the driver for your stepper motor. There are libraries with examples for most types. Adding in an analogRead(...) and map(...) to convert the voltage from the potentiometer into a speed should be simple enough.

Thank you user37968. But there are a number of reason why I want to use stepper motors. To user Majenko♦, I gave ALL you need to determine what I need. I used the word "TABLE SAW FENCE". It should be assumed that I have installed a lead screw on the fence. Any sawyer knows that the fence is moved to the left or right and mine takes VERY little effort; because it rides on roller bearings. All the stuff you gave me was FAR and way above what I need. Thanks anyway for trying. patdee

@patdee Well I am sorry, but we are electronic engineers and makers, not "sawyers" (what are they? Do you mean carpenters?) I, and many others here, have no clue what a "fence" is in this context. To me a fence is what separates me from my neighbours, and I don't want it to move. My answer contained all the information you need to know to use a stepper motor. If you don't want to know that kind of information then you are looking for a ready made product and you don't want to be asking about that here.