text:
Can't use Arduino nano as ISP because it can't read the Device signature
I programmed the 8mhz internal oscillator Bootloader to a new Arduino Nano with another Arduino nano running the ISP Sketch, wich worked fine the first time(Arduino as ISP selected as programmer).
(I wanted to test it befor i want to burn this Bootloader on an Empty 328p-au uC.)
But now since I received the 328p-au uC's i tried the same thing, to burn the Bootloader to the epty uC's but somehow it can't read the device signature, neither from a fresh arduino Nano or another avr(At least that is what avrdude said). I wired everything exectly like it was written in the ISP Sketch.
Here is one of the error messages i received when I was trining to Burn the standard 16mhz Bootloader:
     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

     Fehler beim Brennen des Bootloaders.
     avrdude: AVR device initialized and ready to accept instructions

     Reading | ################################################## | 100%          0.02s

     avrdude: Device signature = 0xff0000
     avrdude: Expected signature for ATmega328P is 1E 95 0F
     Double check chip, or use -F to override this check.

     avrdude done.  Thank you.

So what am I doing wrong?
(Using -F is what I tried but it didn't work, except the first time I programmed the 8Mhz Int. Oscillator Bootloader)
What stand out to me is that there was nothing happening on the MISO line. Here is a screenshot from my Logic Aalyzer software: ibb.co/hWXrpp7
And here is an Image of my setup(the right Arduino is the programmer and the left one has the empty uC soldered onto it): https://ibb.co/zXQFmwR
I am relative new to Arduino, so I hope some of you can help me with that.

do you have "Arduino as ISP" programmer selected?

Yes I did... Same error message.

so do you use other Arduino with "Arduino as ISP" sketch or not? because then there are no other programmer options for "same error". show in Question the output with the right programmer selected

Yes I use the "Arduino as ISP" Sketch and have " Arduino as ISP" Programmer selected. "Same error message" I just tried to programm by using avrdude directly to implement the idea of the other guy who answered but it didn't help.

do you have a capacitor on programmer Arduino to prevent the reset at new USB connection?

A new AVR chip from the manufacturer has some (so called) fusebits set. These prevent the MCU from being programmed or read out. This might be an explanation why you can not read out the signature. But the programmer should set these bits if you use it to upload a bootloader.  Here is a link from a guy that was unhappy with the documentation he found in the internet. He wrote his own
Howto: https://makersportal.com/blog/2018/3/15/arduino-internet-of-things-part-1-burning-the-arduino-bootloader-onto-a-blank-atmega328p-chip-using-the-arduino-uno

As @Jurai mentioned you need a ~ 100µF capacitor between the Reset Pin and the Ground of the programmer arduino. This is essential. I do not see this in the schematics of the link I pointed you to. So for newer UNOs or Nanos this might be integrated on the board. Ahh ... And I forgot: You wrote "internal oscillator". If the chip is new this oscillator might be  switched off, so you eventually need a external quartz to succeed. But that is just a guess.

Thank you, i had a 6.8u Capacitor between reset and ground but with a 100uf capacitor it still doesn't work. Since i soldered the emty uC on to the Nano board there is still the original 16mhz quarz. Here is an Image of my setup. The left one is the programmer and the right one the Arduino with the empty uC https://ibb.co/zXQFmwR

It seems that you are using too high programming speed. SCK period al of 0.1 us renders 10 MHz, which is to fast if crystal is working at 8 MHz. Not sure where to change it in Arduino environment, but you should add this key to avrdude.exe run string:
avrdude.exe -B 8
This will set programming speed to 125 kHz. Also I suggest you to buy a cheap USBasp programmer from eBay or AliExpress. It is well documented and have plenty GUI programs, running on top of the avrdude. In newest Arduino IDE you can generate hex files in the sketch directory, and burn it with programmer.

Thanks, but I tried this and it didn't work. It was awfully slow but I was getting the same error message(this time I was using avrdudess, gui for avrdude). Well I bought such a  cheap chinese USB ISP wich doesnt work, so i was trying to reprogramm the uC on this Programmer by following a tutorial. But as I said, I can't proramm using the Arduino nano anymore.

Oh and I monitord the SPI signals using a Logic Analyzer, so it seems like the Clock is running with 125khz, but as you may or may not see is that Nothing ever happens on the MISO line....

https://ibb.co/hWXrpp7

@LukasKamina You should edit your question to include that information.  All the relevant information should be included in your question.


text:
Why should I connect GND to RST to send data through Rx using USB-TTL?
I've found that when I use Arduino Nano connected with USB everything is working great, and when I tryed to use it with USB to TTL connector I've understood that I can only read data. I tryed to connect GND to RST as it was on some picture in Internet, and it works! Now I can send data through my USB to TTL (and through another UART device). So I can't uderstand, why should I do it? Why can't I just send data through Rx Arduino pin? Why do I need an extra action? Is it related with Arduino microcontroller?

add some diagram about what devices and how you connect

The key here is to remember the simple rules:

One device can send to many devices
One device can receive only from one device

In your situation you have three devices that are communicating:

The USB to UART chip
The on-board ATMega, and
The off-board ATMega connected to the TX/RX pins.

All three of those are connected together through the TX and RX pins.  This means that:

The UART chip sends to the on-board ATMega, and
The UART chip sends to the off-board ATMega

This fits with rule 1 above: one device can talk to many devices.
But:

The UART chip receives from the on-board ATMega, and
The UART chip receives from the off-board ATMega

This breaks rule 2 above. You can't have two devices sending to one receiver.
By connecting the RESET pin to GND you are effectively turning off the on-board ATMega. It's like you removed it from the board. It's not allowed to do anything - including communicating with the UART chip.
So that fixes rule 2 above, because now you only have one device sending to the UART chip, not two.

Thanks! That helped me to understand more! By the way, is it the best way I can itteract with another controller or there are another ones less difficult (Software Serial?) ?

It depends what and how you want to communicate. I2C is a popular choice for sending data from one MCU to another.

source: Stack Exchange

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

authors: Даниил Поляков

sort: votes


text:
How to wait a certain time before doing something while running other code?
I have a project where I'm using the HX711 library with a loadcell to weigh in a fruit that is on a conveyor belt. Each fruit has a weight which needs to be classed. The bigger fruits (200g) are class A so they have to "fall down" the conveyor belt at a later stage. The smaller fruits fall down earlier. This has to be done on a timed basis.
What I want to do is get the fruit size , calculate the class (using weight) and then send an interrupt to the dropping mechanism after x time. But while it must wait to drop the next fruit will be have come in and might be smaller than the first.
I can already weigh in and calculate the class of fruits. I've also done this in C using multithreading but adruino uno doesn't support that.
I also have to mention that there is about 50-200 fruits on a single conveyor belt at any given time.

Non-blocking code with millis() is the answer. Look at the BlinkWithoutDelay example, that comes with the Arduino IDE

You can use timestamp to avoid the blocking code. See BlinkWithoutDelay example

while this is true, it was answer many times. you should search for a duplicate

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


text:
Position Feedback for Stepper Motor
I want to rotate a gearwheel with a stepper motor. While Arduino is on everything is well.
My gearwheel transfer its power to a gear worm. The worm will go 10th cm and back repeatedly. When I cut the power, Stepper Motor stops where its last step and position. When the power is on Stepper starts from last position but steps starts from the first step.
Assume that 2038 steps are rotating the Motor one revolution. For example, when 1500 step pass and power cut. Worm is on 6th cm now. And the power is on. Stepper is working from 6th cm and is going 2038 steps. Now it is on 16th cm.
If I use servo, when the power is on, I can write the motor to the 0 position. But I have to use stepper motor. How can I fix this?
Stepper Motor: 28 BYJ 48
Driver: ULN2003A
The cod is here;
int State;
int Wait;

void setup() {

  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);

  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);
  State = 8;
  Wait = 2;
}

void loop() {

  turnRight(2038);
  delay(1000);
  turnLeft(2038);
  delay(1000);

  }

void turnRight(int Step) {
    for (int i = 0; i < Step ; i++){
      digitalWrite(State,HIGH);
      delay(Wait);
      digitalWrite(State,LOW);
      IncreaseState();
    }
}

void IncreaseState() {
  State++;
  if (State==12){
    State=8;
  }
}

void turnLeft(int Step) {
for (int i = 0; i < Step ; i++){
      digitalWrite(State,HIGH);
      delay(Wait);
      digitalWrite(State,LOW);
      DecreaseState();
    }

}

void DecreaseState() {
  State--;
  if(State==7){
    State=11;
  }
}

There are multiple ways to to this. The easiest and most commonly used way is to use a limit switch as home position sensor. At startup the device will first drive the motor in the direction of the limit switch, until the switch get's activated. Now the the absolute position on this axis is known and you can go on from there. (CNC machines and 3D printers mostly work that way. Often they retract again from the limit switch and approach the switch again with less speed, to increase the accuracy). For this you just need a micro switch on the axis and connect it to one input pin. In setup() you are driving the stepper motor in the direction of the limit switch, until it gets activated. Then you are on position zero and can go on with your sketch.
A more difficult way is to introduce a measurement of position into your device. A servo incorporates a potentiometer connected to the axis. By measuring the voltage on this potentiometer (it is basically a voltage divider), the servos electronics can always know, where it currently is. There are also fader potentiometers, where you don't rotate a knob, but you slide a fader over a linear rail. You might find a fader potentiometer, that fits your scale (10cm is not that much, there might be some).
Or you could save the current position to a non-volatile memory (like EEPROM) and retrieve it, when you start up. But since a power-cut during writing of the position may corrupt the data, you would have to go a more complex way. Something like sensing, that the power was cut, providing the Arduino with power through a big capacitor, so that, when it senses power loss, it still has enough time to write the current position to a non-volatile memory. (This is also better for the EEPROM, than continuously writing to it, since EEPROM has limited write cycles).
All in all I would suggest using the first mentioned method (limit switch). It is used in many devices for a reason. Though it depends on your exact project requirements.

Thanks for your reply, I'll try limit switch I think.

Another answer chrism didn't mention is to use an "absolute position rotary encoder". It's a device that outputs a bit pattern using "gray code" or "grays binary" that tells you the position of the shaft. The more bits in the encoder, the more precisely you can measure the position. The "gray code" bit pattern enables you to read the changing position without false reading due to contact/sensor bounce.
However, if you want to uniquely detect 2038 separate steps you'd need a 12 bit rotary encoder, which would be a little expensive and take a lot of interface pins.

Thanks for yor adding. I used Limit Switch and worked well for now. I'll try your idea for improvement in another project.


text:
I2C Devices Interference
I am currently trying to connect 3 I2C Devices to an Arduino Mega, as detailed in the fritzing sketch. The Sensors are: Max86150 PPG Sensor on a breakout board (5v), MLX90614 IR Temperature Sensor (3.3V) and a SM9336 Pressure Sensor(3.3V). Essentially I can connect all devices and read off the sensors using individual sketches, but when I combine the sketches the values are not consistent and then the sketch crashes after only a few seconds.
Weirdly enough, when I combine a sketch with either the Temperature sensor and the Pressure sensor or the Temperature Sensor and PPG Sensor, it will work. But Pressure and PPG do not work together.
Does anyone have any idea what could be happening? I did have it working for a small while with some different wires, could this have anything to do with it? But even still some results I was reading from the sensor were the error values (e.g. the value you get when there is nothing connected, but it wasn't crashing). For reference I am using 30 AWG wires and strip board instead of the breadboard in the Fritzing.
//PPG
#include "max86150.h"
MAX86150 max86150Sensor;
uint16_t ppgunsigned16;
uint16_t irdata;

// Pressure Sensor
#include <Wire.h>

#define PressureSensor_Data 0x30 // Pressure Register address
#define TemperatureSensor_Data 0x2E // Pressure Temp Sensor Address

int P0,T0,P1,T1;
int SMD993Address = 0x6C; // Device Address

//Timing
#define INTERVAL 10 //10 milliseconds per sample for 100 Hz, change this for different sampling rates.
uint32_t lastMicros = 0;

// Temp
#include <Adafruit_MLX90614.h>
Adafruit_MLX90614 mlx = Adafruit_MLX90614();

void ppgsetup()
{
  max86150Sensor.setup();
}

void PPG() {

while (1){
 if(max86150Sensor.check()>0)
    {
        ppgunsigned16 = (uint16_t) (max86150Sensor.getFIFORed()>>2);

        Serial.println(ppgunsigned16);
  //ppgunsigned16 = (uint16_t) (max86150Sensor.getFIFORed()>>2);
  //Serial.println(ppgunsigned16);

  if (ppgunsigned16 > 7000){

     for (int z = 0; z <= 500; z++){//This takes a reading every 10 milliseconds for 5000 milli seconds which is 5 seconds, 500 readings
       digitalWrite(ledPin,HIGH);//turning LED on
        //if (micros() - lastMicros > INTERVAL) { //This takes a reading every 100th of a second
            //lastMicros = micros(); // do this first or your interval is too long!

            if(max86150Sensor.check()>0)
    {
        ppgunsigned16 = (uint16_t) (max86150Sensor.getFIFORed()>>2);
        irdata = (uint16_t) (max86150Sensor.getFIFOIR()>>2);

        Serial.print(ppgunsigned16);
        Serial.print(",");
        Serial.println(irdata);
            //Serial.print("Check PPG");Serial.println(y);
            //mySerial.write(84);mySerial.print(ppgunsigned16);mySerial.print("/");
            //mySerial.write(83);mySerial.print(irdata);mySerial.print("/");
    }
    }
    digitalWrite(ledPin,LOW);//turning LED off
    break;

}
}
}
}

void spirometry() {

    for (int x = 0; x <= 500; x++){
    Wire.beginTransmission(SMD993Address);
    Wire.write(PressureSensor_Data);
    Wire.write(TemperatureSensor_Data);
    Wire.endTransmission();
    Wire.requestFrom(SMD993Address,2);//This takes a reading every 100 milliseconds for 10000 milli seconds which is 10 seconds

    //if (micros() - lastMicros > INTERVAL) { //This takes a reading every 1000th of a second
      //lastMicros = micros(); // do this first or your interval is too long!

    if(Wire.available()<= 2) {
    P0 = Wire.read();
    P1 = Wire.read();
      }

    int Ptotal = P0 + (P1<<8); //The high byte is transmitted second so that

    Serial.println(Ptotal); // Print Ptotal to the serial monitor
    //mySerial.write(81);mySerial.print(Ptotal);mySerial.print("/");// Send PTotal over BLE with flag 81, this will change as sending via bytes is more efficient

    }

  }

void temperature() {
  for (int y = 0; y <= 10; y++){
      mlx.begin();
      Serial.println(mlx.readObjectTempC());
      mySerial.write(82);mySerial.print(mlx.readObjectTempC());mySerial.print("/");
      delay(10);
}
}

void setup() {

  // BT
  mySerial.begin(9600);
  Serial.begin(9600);//Sets BT Serial Comms to 115200, ensure that BT is allowing for this
  //LED
  pinMode(ledPin, OUTPUT);
  // PPG
    // Initialize sensor
    if (max86150Sensor.begin(Wire, I2C_SPEED_FAST) == false)
    {
        Serial.println("MAX86150 was not found. Please check wiring/power. ");
        while (1);
    }
    Serial.println(max86150Sensor.readPartID());
    ppgsetup();

  //Pressure Sensor

  //Temp

  //Sleep
  sleep();

}

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

   PPG();
   delay(10000);
   spirometry();
   delay(1000);
   temperature();

}

Have you tried adding pullup resistors to the lines? As you put more devices on the bus, the capacitance is rising. Pullups (maybe 4.7kOhm, which I mostly use for I2C) may help with that. Also: How long are your wires? I2C is made for rather short connections in the single digit cm region. Long wires can make it unreliable.

It might not be a good idea to totally spam the bus with your messages (for example you take readings very rapidly in spirometry(). Please try to introduce a small delay or similar there. And why do you call mlx.begin() 11 times for reading the temperature? Wouldn't one begin in setup be enough?

@chrisl I've been running I2C devices over 10m cable, with only occassional read errors, so that's unlikely the problem here. Are the device addresses unique?

@chrisl AFAIK there are internal pullup resistors within the Arduino, but I will give them a try and see if it works any better. The cables are probably 10 cm max, most would be in the single cm range.
I have tried playing around with the delays but it doesn't seem to change anything, I am trying to achieve a 100 hz sample rate, which I have read should be achievable on the Arduino Mega. The Mlx.begin() is in the wrong location, good spot I will move that.

@PMF Yes all addresses are unique, what wire gauge are you using for 10m?

@TeeGallagher It was a 8x 0.25mm2 data cable. I used 2 wires for ground, 1x 5V, 1x 3.3V, 2x for I2C. The remote end has a 4x20LCD, a temperature sensor, a GPIO expander with a few buttons and LEDs. The main problem is actually that the 3.3V are not really stable on the far side.

You start Wire in High Speed mode for ppg. You did not set that back, when performing Wire access for pressure. Can the pressure sensor handle high speed mode? Your code is quiet unreadable to me, so it might be, that I've overseen something.

@PeterPaulKiefer This looks like it could have worked, I had to replace a wire because it broke but this seems to have solved the issue. So great spot thank you, I pulled that line of code from an example and I thought it was belonging to a library. Serves me right.

As pointed out by @peterpaulkeifer; Here
// Initialize sensor
    if (max86150Sensor.begin(Wire, I2C_SPEED_FAST) == false)
    {
        Serial.println("MAX86150 was not found. Please check wiring/power. ");
        while (1);
    }

I was setting the I2C Speed of the I2C Interface bus to fast and it seems that the pressure sensor was not able to handle this and would therefore give error answers and then crash.

I had a similar problem sometime ago, where I attached 2 servo driver boards and a battery hat (that used I2C for reading power levels) to a Raspberry Pi. The battery board worked alone and the servo boards worked alone, but when all three were present, the battery board stopped working. And all had unique addresses. After a few hours of going nuts, I realised that there were pullup resistors on the pi and all three boards attached. The total resistance of all 4 parallel pullup resistors were out of spec for I2C. I removed the resistors from the servo boards and everything started working together. So maybe you could disable the pullups on all baords except the Arduino and see if that is the problem.

Thanks for the response, it seems to be that I had unknowingly set the I2C Wire Interface to High Speed and that it was essentially crashing the pressure sensor and the sketch, as far as I can tell anyway.

@TeeGallagher, I voted this up because it was a good answer anyway.  If you have some confidence that your high-speed rate was the problem, you should make a separate answer and later accept it.


text:
Change values of timer using I2C
I'd like to alter the "LED_T_ON" values using an I2C enabled device (i.e. RPi)
Code for Arduino Mega slave:
//slave

#include <Wire.h>

#define SLAVE_ADDRESS 0x08

const int PWR_LED = 43;
int LED_TinH_ON = 18;
int LED_T_ON = 5000;
int LED_T_OFF = 5000;

String inString = "";    // string to hold input
byte LastMasterCommand = 0;
int Mval;

char user_input;

class Relay {
  int relayPin;
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int relayState;                 // pumpState used to set the PUMP
  unsigned long previousMillis;   // will store last time PUMP was updated

  // Constructor - creates a Timer and initializes the member variables and state
  public:
  Relay(int pin, long on, long off)
  {
    relayPin = pin;
    pinMode(relayPin, OUTPUT);

    OnTime = on;
    OffTime = off;

    relayState = LOW;
    previousMillis = 0;  //ORIGINALLY 0
  }

  void Update()
  {
    // check to see if it's time to change the state of the TIMER
    unsigned long currentMillis = millis();

    if((relayState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      relayState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(relayPin, relayState);  // Update the actual LED
    }
    else if ((relayState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      relayState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(relayPin, relayState);   // Update the actual RELAY
    }
  }
};

Relay relay3(PWR_LED, LED_T_OFF, LED_T_ON);

void setup() {
 // initialize serial communication with computer:
  Serial.begin(9600);

  Wire.begin(SLAVE_ADDRESS);

  Wire.onReceive(receiveData);
  Wire.onRequest(slavesRespond);

  pinMode(PWR_LED, OUTPUT);
}

void loop() {
  delay(1000);

  Serial.print("LED_T_ON=");
  Serial.println(LED_T_ON);
  Serial.print("LED_T_OFF=");
  Serial.println(LED_T_OFF);
  Serial.println();

  relay3.Update();

  switch (Mval) {
    case 1 ... 25:
      LED_TinH_ON = Mval;
      Serial.print("LED time on: ");
      Serial.print(LED_TinH_ON);
      Serial.println("h");
      LED_T_ON = LED_TinH_ON*1000;//*60*60;
      LED_T_OFF = (24-LED_TinH_ON)*1000;//*60*60;
    break;
  }
}

void receiveData(int byteCount) {
  LastMasterCommand = Wire.read();
  while (Wire.available()) {
    int msg = Wire.read();

    if (isDigit(msg)) {
      inString += (char)msg;
    }
  }
  Mval = inString.toInt();
  //Serial.println(LastMasterCommand);
  inString = "";
  //Serial.println(Mval);
}

void slavesRespond() {
}

When I change the value on the RPi the Arduino receives and displays the correct value but the timed relays don't actually use the updated values.
Am I missing something?

I see nothing there relating to I2C. What there can be "displaying the correct value" when there is neither anything receiving a value nor anything displaying anything anywhere?

Same. Also LED_T_ON is not changed anywhere (nor is OnTime).

My bad, edited to display the right code

assuming maybe you have other code that is doing the I2C bit, if that code is changing the value of LED_T_ON that will have no effect on that relay object as that value is passed in during the construction. You would need to update relay3.OnTime    ( your order/naming is also switched, relay3(PWR_LED, LED_T_OFF, LED_T_ON); calls Relay(int pin, long on, long off)

Your updating LED_T_ON and LED_T_OFF but those values were already passed into the constructor and changing them will not change the object. you need to update  relay3.OnTime and relay3.OffTime


text:
How to increase the brightness of a IR transmitter LED?
I have a pair of IR transmitters and receivers, but I have found that the brightness of the transmitter is very low, so that I can't use it to detect an object in front of them.
What should I do?

Please specify the part(nr) you are using.

?
Anyway, how is your Arduino connected? Try using an external power supply (5V) to connect your IR transmitter.

A schematic would help. We have no idea of what transmitters you are using, whether or not you are using driver transistors, and what part numbers you are using. Adafruit has an example which sadly does not have a current-limiting resistor for the LED. However the idea of using a transistor to increase output is sensible.

IR transmitter LEDs are literally just LEDs that emits Infrared Light which is not visible to the human eye.
That being said, IR LEDs behave very similarly to regular LEDs and therefore to increase the brightness you need to increase the Voltage it is receiving, just like you would do with a regular LED.
But the problem with LEDs is that they drain current and that's why we use resistors,to protect our electronics(i.e. Arduino).
So to recieve maximum voltage you can reduce the resistance of the resistor (let's say 220ohm or even 100ohm).
Forgot to mention that the correct wiring of LEDs to an arduino is as follows:
5V pin(or digital pin set to high) -> Anode leg(longer) of LED -> Resistor(connected to shorter leg :3) -> ground pin

That is indeed a correct way. Others are: Anode to +5, Cathode to resistor to I/O pin (LOW pin enables, HIGH pin disables the LED). The resistor can be on the Anode side or the Cathode side of the LED; it is absolutely irrelevant which way it is done.

Actually you need to increase the current not the voltage. Increasing the voltage without changing the resistance has the knock-on effect of increasing the current. Or you can decrease the resistance and keep the voltage the same to increase the current. Either way you are limited to either the IO pin's absolute maximum (40mA) or the LEDs absolute maximum, whichever is lower.

@Majenko True. But I thought that because the resistor and LED are in series then they should Hv an equal current draw. But the you are right because the LED and resistor act like one load and voltage is constant . So the only way to increase power is by reducing resistance.

If you aren't at the current limit of either the IO pin (40mA) or the LED (usually around 30mA) you can increase the current as far as the lower of those.  That can be done by reducing the value of the resistor you are using with the LED or using a higher current drive circuit.
However, just having an LED turned on all the time is not a good way of using it - you are constantly fighting against the background light.
Instead the LED needs to be pulsed on and off using PWM at a very high frequency (typically 30-50kHz) and you need to detect that pulsed light with the receiver.
This is usually achieved by using a high-pass (or band pass) filter and amplifier on the receiver.

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


text:
How can we replace a 10k potentiometer with resistors?
I am using an LCD (16x2) with an Arduino Uno R3, in for that I need a 10 kΩ potentiometer, but I don't have it now. How can I replace that?
I have resistors of many kinds and a 1 kΩ potentiometer.

Just use your 1k pot in place of the 10k pot. The resistance doesn't matter that much (though you don't want to go loo low or you could draw too much current) since it is just being used as a voltage divider to set an offset point for the LCD.

"though you don't want to go loo low" just to be sure: a 1k pot can go as low as a 10k pot, right? Like from 0 to 1k rather than from 0 to 10k, and the zero being the lowest value?

No. Like using a 100 ohm potentiometer. It's the total pot resistance that determines the current drawn from Vee.

Ah, you wrote "voltage divider", so that connects all 3 pins of the pot of course. Thanks!

I tried it but the brightness is too high so that the letters are not visible.

Derived from Ohm's Law:

R = R1 + R2 + ... + Rn (For resistors in Series)
(1/R) = (1/R1) + (1/R2) + ... + (1/Rn) (For resistors in Parallel)

You can use any resistance from 1k to 10k with your LCD but the actual value depends on your choice and preferences. You may start with 5k and if you have one then its allright. But if you do not have a resistor of that value you can join resistors of lower values in series with your 1k POT to get resistance of 5k ~ 6k.
In such a way you may get a variable resistance (1k pot) with a suitably high value (other resistors in series). If you wish, you may add more resistors to get higher values like 8k ~ 9k and so on.

Try using 9k~1k. (It worked for my 16*2 LCD)
Or place 9k in series with 1K and vary that.
Connect 10 of your 1K resistors in series. Connect one end to GND and other end to VCC. Now, you will have 10 different nodes (including VCC and GND) each having a different voltage. Connect your desired input pin to any of those nodes.

can you please decribe the circuit(resistors)?

Ok. Connect 10 of your 1K resistors in series.
Connect one end to GND and other end to VCC. Now, you will have 10 different nodes (including VCC and GND) each having diff. voltage. connect you desired input pin to any of that node.

copt-ied past-ed same sentence? :)

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


text:
How can there be not enough current?
I am new to the Arduino world. I have a question regarding current that the Arduino outputs over its 5V port. Why is the current in the Arduino too weak for current hungry circuit when the only thing that changes in this equation V=IR is the current itself.
For instance, the voltage in an Arduino is restricted to 5 volts. Assuming that the resistance of the current stays the same, shouldn't the current also increase (following Ohm's law) over its 5V port? More specifically, I am talking about powering ESP8266 with an Arduino.

Are you talking about the microcontrollers pins or the 5V power point, the reason why the later would be restricted would be because of the type of regulator not being designed for current hungry applications.

When I enumerate my Arduino using USB I see this: MaxPower              100mA - so it is only requesting 100 mA from the USB port. Can you clarify what you mean by: Assuming that the resistance of the current stays the same ...

Why is the current in the arduino too weak for current hungry circuit ... there isn't "current in the Arduino" in the first place.

The problem is not that "there is not enough current", but that you can't dissipate enough power.
Let's assume you are powering the board from an external 12V supply. Now, the 5V are obtained from 12V with a resistive regulator: this means that the regulator (see this image if you are interested in knowing what component it is) simply behaves like a variable resistor, dissipating the power in excess. Now, let's assume you want to draw 4A from the 5V rail, since you want to turn on a lot of LEDs and other stuff. Since P=VI, the regulator (that very little component) has to dissipate (12V-5V)*4A = almost 30W. This means that it becomes a little heater and.. Puff! it breaks.
Now, 4A is a really high current, but that regulator can withstand very little power dissipations. According to the datasheet, and estimating a 1cm x 2cm heatsing under it, we can estimate a 25 K/W thermal resistance, which means that each watt you dissipate raises the internal temperature by 25K (=25°C). You can't go beyond 150°C without damaging the component, which means that if your room is at 25°C you can dissipate AT MOST 5W. In practice, never go beyond 3W. Anyway even 5W mean that, at 12V, you can't get more than 5W/7V=0.7A.
By the way, the regulator is rated 0.8A, so you should never go beyond that value in any case.
Now, this was the external regulator. As for the usb, you can't get more than 500mA from that power supply. That's written in the specs. For this reason, a 500mA fuse is on that rail, so going beyond 500mA will blow that one, interrupting your power. Well, that's a self-healing fuse, so after some time (maybe hours?) it will operate again, but.. Don't try that.
In the end, the digital pin current. The atmega datasheet says that

The absolute maximum current per I/O Pin is 40.0mA
The absolute maximum current inside VCC and GND Pins is 200.0mA

This means that from each single pin you can get at most 40mA (but I suggest you never go beyond 20mA), and the sum of all the currents (and the internal peripherals) should never exceed 200mA. So if you need to power 2 leds, you can give each of them 20mA, if you need to power 15 of them you can't (you are limited to, let's say, 10mA). If you need more, use transistors to separate the current paths.

More than likely, the reason for the 20ma/40ma safe/absolute limits per pin is not a current cutoff, but as your first sentence states, the inability to dissipate enough power - specifically, heat - to exceed them without eventual damage. They probably would pass more than 40ma, briefly, but fail, doing so.

The per pin limits are of course due to the thermal design of the IC. Probably because of the wire bonding diameter, or the IC traces width, or the parasite resistor, or... Whatever, the Atmel characterized the IC and stated that you should not exceed it, otherwise you COULD damage it. Of course, maybe getting 10A for 1ps can leave you with a sane IC, but.. Hey, no guarantee ;)

Could you explain how you would use a transistor to separate the current path? I have tested some things with PNP and NPN transistors but I did not know you could use that to separate the current path. I just used them as logic gates.

@steven well, if you attach an NPN base to an arduino output through a resistor (usually in the range 10k-47k), emitter to ground and the load to the collector you just separated the two current paths, since now the load discharges through the NPN instead of the arduino. So.. using an NPN as switch actually "separates" them. Personally I tend to prefer nMOSs instead of NPN (and pMOS instead of PNP) because they behave more "ideally" in my mind ;)

A very simple answer:  The Arduino is limited to an absolute 40mA per pin, because within the controller chip (ATMega328 usually) the path the current follows is very small.  More current can destroy the tiny transistors in the chip.  Best case, you burn out that pin.
If you have a problem that requires more than 40mA (and really, as other posters point out, 20mA!) you should be using a transistor, mosfet or relay controlled by the Arduino, rather than directly power the end device.


text:
Can I specify custom port names in the Arduino IDE on Linux?
On Linux, if you have more than one USB TTY device, the USB port name (/dev/ttyUSBx) changes every time one is plugged in, and there's no easy way to know the new name without going and looking through dmesg.  It's trivial to set up a udev rule that creates a custom symlink so that my Arduino's FTDI can always be accessed through e.g., /dev/ttyArduino, and this is the standard procedure for persistent access to USB devices.
However, I can't make the IDE accept anything other than the /dev/ttyUSBx names.  Even directly editing preferences.txt is ignored.
Is there any way to instruct the IDE to use custom port names in order to access the Arduino through a symlink or other persistent name?

I am not aware of a way in the Arduino IDE, but you can in UECIDE.

Look here: http://arduino.stackexchange.com/questions/3680/in-linux-how-to-identify-multiple-arduinos-connected-over-usb/22323#22323

Consider using a device name of form ttyUSBnn, where nn is fairly large.  For example, in /dev you could say
sudo ln -s ttyUSB1 ttyUSB77

Then, ttyUSB77 shows up in the IDE's ports list and can be selected.
(I don't know how to set up that link using the udev system, but imagine it can be done.)

Excellent hack, and it does work. Thanks.  If nobody answers with an IDE configuration answer in a few days I'll accept this.

This is also very dynamic and will not do what you've asked for

Obviously this is a one-off hack and doesn't work on the next plug-in, but doing it from udev appears to work fine.

Think the other way.
If your device has a port name, that is not supported by the IDE, you can create an additional (static) symlink /dev/USBx that you can identify and select in the arduino IDE.
And yes, it is quite easy to make all of your arduinos unique to udev.

Thanks!   Your link on how to flash a new serial number to an FTDI chip is very cool.  Unfortunately, there's nothing similar for the (all-too-common) CH340 and PL2303 chips -- they have no onboard storage.


text:
DS3231 + button to trigger light
please can someone help me with code, i want to have automatic trigger on specific hour, also i want to have button switch if needed, in my code i can press the button to trigger light relay, but my specific time trigger just flash at start time and does nothing, here is code:
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
LiquidCrystal_I2C lcd(0x27, 2, 1,0,4,5,6,7,3, POSITIVE);
DS3231  rtc(SDA, SCL);
Time t;

const int OnSec = 30;
const int OffSec = 5;
int relay_3 = 5 ;

void setup() {
 lcd.begin(20,4);
 rtc.begin();

 pinMode(relay_3,OUTPUT);
 pinMode(8, INPUT_PULLUP);
}

void loop() {
  int button_4 = digitalRead(8);
  t = rtc.getTime();
  lcd.setCursor(0,1);
  lcd.print(rtc.getTimeStr());

  if(t.sec == OnSec)                                  //if is hh.mm.30 - just for 1 sec trigger relay
  {
  digitalWrite(5,HIGH);
  }
    else if(t.sec == OffSec)                         //if is hh.mm.05 - release relay
  {
  digitalWrite(5,LOW);
  }
      else if (button_4 == HIGH)                     //if button is pressed - trigger relay
  {
  digitalWrite(5,HIGH);
  }
        else
  {
  digitalWrite(5,LOW);
  }

  lcd.clear();
}

i would be gratefull for any advice :)

the indentation of the code in the if ... else block is really messed up

the last else command is the culprit .... think very carefully about the whole if ... else block

The else case is executed every time the other if and else if conditions are not true. That means if it is not 5 sec and not 30 sec and no button is pressed, the relay is switched off.
To achieve what you want is not that easy, because you have to synchronize button press and button release with the timer actions. First you must specify what you exactly want to do. e.g What happens if you have already pressed the button and release it in the time interval between 30 and 5. Releasing the button would switch off the light but should it stay on because you are within the on-time? This is just an example of what to think about.
I wrote a little code for fun doing the things as I would do it:
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
LiquidCrystal_I2C lcd(0x27, 2, 1,0,4,5,6,7,3, POSITIVE);
DS3231  rtc( SDA, SCL );
Time t;

const int OnSec = 30;
const int OffSec = 5;
int relay_3 = 5;

int timerPhase = -1;
int relayState = LOW;

void setup()
{
 lcd.begin( 20, 4 );
 rtc.begin();

 pinMode( relay_3, OUTPUT );
 pinMode( 8, INPUT_PULLUP );
}

void loop()
{
  t = rtc.getTime( );

  int button_4 = digitalRead( 8 );

  lcd.setCursor( 0, 1 );
  lcd.print( rtc.getTimeStr( ) );

  // this only works if the off time is
  // less than the on time. (OffSec < OnSec)
  timerPhase = ( (t.sec > OffSec) && ( t.sec < OnSec ) ) ? 0 : 1;

  if ( button_4 == HIGH )
  {
    // a button overrides the timer phase
    relayState = HIGH;
  }
  else
  {
    if ( timerPhase == 0 )
    {
      relayState = LOW;
    }
    else
    {
      relayState = HIGH;
    }
  }

  digitalWrite( relay_3, relayState );

  lcd.clear();
}

I could not try the code because I don't know which libraries you used and therefor got compiler errors. So there might be syntax errors in my code but I hope I wrote correct code. It would be nice if you report errors here, if you find one/some ;-).
The line
timerPhase = ( (t.sec > OffSec) && ( t.sec < OnSec ) ) ? 0 : 1;

uses a ternary operator. It means if the condition ( (t.sec > OffSec) && ( t.sec < OnSec ) ) is true, take the first alternative 0 and assign it to the variable timerPhase, if it is false choose the second alternative '1'.


text:
Code running on UNO doesn't run on MEGA
the code posted below runs perfectly on UNO, but the loop only runs for twice or thrice (figured this out by printing out "TEST" on the Serial Monitor) on the Arduino mega. Someone can tell me what's wrong with this? It's a 4wd robot which runs on RF Joystick. The circuit has a RF receiver connected to digital pin 2. Also, I noticed that when all the functions are removed from the loop, it runs perfectly.
However, as my suspicion that the board is not functioning properly, I tried uploading other programs to the MEGA and they run flawlessly.Including the "ESP8266 as a shield controlled using the Blynk app version" of this code.
#include <VirtualWire.h>
#include <AFMotor.h>
int RF_RX_PIN = 2;// RF signal from joystick
void(* resetFunc) (void) = 0;
AF_DCMotor rb(4);//means rightside,back wheel
AF_DCMotor lb(3);//leftside, back wheel
AF_DCMotor rf(1);
AF_DCMotor lf(2);
  int xh,xl,yh,yl;
  uint8_t z;
  uint8_t button;

void setup()
{
  Serial.begin(9600);
  vw_set_rx_pin(RF_RX_PIN);  // Setup receive pin.
  vw_setup(2000); // Transmission speed in bits per second.
  vw_rx_start(); // Start the PLL receiver.
  pinMode(servopin,OUTPUT);
  pinMode(13,OUTPUT);
  rf.run(RELEASE);
  lf.run(RELEASE);
  lb.run(RELEASE);
  rb.run(RELEASE);
  digitalWrite(13,HIGH);
}

uint8_t buffer[VW_MAX_MESSAGE_LEN]; // buffer array for data recieve over serial port
uint8_t buflen = VW_MAX_MESSAGE_LEN;
int x=0;
int y=0;
int state=2;

void loop()
{
  Serial.println("TEST");
  if(vw_get_message(buffer, &buflen)) // non-blocking I/O
  {
    decode();
  if ((x==0 && y==0) || z==1){rstop();}
  else {
  Serial.print(x);
  Serial.print(" ");
  Serial.println(y);
  godirection(x,y);
  }
  }else{
    state=2;
    rstop();
  }
}

void decode()
{
  if((buffer[0]!=0x7E)||(buffer[4]!=0xEF))
  {
  resetFunc();
  }
  uint8_t i = 0;
  x = buffer[1]<<2;
  y = buffer[2]<<2;
  z = buffer[3]>>3;
  button = buffer[3]&0x07;
   if (x>600){
    x=1;
  }else if (x<=600 && x>=400){x=0;}
  else {x=-1;}
  if (y>600){
    y=1;
  }else if (y<=600 && y>=400){y=0;}
  else {y=-1;}
}

void clearBufferArray()              // function to clear buffer array
{
  for (int i=0; i<VW_MAX_MESSAGE_LEN;i++)
    { buffer[i]=0;}                  // clear all index of array with command NULL
}
void godirection(int x,int y) {
     if (x==0){
      if (y==1){forward();}
      else if (y==0){rstop();}
      else if (y==-1){backward();}
     }
     else if (x==1){
      if (y==1){srf();}
      else if (y==0){right();}
      else if (y==-1){srb();}
     }
     else if (x==-1){
      if(y==1){slf();}
      else if (y==0){left();}
      else if (y==-1){slb();}
     }
}

void rstop (){
  if (state==0){
  rf.run(FORWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(FORWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
  delay(75);
  rf.run(RELEASE);lf.run(RELEASE);lb.run(RELEASE);rb.run(RELEASE);
  rf.setSpeed(0);lf.setSpeed(0);rb.setSpeed(0);lb.setSpeed(0);
  state=2;
}
else if (state==1){
  rf.run(BACKWARD);lf.run(BACKWARD);lb.run(BACKWARD);rb.run(BACKWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
  delay(75);
  rf.run(RELEASE);lf.run(RELEASE);lb.run(RELEASE);rb.run(RELEASE);
  rf.setSpeed(0);lf.setSpeed(0);rb.setSpeed(0);lb.setSpeed(0);
  state=2;
}
else if (state==2){
    rf.run(RELEASE);lf.run(RELEASE);lb.run(RELEASE);rb.run(RELEASE);
  rf.setSpeed(0);lf.setSpeed(0);rb.setSpeed(0);lb.setSpeed(0);
}
}

void forward(){
  state=1;
  rf.run(FORWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(FORWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
}

void backward(){
  state=0;
  rf.run(BACKWARD);lf.run(BACKWARD);lb.run(BACKWARD);rb.run(BACKWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
}

void right(){
  state=2;
  rf.run(BACKWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(BACKWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
}
void left(){
  state=2;
  lf.run(BACKWARD);rf.run(FORWARD);rb.run(FORWARD);lb.run(BACKWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
}

void srf(){//srf means slanted right forward
  state=1;
  rf.run(FORWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(FORWARD);
  rf.setSpeed(50);lf.setSpeed(200);rb.setSpeed(50);lb.setSpeed(200);
}

void srb(){
  state=0;
  Serial.println("SRB");
  rf.run(BACKWARD);lf.run(BACKWARD);lb.run(BACKWARD);rb.run(BACKWARD);
  rf.setSpeed(50);lf.setSpeed(200);rb.setSpeed(50);lb.setSpeed(200);
}

void slf(){
  state=1;
  rf.run(FORWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(FORWARD);
  lf.setSpeed(50);rf.setSpeed(200);lb.setSpeed(50);rb.setSpeed(200);
}

void slb(){
  state=0;
  rf.run(BACKWARD);lf.run(BACKWARD);lb.run(BACKWARD);rb.run(BACKWARD);
  lf.setSpeed(50);rf.setSpeed(200);lb.setSpeed(50);rb.setSpeed(200);
}

where in the program does it stop?

the whole thing stops just I couldn't find a specific place it did. the serial monitor just stops after printing two or three "TEST" s. I think the loop iteration stops. However, if all the functions such as rstop, and decode are removed, it runs again. but it is not specific to any function.

then figure out where is stops exactly

it just stops when it meets a function :(… I figured it.. any function... when it meets one.. it freezes. but any other code with any function works perfectly fine. only in this code

You need to put in a lot more print statements to figure out exactly where the program is halting.  Put a print statement at the beginning and end of each function. then you'll see which function is causing the crash.

You also need to fix your indentation. The way your rstop() function is indented, it looks like the first closing brace ends the function and the else if (state==1) code is outside any function. The body of the first if statement should be indented, and the closing brace that ends the if statement should be on the same line as the if statement. There are quite a few bad uses of indentation that make your code very hard to read.

There is a servopin variable you configure as OUTPUT. Where does it come from? From the header files? If it is not declared anywhere, i don't believe that code compiles. Or did you delete some code, and this is not all you have done?

Im sorry please ignore the servopin,,, I removed the variable declaration to make it easier to focus on this problem for you guys... forgot to delete that line


text:
Initalizing library object in own library
EDIT: @Juraj fixed the Issue, changes at the end of the post
I am developing an application to program OneWire ID Chips. I am using the OneWire library (https://github.com/PaulStoffregen/OneWire) and built my own Library for the DS28EC20 Chip on top of it.
It is working but it's not very elegant. I have issues initalizing the OneWire object in my own library. At the moment it is only working with a fixed pin declared in my own library.
I want to call a function in my code which initalizes the OneWire library aswell as my own library for the DS28EC20.
I am not using the Arduino IDE, I am using Platform.io for VSCode because it's more powerful.
It would be awesome if someone could help me, because I need to use multiple ID Chips in my application.
Because of unkown reasons I need to pass a variable to the constructor of the DS28EC20. Calling the OneWire library in there does not work...
I excluded the other functions in the DS28EC20.cpp file, I think they are not necessary rn
Thank you very much in advance!
- pitchbent
main.cpp:
#include <Arduino.h>
#include <OneWire.h>
#include <DS28EC20.h>

uint8_t scratchpad[32];                                                   // Array for scratchpad
uint16_t location;                                                        //Memory location to store scratchpad in
//uint8_t memory[32];
bool status;                                                              // Status of the crc check

DS28EC20 One(5);

void setup() {

  pinMode(13,OUTPUT);
  Serial.begin(115200);                                                   //begin serial connection 0
  location = 0x460;                                                       //Memory location

  for (uint8_t i = 0; i < 32; i++)                                        //filling array for scratchpad
  {
    scratchpad[i]=0x22;
  }
  Serial.println(scratchpad[2]);

  status = One.write_scratchpad(scratchpad,32,location);                  //write scratchpad
  Serial.println("Status:");                                              //print status
  Serial.println(status);

  // put your setup code here, to run once:
}

void loop() {

  // put your main code here, to run repeatedly:
}

DS28EC20.cpp:
#include "Arduino.h"
#include "OneWire.h"
#include "DS28EC20.h"

OneWire Wire(31);

DS28EC20::DS28EC20(uint8_t)
{

}
bool DS28EC20::write_scratchpad(uint8_t *data, uint8_t leng, uint_fast16_t adress)
{
  Serial.println("123");
  uint8_t TA1;                                                            // Var for adress Bytes
  uint8_t TA2;
  uint8_t crc_rec[6];                                                     // Array for recieved CRC Bytes
  uint8_t crc_array[leng+3];                                              // Array for calculation of CRC value

  TA1 = (adress & 0xFF);                                                  // calculation of TA1 & TA2
  TA2 = ((adress >> 8) & 0xFF);
 crc_array[0]=WRITE_SCRATCHPAD;                                            // The CRC sum is computed out of the command aswell as the adress byteys
  crc_array[1]=TA1;                                                         //
  crc_array[2]=TA2;

  for (int i = 0; i < leng; i++)                                            // write data into crc array
  {
    crc_array[i+3]=data[i];
  }
 Wire.reset();                                                             // Reset
  Wire.write(SKIP_ROM);                                                     // Skip ROM
  Wire.write(WRITE_SCRATCHPAD);                                             // write Scratchpad

  Wire.write(TA1);                                                          // send adress bytes
  Wire.write(TA2);

  for(int i=0;i<leng; i++)                                                  // write data
  {
    Wire.write(data[i]);
  }

  Wire.read_bytes(crc_rec,6);                                               // safe CRC values sent from chip

  delay(10);
 Wire.reset();                                                             // Reset
if(Wire.check_crc16(crc_array,leng+3,&crc_rec[0]))                        // CRC Check
  {
    return true;
  }
  else
  {
    return false;
  }

}

DS28EC20.h
/*
Library for DS28EC20, built on top of OneWire.h lib
*/

#ifndef DS28EC20_h
#define DS28EC20_h

#include "Arduino.h"
#include "OneWire.h"
#include "DS28EC20.h"

#define WRITE_SCRATCHPAD 0xF                                              // commands für DS28EC20
#define READ_SCRATCHPAD 0xAA
#define COPY_SCRATCHPAD 0x55
#define READ_MEMORY 0xF0
#define EXTENDED_READ_MEMORY 0xA5

#define READ_ROM 0x33
#define MATCH_ROM 0x55
#define SEARCH_ROM 0xF0
#define SKIP_ROM 0xCC
#define RESUME 0xA5

class DS28EC20
{
    public:
     DS28EC20(uint8_t); // Constructor, add DS28EC20 to "pin"
     bool write_scratchpad(uint8_t *data, uint8_t leng, uint_fast16_t adress);
     bool write_memory(uint16_t adress);
     void read_memory(uint16_t adress,uint8_t *data, uint8_t leng);

     private:

};

Fix:
In main.cpp call Object with corresponding pin:
DS28EC20 One(31);

In DS28EC20.cpp add
OneWire Wire;

after includes, change the constructor aswell:
DS28EC20::DS28EC20(uint8_t pin)
{
  Wire.begin(pin);
}

In DS28EC20.h you need to change the class to:
class DS28EC20
{
    public:

     DS28EC20(uint8_t pin); // Constructor, add DS28EC20 to "pin"
     bool write_scratchpad(uint8_t *data, uint8_t leng, uint_fast16_t adress);
     bool write_memory(uint16_t adress);
     void read_memory(uint16_t adress,uint8_t *data, uint8_t leng);

     private:
     OneWire Wire;

};

Do you get an error, if you don't provide a constructor parameter?

Yes. The answer of @Juraj kinda solved the issue. The only issue which still persists i calling a second instance...

Use the constructor without parameter OneWire wire; and call wire.begin(pin); to set the pin.
And to use more sensors on different pins, make the OneWire instance member of the DS28EC20 class.

It works better than before now, thank you. Initializing via DS28EC20 One(31)works now, but if I initalize a second instance (for example DS28EC20 Two(32) i return the same results as in the first object....

Please notice the commenct above yours :)

Thank you so much! I still need to learn a lot of things.


text:
Uno PWM freq conflicts with other PORTs
Am working on a small project in which I can control the speed a 24V DC Motor using a Variable resistance to A/D then generate the right PWM to an optocoupler while displaying the speed in 4 7-segments, the problem is the PWM (PORTD Pin 5) pin 5 on the Uno is not working when I Initialize any pin of PORTB (7-segment port)
int main(void)
{
  uint8 duty_cycle = 0, digit_t = 0, digit_h = 0, digit_ten = 0, digit = 0, read_index = 0, duty_old = 0;
  uint16 old_reading = 0, motor_rpm, read_average = 0;
  uint32 adc_readings = 0;
  /* Declare the 4 7-segments in the system */
  //    BCD_Segment seg_1, seg_2, seg_3, seg_4;

  //    /* Initialize the 7-segments */
  //    Segment_Init(&seg_1, B, pin0, pin1, pin2, pin3, D, pin0);
  //    Segment_Init(&seg_2, B, pin0, pin1, pin2, pin3, D, pin1);
  //    Segment_Init(&seg_3, B, pin0, pin1, pin2, pin3, D, pin2);
  //    Segment_Init(&seg_4, B, pin0, pin1, pin2, pin3, D, pin3);
  //    //
  //    ///* Turn off segments */
  //    //Segment_OFF(&seg_1);
  //    //Segment_OFF(&seg_2);
  //    //Segment_OFF(&seg_3);
  //    //Segment_OFF(&seg_4);
  /* segment pins */
  //SET_BIT(DDRB, 0);
  //SET_BIT(DDRB, 1);
  //SET_BIT(DDRB, 2);
  //SET_BIT(DDRB, 3);

    /* Enable pins */
SET_BIT(DDRD, 0);
SET_BIT(DDRD, 1);
SET_BIT(DDRD, 2);
SET_BIT(DDRD, 3);

  /* display 0*/
  //CLEAR_BIT(PORTB, 0);
  //CLEAR_BIT(PORTB, 1);
  //CLEAR_BIT(PORTB, 2);
  //CLEAR_BIT(PORTB, 3);

  /* segments off */
  CLEAR_BIT(PORTD, 0);
  CLEAR_BIT(PORTD, 1);
  CLEAR_BIT(PORTD, 2);
  CLEAR_BIT(PORTD, 3);

  uint16 adc_reading = 0;
  Boolean adc_flag = False;
  /* Declare the 4 7-segments in the system */

  /* Initialize the adc and the pwm timer */
  ADC_init();
  PWM_Init();

  while (1)
    {
      ADC_StartConversion();
      adc_flag = ADC_WaitForFlag();

      /* calculate the ADC voltage */
      adc_reading = ADC_GetValue();

      if((adc_reading <= 256) && (adc_reading >= 0))
    {
      PWM_DutyCycle(0);
    }
      else if((adc_reading > 256) && (adc_reading <= 512))
    {
      PWM_DutyCycle(50);
    }
      else if((adc_reading < 768) && (adc_reading > 512))
    {
      PWM_DutyCycle(75);
    }
      else if(adc_reading >= 768)
    {
      PWM_DutyCycle(100);
    }

      /* Clear the ADC flag */
      ADC_ClearFlag();

      /* update the pwm */
      //PWM_DutyCycle(duty_cycle);
    }
}

and here the code for the bad PWM
    int main(void)
    {
      uint8 duty_cycle = 0, digit_t = 0, digit_h = 0, digit_ten = 0, digit = 0, read_index = 0, duty_old = 0;
       uint16 old_reading = 0, motor_rpm, read_average = 0;
  uint32 adc_readings = 0;
  /* Declare the 4 7-segments in the system */
  //    BCD_Segment seg_1, seg_2, seg_3, seg_4;

  //    /* Initialize the 7-segments */
  //    Segment_Init(&seg_1, B, pin0, pin1, pin2, pin3, D, pin0);
  //    Segment_Init(&seg_2, B, pin0, pin1, pin2, pin3, D, pin1);
  //    Segment_Init(&seg_3, B, pin0, pin1, pin2, pin3, D, pin2);
  //    Segment_Init(&seg_4, B, pin0, pin1, pin2, pin3, D, pin3);
  //    //
  //    ///* Turn off segments */
  //    //Segment_OFF(&seg_1);
  //    //Segment_OFF(&seg_2);
  //    //Segment_OFF(&seg_3);
  //    //Segment_OFF(&seg_4);

  /* segment pins */
  /* just enabling one pin or all fails the PWM on PORTD PIN 5*/
  SET_BIT(DDRB, 0);
  //SET_BIT(DDRB, 1);
  //SET_BIT(DDRB, 2);
  //SET_BIT(DDRB, 3);

    /* Enable pins */
SET_BIT(DDRD, 0);
SET_BIT(DDRD, 1);
SET_BIT(DDRD, 2);
SET_BIT(DDRD, 3);

  /* display 0*/
  //CLEAR_BIT(PORTB, 0);
  //CLEAR_BIT(PORTB, 1);
  //CLEAR_BIT(PORTB, 2);
  //CLEAR_BIT(PORTB, 3);

  /* segments off */
  CLEAR_BIT(PORTD, 0);
  CLEAR_BIT(PORTD, 1);
  CLEAR_BIT(PORTD, 2);
  CLEAR_BIT(PORTD, 3);

  uint16 adc_reading = 0;
  Boolean adc_flag = False;
  /* Declare the 4 7-segments in the system */

  /* Initialize the adc and the pwm timer */
  ADC_init();
  PWM_Init();

  while (1)
    {
      ADC_StartConversion();
      adc_flag = ADC_WaitForFlag();

      /* calculate the ADC voltage */
      adc_reading = ADC_GetValue();

      if((adc_reading <= 256) && (adc_reading >= 0))
    {
      PWM_DutyCycle(0);
    }
      else if((adc_reading > 256) && (adc_reading <= 512))
    {
      PWM_DutyCycle(50);
    }
      else if((adc_reading < 768) && (adc_reading > 512))
    {
      PWM_DutyCycle(75);
    }
      else if(adc_reading >= 768)
    {
      PWM_DutyCycle(100);
    }

      /* Clear the ADC flag */
      ADC_ClearFlag();

      /* update the pwm */
      //PWM_DutyCycle(duty_cycle);
    }
}

and the output is like this

Here's the code for PWM_Init
void PWM_Init(void)
{
  /* Making the pwm pin output */
  pinMode(pin5, D, Output);

  /* fast pwm mode */
  SET_BIT(TCCR0A, WGM00);
  SET_BIT(TCCR0A, WGM01);
  CLEAR_BIT(TCCR0A, WGM02);

  /* Inverting */
  SET_BIT(TCCR0A, COM0B1);
  SET_BIT(TCCR0A, COM0B0);

  /* prescaler 1024 */
  SET_BIT(TCCR0B, CS00);
  CLEAR_BIT(TCCR0B, CS01);
  SET_BIT(TCCR0B, CS02);
}

void PWM_DutyCycle(uint8_t duty)
{
  OCR0B = (duty * 255) / 100;
}

Can you be more specific about what "bad PWM" means?

I used the fast PWM mode so the output should be continuous like the first pic, but when write to the DDRB in any pin the PWM output is like what appears in the last pic

Please show us your PWM code, like PWM_Init() and such

What is connected to pin 12?

I added the code for the PWM_Init() and PWM_DutyCycle()

for pin 12 it's not connected to anything and not even Initialized.

Re “pinMode(pin5, D, Output);”: you mean pinMode(5, OUTPUT);?

it means pin 5 of PORT D is output it writes to the DDRD register and this pin is pin5 on the UNO


text:
Need Help to Select Microcontroller ?? Help
i am doing a project which has to run in side a garage to control water levels in sump pit as well as in overhead tank . also schedule running of  pumps.
i have to run 5 pumps  (two for ground water to sump pit , three for sump pit to  over head tank) check two levels also need to check when pump goes on the water is flowing or not if not try another pump
the micro controller should last at least two years .
the temperature inside garage where micro controller board will be kept will go to 47 centigrade in summer to 15 centigrade in winter .
i see many options :
1.arduino uno
2.arduino uno from sparfu and adafruit
3.Sparkfun Arduino Fio
4.SparkFun Arduino Pro Mini 328
5.Adafruit Metro Mini 328
6.Adafruit METRO 328
7.Particle Photon
what whould i use ?

That greatly depends on your exact requirements. As you seem to only control 1 pump and 2 inputs (for water level), you don't have big requirements. How should the Arduino be powered? (Though I think the Particle Photon is a big overkill for this)

i have to run 5 pumps check two levels also need to check when pump goes on the water is flowing or not if not try another pump.  arduino will be powered by a smps 5 v. supply.i am concern about the durability of the controller at this temp. range for two year.

That temperature range is no problem. What is the humidity though?

can go to 96%.....

Particle Photon is not Arduino. all the other options are almost identical

i know...........

We cannot say, what single board you need to use. There are many boards, that are fitting to your requirements. You yourself have to choose.
Most of your listed boards use the same microcontroller (as Juraj wrote in his comment):
The Arduino Uno (doesn't matter where you buy it, it's the same) and all the boards with a 328 at the end use the Atmega238P. The Sparkfun Arduino Fio uses an Atmega32U4, which is different from the 328P, but not a very big jump (though it implements native USB support). These are all AVR based microcontrollers. The Particle Photon is not an Arduino. It uses an ARM processor and has wifi.
To choose from the big amount of boards on the market, you should look into your requirements:
- How many outputs do I need? Only simple digital outputs or also PWM? If the latter, how many individual PWM pins do I need?
- How many inputs do I need? Only digital or also analog?
- What extra devices do I need? Relays for motors/high loads? Special boards? And how do they need to be connected (what interfaces they use)?
- What interfaces do I need to the outside world? LCD Display + Buttons? Bluetooth? Wifi? Or nothing?
- How computationtime- and memory-consuming are the calculation tasks, that I need to perform (resources)?
- What environment will the project be in?
Based on the answers, you can choose a board, that fit's all the requirements and still leaves a bit headroom for further development. To help you I will write some examples for your project, that might be fitting for you.

Outputs: I guess your pumps are using mains power or similar (Be VERY carefully with mains power. It can easily kill you!). You need a relay to control these. It would be easiest to use a complete relay board, that includes all the needed extra circuitry. Then you just need to use one digital output pin per controlled pump, which results in 5 pins needed.
Inputs: This depends on what level sensors you have. If they have a digital signal (like a simple switch, that triggers, when it is covered by water), you just need to tie one digital input pin to each level sensor. With 2 level sensors per tank and 2 tanks we need 4 digital input pins for level sensing.
If the level sensors work with an analog voltage, you need to use 4 analog input pins. Their usage is a bit different, since their voltage has to be converted to a number value by the ADC (Analog Digital Converter) inside the microcontroller.
Interfaces: This is mostly up to you, since you didn't specify anything. You can just build the device with any outside interfaces, if you don't need them. Then you also can use a board without wifi. If you think, that adding wifi in the future would be a great idea, you can use a wifi capable board and just disabling wifi, until you need it. (Thinking a bit in the future, what future development might get interesting for this project)
Resources: Controlling motors (pumps are only motors for the microcontroller) based on some simple inputs is somewhat the standard task for a simple microcontroller. It doesn't need much computation power, neither much memory.
Environment: The temperature is not a problem for you. Basically all microcontrollers can operate in temperatures up to 80°C und down to -35°C (the exact values can be found in the datasheet of the corresponding microcontroller). The humidity is more of a problem. You need to build a water resistant casing for the electronics of your project, so that no water can get on the electronic parts. Also - to be sure - you should put one or two of these little silica bags into the casing, which sometimes come with electronic devices or such. The silica bags will bind the water in the air inside the casing and will keep the electronics even more dry.

So you need a simple microcontroller with 5 digital outputs and 4 inputs (digital or analog depending on your sensors), so in total 9 free fitting pins. An Uno or some of it's variants are fitting for this. If you want it smaller, that the Uno, you might want to use the Nano, which is the same as the Uno, just smaller. If you want wifi capabilities, you can go with an ESP variant like the NodeMCU.
This is just an example. There are many ways to build such a project, so there is no definitive answer. Any microcontroller, that fit's your requirements, is ok for the job.


text:
I need some help getting data from a rangefinder
I have wired up my range finder (CJVL53L0XV2) to a breadboard for testing and have run the arduino example code for the rangefinder. The rangefinder works, but I do not know how to take the distance that the range finder shows on the serial monitor, example: distance measured 44mm, and turn that information into a variable that the rest of my program could use.
I am not sure how to "grab" data from the sensor and turn that data into a variable that I can then manipulate. I have tried to dissect the example code, but it seems to be taking data and using functions that do not exist anywhere but in some files in the arduino library that I can't identify or access.
Below is the code that I have been trying to reverse engineer.
[code]
Adafruit_VL53L0X lox = Adafruit_VL53L0X();
int pbl = 9;
void setup() {
  pinMode(pbl, OUTPUT);
  digitalWrite(pbl, HIGH);
  delay(1);
  Serial.begin(115200);

  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }

  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin()) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power
  Serial.println(F("VL53L0X API Simple Ranging example\n\n"));
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  if (measure.RangeStatus != 4) {  // phase failures have incorrect data
    Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println(" out of range ");
  }

  delay(100);
}
[/code]

use a lookup table ... distance to number of rounds

please reduce the amount of text in your post ... you can delete the first and third paragraphs ... also delete the bottom half of second paragraph, starting with The way I would like the rangefinder .... that should leave a simple, to the point question.

jsotola, Thanks. I have edited my question to get to the point more quickly.

Perhaps if you add the code to the question, we can suggest what to add/change.

My apologies. The code I have been trying to work with is just the sample code. I posted it with my question. Thanks!

measure.RangeMilliMeter was the key to it all. After experimenting for several hours, I finally got it.


text:
How to Compile Different Sketches in Different Visual Studio Code Workspaces
I'm using Visual Studio Code with the Arduino extension. I have two workspaces each with a different sketch file loaded - Sketch_1 and Sketch_2. Sketch_1 will verify and upload properly. When I click on the Verify to compile or Upload buttons for Sketch_2 in its workspace, VS Code verifies and uploads Sketch_1, not Sketch_2. Am I doing something wrong, or is it not possible to separately Verify and Upload different sketches in different workspaces?

The first time you verify your sketch you are confronted with a list of available sketches (INO's). As soon as you select one of these it gets stored under "sketch" in .vscode/arduino.json.
If you zero this, "", you'll once again be asked which sketch to set as "main sketch".
This "device context" is stored per workspace so you might consider narrowing your scope when opening a folder. I know this is no fun when exploring, and the will to switch and try different examples is big, but currently there are nothing that facilitates a smoother alternative.


text:
expected `}' at end of input
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup() {
    Serial.begin(9600);
    pinMode(6, OUTPUT);
    pinMode(9, OUTPUT);
 }
void loop(){
 sensorVal = analogRead(A1);

 Serial.print("Sensor Value: ");
 Serial.print(sensorVal);

 float voltage = (sensorVal*5.0)/1024.0;
    Serial.print("Volts: ");
    Serial.print(voltage);

 float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
 float pressure_bar = pressure_pascal/10e5;
   Serial.print("Pressure = ");
   Serial.print(pressure_bar);
   Serial.println(" bars");
   Serial.print("Pressure = ");
   {
 for(int a = 255; a>=0;a--)
 {
   analogWrite(6,a);
 if (pressure_bar = 1600){
   analogWrite (6, a);
 if (pressure_bar > 1600){
   analogWrite (6, a);
 }
 for(int a = 0; a<256; a++)
 {
  analogWrite(6, a);
 {
 if(pressure_bar < 1600){
  analogWrite (6, a);
 }
 for(int b = 255; b>=0;b--)
 {
 analogWrite(9, b);
 {
 if (pressure_bar == 1600){
   analogWrite (9, b);
 if(pressure_bar < 1600){
   analogWrite (9, b);
}
 for(int b = 0; b<256; b++)
 {
   analogWrite(9, b);
 {
if (pressure_bar > 1600){
   analogWrite (9, b);
   }
  }

Welcome to Arduino:SE.  Your life would be so much easier if you indented your code correctly.  It would then be fairly obvious where the missing } should be.

do you help me?

@Duc Hoang: Are you formatting your code correctly, that it is readable? Select in in the question editor and click on the {} button

Never before have I see such random use of brackets... ;)

do you help me? .... you have to start by helping yourself ..... read and understand the answers below ..... do not copy and paste code without thinking

also, what text editor/IDE are you using? Some of them highlight matching brackets abut not Arduino's one

Some guidelines for programming:
Start each statement on a new line
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup() {
Serial.begin(9600);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
} void loop(){
sensorVal = analogRead(A1);

Serial.print("Sensor Value: "); Serial.print(sensorVal);

float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: "); Serial.print(voltage);

float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
float pressure_bar = pressure_pascal/10e5;
Serial.print("Pressure = ");
Serial.print(pressure_bar);
Serial.println(" bars");
Serial.print("Pressure = "); {
for(int a = 255; a>=0;a--) {
analogWrite(6,a);
if (pressure_bar = 1600){
analogWrite (6, a);
if (pressure_bar > 1600){
analogWrite (6, a); }
for(int a = 0; a<256; a++) {
analogWrite(6, a); {
if(pressure_bar < 1600){
analogWrite (6, a); }
for(int b = 255; b>=0;b--) {
analogWrite(9, b); {
if (pressure_bar == 1600){
analogWrite (9, b);
if(pressure_bar < 1600){
analogWrite (9, b); }
for(int b = 0; b<256; b++) {
analogWrite(9, b); {
if (pressure_bar > 1600){
analogWrite (9, b);
} }

Use brackets and align them
.. so each pair of { and } is on the same column and align code with brackets to be indented 2, 3 or 4 spaces
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
}
void loop()
{
  sensorVal = analogRead(A1);

  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: ");
  Serial.print(voltage);

  float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
  float pressure_bar = pressure_pascal/10e5;
  Serial.print("Pressure = ");
  Serial.print(pressure_bar);
  Serial.println(" bars");
  Serial.print("Pressure = ");
  {
    for(int a = 255; a>=0;a--)
    {
      analogWrite(6,a);
      if (pressure_bar = 1600)
      {
        analogWrite (6, a);
        if (pressure_bar > 1600)
        {
          analogWrite (6, a);
        }
        for(int a = 0; a<256; a++)
        {
          analogWrite(6, a);
          {
            if(pressure_bar < 1600)
            {
              analogWrite (6, a);
            }
            for(int b = 255; b>=0;b--)
            {
              analogWrite(9, b);
              {
                if (pressure_bar == 1600)
                {
                  analogWrite (9, b);
                  if(pressure_bar < 1600)
                  {
                    analogWrite (9, b);
                  }
                  for(int b = 0; b<256; b++)
                  {
                    analogWrite(9, b);
                    {
                      if (pressure_bar > 1600)
                      {
                        analogWrite (9, b);
                      }
                    }

Remove superfluous brackets
As you can see, you are having some superfluous/missing brackets. What you want is probably something like:
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
}
void loop()
{
  sensorVal = analogRead(A1);

  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: ");
  Serial.print(voltage);

  float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
  float pressure_bar = pressure_pascal/10e5;
  Serial.print("Pressure = ");
  Serial.print(pressure_bar);
  Serial.println(" bars");
  Serial.print("Pressure = ");

  for(int a = 255; a>=0;a--)
  {
    analogWrite(6,a);
    if (pressure_bar = 1600)
    {
      analogWrite (6, a);
    }
    if (pressure_bar > 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int a = 0; a<256; a++)
  {
    analogWrite(6, a);
    if(pressure_bar < 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int b = 255; b>=0;b--)
  {
    analogWrite(9, b);
    if (pressure_bar == 1600)
    {
      analogWrite (9, b);
    }
    if(pressure_bar < 1600)
    {
      analogWrite (9, b);
    }
  }
  for(int b = 0; b<256; b++)
  {
    analogWrite(9, b);
    if (pressure_bar > 1600)
    {
      analogWrite (9, b);
    }
  }
}

Remove duplicate code
In the if statement, you perform twice the same code (both you send an analogWrite with the same value, so the code (from the for loops can be reduced to:
  for(int a = 255; a>=0;a--)
  {
    analogWrite(6,a);
    if (pressure_bar >= 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int a = 0; a<256; a++)
  {
    analogWrite(6, a);
    if(pressure_bar <= 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int b = 255; b>=0;b--)
  {
    analogWrite(9, b);
    if (pressure_bar <= 1600)
    {
      analogWrite (9, b);
    }
  }
  for(int b = 0; b<256; b++)
  {
    analogWrite(9, b);
    if (pressure_bar >= 1600)
    {
      analogWrite (9, b);
    }
  }
}

Unclear
What is unclear why you first write an analog value, and directly afterward (in each if) you write the same value. I'm not sure what you really want here. Either you want to write to a different pin, or you want a delay (to have the value having some effect), I'm just not sure.

Look at your open brackets { vs closing brackets, }. You need the same number of each. If have this in the Arduino IDE and use CTRL-T, they are somewhat easy to find.  I just looked, and I can spot them pretty easily.
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
Serial.begin(9600);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
}
void loop()
{
sensorVal = analogRead(A1);
Serial.print("Sensor Value: ");
Serial.print(sensorVal);
float voltage = (sensorVal*5.0)/1024.0;
Serial.print("Volts: ");
Serial.print(voltage);
float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
float pressure_bar = pressure_pascal/10e5;
Serial.print("Pressure = ");
Serial.print(pressure_bar);
Serial.println(" bars");
Serial.print("Pressure = ");
{                            << bracket for what?
for(int a = 255; a>=0;a--) { << missing closing bracket
  analogWrite(6,a);
  if (pressure_bar = 1600){   << missing closing bracket
   analogWrite (6, a);
     if (pressure_bar > 1600){
     analogWrite (6, a);
     }
  for(int a = 0; a<256; a++) {
    analogWrite(6, a);
    {                      << wrong direction
    if(pressure_bar < 1600){
       analogWrite (6, a);
    }
  for(int b = 255; b>=0;b--) {
    analogWrite(9, b);
   {                           << wrong direction
    if (pressure_bar == 1600){ << missing closing bracket
      analogWrite (9, b);
      if(pressure_bar < 1600){ << missing closing bracket
        analogWrite (9, b);
    }
   for(int b = 0; b<256; b++) {
     analogWrite(9, b);
   {                            << wrong direction
   if (pressure_bar > 1600){
     analogWrite (9, b);
   }
}  << closing bracket for loop


text:
Osepp DS1307 RTC program error (tmElements_t tm; does not name a type)
Using a basic 1307 SetTime program, and ran into a problem (first time programming a module).
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

const char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

tmElements_t tm;

void setup() {
  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

And I got the following
"tmElements_t tm;" does not name a type.

According to example ReadTest/ReadTest.ino, you have to include
#include <TimeLib.h>

See also comment from Alexander below (unchecked by me) that Time.h needs to be referenced.

Added that to the code, and it tells me there is no such file or directory.

Maybe you used another library (you could try this one instead?) I never used this or the other library myself btw.

Arduino Studio also need to reference Time Library.

I'm pretty sure I used the right library, and it's in the Arduino library folder. Changed it to <TimeLib.h> and ran into the invalid library issue. I put on my TFT shield and tested the examples for that and it ran fine. Maybe something else that I am missing... First time wiring up a module.


text:
Send HTTP request from Arduino Ethernet to server on PC
I am simply trying to send a simple HTTP request from an Arduino Uno with w5500 Ethernet Shield to a local server running on my PC.
The two are connected via a crossover ethernet cable and I am able to host a server on the Arduino that is accessible from my PC browser. Now I am trying to use the PC as a server and the Arduino as the client.
Using the simple WebClient example, I can send a successful GET request to google.com from the Arduino.
Here is what I am trying that is failing:
1 - Start a local server via running http-server in my command prompt. That successfully starts a server at 192.168.56.1:8080 that I can access via my browser
2 - Change the Web Client example to use
IPAddress server(192,168,56,1);

and change the port to
if (client.connect(server, 8080))

3 - Run this Arduino sketch. The connection fails and I don't know why. I have allowed port 8080 full input access through the Windows firewall.
Any ideas?

Edited your question to remove the misuse of the term "localhost" - that by definition refers to a computer talking to itself on the loopback interface, which is not what you are doing here.

Thank you for the corrections! You are both absolutely correct and that helps my understanding of localhost

What web server are you running on your PC.  There is one that comes with Visual Studio that will only accept connections from the localhost.  Can you use another device (i.e. phone) and try and connect to the web server?  Also what is the IP address (& mask & Default Gateway) of the Arduino?

I am running a simple node server (https://www.npmjs.com/package/http-server) for initial testing just to figure out how to get it all connected. I cannot connect via my phone (by going to 192.168.56.1:8080) but I may be missing a step. They are on the same Wi-Fi connection and the Windows firewall is off

The answer was simple. Instead of trying to connect to the IP address of the local server (192.168.56.1) I had to use the IP address of the ethernet connection between the Arduino and the PC (found using the ipconfig command on the command prompt).


text:
HM-10 only works when holding button
My HM-10 bluetooth module is behaving weird.
In order to have it operate normally, I have to keep holding the small black button on it. If I ever release the button, it just disconnects from my phone (if it was connected) and doesn't show on the bluetooth devices list anymore, and its red LED light becomes low, not bright as usual.
It operated normally before.
How can I fix this?
What would some possibles causes be for this weird behavior?
UPDATE: picture showing the button on lower right corner.

What button? I see no button on the HM-10...

@Majenko I uploaded a picture

That isn't on the HM-10, that's on the breakout board the HM-10 is soldered to. No idea what the button is supposed to do, since I don't see it on any of the breakouts on google...

I just had to connect the RX/TX jumpers. There was no real issue.
I though connecting the power jumpers was enough to just see HM-10 on my phone, since I didn't care about any data. Turns out if the RX/TX jumpers are not connect, the module behaves weird.

I'm sure everyone is glad you solved your problem, but this isn't really a valid answer - there are no apparent "RX/TX jumpers" in your picture.  To be a valid answer, this needs to be something which could make sense to someone else holding that module, and not only to you.


text:
ATtiny85 MIDI IN with less than 3V -can it be done?
I've been trying to add a MIDI INput to an ATtiny-based synthesizer, powered by a CR2032 battery (3v) and running softwareSerial.
Currently I'm using an H11L1 optocoupler, which works fine at 5v, but I am missing notes at 3V; I'm not sure whether the problem is the optocoupler, or that the ATtiny can't establish proper communication on that voltage; any pointers will be much appreciated :)

This is what parametric searches on electronics suppliers' websites are for. And what does this have to do with Arduino anyway? This is both a general electronics question and a shopping question: doubly off-topic.

I thought it would be better to ask a generic question, but it does relate to an ATtiny-powered synthesizer, and MIDI is a popular topic for Arduino enthusiasts. As ever lower voltage MCUs are becoming commonplace, I believe it'd be very useful for the community to get an update on the devices that work with them.

Generic questions belong on electronics.stackexchange.com - however it would get closed there as a shopping question.

if asking in this way was a mistake on my part, I apologize. Maybe it's worth keeping it alive on the merit of the interest people have shown on it already, though.

The H11L1's minimum supply voltage is 3 V.
There are low-power optocouplers like the TLP2361, but event those do not go below 2.7 V. (And those limits are actually designed for 3.3 V ± 10 % or 3.0 V ± 10 %.)
To get a high-speed optocoupler for lower voltages, you have to build it yourself from discrete parts, e.g.:

(R1 is sized for the PC817-A's minimum CTR of 50 %; higher CTRs should use a lower value for R1. Q1 can be any random small-signal transistor. Adjust R2 for about 1 mA, depending on VCC.)

What is the purpose of Q1? The proposed circuit has an inverted signal at the output.

The PC817 alone would be too slow; Q1 has a lower input impedance and reduces the voltage swing at the PC817's output. The output of this circuit has the same polarity as the original MIDI circuit (both transmitter and receiver are inverting).

If the load is a digital input which has high internal resistance. Then Q1 is not needed as a buffer?

When putting a pull-up resistor directly on the PC817's output, it would be too slow. Q1's input impedance is its base, as seen by the PC817. The optocoupler does not provide a voltage signal but is used as a current source to reduce its Miller capacitance.


text:
Detect button on a ground line (reverse eng)
I've found a circuit board that has a couple of circuits (buttons, IR Receiver, LED, USB). The thing is that following the line for interfacing the buttons I came across what seems to be like buttons that are connected only to the ground line of the PCB while the other end is a free pin cable.
Is there a way for the arduino to detect the ground when the button is pressed or a way to detect a short of some kind? There is a smd and a resistor on both buttons.
Circuit:
Main Ground-----Button-----SMD Capacitor-----Resistor(101)-----Free Pin
Thanks in advance!
Edit: Circuit Board

Just connect the ground to the ground on the arduino, and the free pin to a IO pin. Enable the pull-up resistor on that pin using pinMode(<nr>, INPUT_PULLUP);. If the button is not pressed, you will read a HIGH. If the button is pressed you will read a LOW.

Exactly what I wanted. Simple explanation! The internal_pullup thing was the thing that bothered me the most but it's all explained now. So thanks! Until I can confirm this I will refrain from accepting this answer :)

That's fine. Good luck on your project.

It sounds like you might have a PCB with debounced switches on them. One such circuit for debouncing switches looks like this:

That circuit and more about switch debouncing can be found here.
A debouncer basically masks the problem of switch "bounce" which is what happens when the contacts get close and the circuit is quickly closed and opened in rapid succession until a firm connection is obtained. Its a natural problem  mechanical switches.
If that's not quite right, maybe you could help us help you better by posting a photo of the board in question.

Well I'll do some research on debouncing... You can see my edit for further analysis on the circuit! Thanks for your concern!

I did some research on the subjects and I came with a solution: I borrowed the code from here and made some modifications to fit my needs.
const int buttonPin = 6;
const int buttonPin1 = 7;

int previousReading = HIGH;
int previousReading1 = HIGH;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin1, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int reading = digitalRead(buttonPin);
  int reading1 = digitalRead(buttonPin1);

  if (previousReading == HIGH && reading == LOW) {
     Serial.println(HIGH);
  }

  if (previousReading1 == HIGH && reading1 == LOW) {
     Serial.println(LOW);
  }

  previousReading = reading;
  previousReading1 = reading1;

}


text:
How to filter a blank line received over serial - ESP8266
How can I filter a garbage completely blank line over my serial data? It comes from the wifi module ESP8266
How I read data:
  while (Serial1.available()){
       String inData = Serial1.readStringUntil('\n');

       Serial.println("Got: " + inData);

  }

Here is my common output:
Got: AT+CIPSEND=6
Got:
Got: OK
Got: >
Got: Recv 6 bytes
Got:
Got: SEND OK
Got:
Got: +IPD,21:Volume From: 99 To 89AT+CIPCLOSE
Got: CLOSED
Got:
Got: OK

That question may be too broad, and lacking in relevant context, for a meaningful answer to be provided.  Eg, we don't know if just suppressing all white space would work for you.  What kind of data, in what format, needs to be passed through the filter?

It's just a blank line / newline that prints between responses to my commands. I only want to get rid of that line. The only way to do it is to filter cos I don't have control over the firmware. I'll add some output. Thanks for pointing that out.

It might be a \r \n, carriage return and new-line. So effectively, the cr+lf is printed out as two blank lines, one cr and one lf. You may try String inData = Serial1.readStringUntil('\r'); but other than that, why even bother?

You are right in your assumption! It's a combination of both. I'll give it a try! For me the right solution is to filter any newline and concentrate on regex. It's quite difficult but it's working

inData.trim();
if( inData.length() > 0 ){
   Serial.println("Got: " + inData + "\n");

::trim() removes all leading and trailing whitespace characters including newlines. A line of [zero or more whitespace] + [newline] will get trimmed to the null string. If the result isn't null, then append the stripped off newline and print it. Note that this will flatten any indentation or vertical spacing that was supplied in the incoming text.

Worked like charm! Thanks! Since I don't want to process any blank line/newline I just removed the "+ \n"  since "println()" does it  automatically

You're right - missed that. (oops!). Glad you got it working.

Don't worry It's alright. Thanks for your effort


text:
Parse data from sensor without delimeters
Im using a variant of Arduino Due embedded on a ARM (Udoo). And I have connected a Medlab SPO2 Pearl 200 sensor to Serial1.
Im just trying to parse input from Serial1 to Serial, in a human-readable format (Hexadecimal).
The protocol is described in this image:

And using this Arduino code I reveice two times the "no finger detected line"
int lineLength = 16;
int spo2read[16];
int readed = 0;
 if (Serial1.available()) {
    int inByte = Serial1.read();
    if (readed < lineLength) {
      spo2read[readed] = inByte;
    }
    readed++;
    if (readed == lineLength) {
      Serial.print("SPO2: ");
      for (int i = 0; i <= lineLength; i++) {
        Serial.print(spo2read[i], HEX);
        Serial.print( delimeter);
      }
      Serial.println("");

      readed = 0;
    }

  }

Output with no finger is:
SPO2: A,FB,2,F9,0,FA,0,FC,A,FB,2,F9,0,FA,0,FC,0,

Buf if I put my finger, all is messed up:
SPO2: 7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,
SPO2: 36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,
SPO2: 24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,
SPO2: 35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,
SPO2: 5E,60,61,F9,0,FA,0,FC,1A,FB,0,F8,62,62,62,63,0,

Sensor doesn't sends a \n or \r so I don't know exactly how to parse the data

It says there is a marker byte. You have to look for the marker byte to know when the message has ended.

as per http://www.medlab-gmbh.de/english/downloads/pearl100_144.pdf page 13 marker bytes and example C code page 16 are values greater than or equal than F0

I have used the source code available on the Medlab web, and do some "modifications" to be Arduino compatible.
I dont wanna the waveform data, because my final program will do the waveforms acording the data received, so I don't "listen" to the waveform packet
boolean startbyte = false;
byte buf = 0;

  while (Serial1.available() > 3)
  {
    buf = Serial1.read();
    if (buf > 0xfc)
    {
      buf = Serial1.read();
    }

    if ((startbyte == true) && buf > 0xF7)
    {
      startbyte = false;
    }

    if (buf > 0xf7 && startbyte == false)
    {
      //startbyte = true;
      if (buf == 0xf8)
      {
        startbyte = true;
      }

      if (buf > 0xf8)
      {
        byte RX = buf;
        buf = Serial1.read();
        if (buf > 0xfc)
        {
          buf = Serial1.read();
        }

        if (RX == 0xf9)
        {
          //SPO = buf;
          Serial.print("SV:");
          Serial.print(buf, DEC);
          Serial.println();
        }

        else if (RX == 0xfa)
        {
          //Pulse = buf;
          Serial.print("SPV:");
          Serial.print(buf, DEC);
          Serial.println();
        }
        else if (RX == 0xfb)
        {
          //Status = buf;
          Serial.print("StV:");
          Serial.print(buf, DEC);
          Serial.println();
        }

        else if (RX == 0xfc)
        {
          //quality = buf;
          Serial.print("QV:");
          Serial.print(buf, DEC);
          Serial.println();
          Serial.println();
        }
        else { }
      }

    }
    else if (startbyte == true)
    {
     //Waveform data
    }
  }

actually I don't think it is all mixed up
as per geometrikal use the markers to parse the data stream
I believe your above sample data started mid-stream during the 0xF8 of the wave form.
F8,...
...,7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,5E,60,61
F9,0
FA,0
FC,1A
FB,0
F8,62,62,62,63,0,...

I believe reading this as a finite length does not portray the data for easy interpetation. Given that 0xF8 is a variable length protocol.
Where the reparse of your data initially appears to be legitimate parse.
That said I do read the SPO2, Pulse as zero. Where it may be likely the sensor has not finished its reading and auto gain cycles.


text:
Break statement terminating loop()
I am experiencing some very strange behavior with my arduino. I have a switch-case statement in the loop() method, and the break methods are not only breaking out of the case block, but also out of the loop() statement. Is this normal, and if so, how can I edit the structure so it doesn't do that?
My code structure looks like this:
void loop(){
  switch(int i){
    case 1:{
      //do something
      break;// this also breaks out of the loop() method.
    }
  }
}

I'm closing this because the source of the problem turned out to be unrelated to the original question.

I just realized it wasn't the sketch, but a faulty SD card reader on my computer corrupted my SD card. BIG TIME.

Ok, I guess you should accept your own answer. That or delete the question. I still stand by my statement that you need a way of displaying debug information or you're going to drive yourself crazy.

@DuncanC Yeah, good point.

@DuncanC I have to wait one more day.

Your sample is too simple to test your hypothesis (which is wrong, by the way.)
Set up serial output so you can test:
void loop()
{
  Serial.println("Before switch statement");
  int i = 1;
  switch (i)
  {
    case 1:
      Serial.println("In case 1");
      break;
    default:
      Serial.println("In default case");
  }
  Serial.println("After switch statement.");
}

You can even add an outer for loop to make things a little more complicated:
void loop()
{
  Serial.println("Before for loop statement");
  for (int i = 1; i< 10; i++)
  {
    Serial.print("In for loop before switch, i = ");
    Serial.println(i);
    switch (i)
    {
      case 1:
        Serial.println("In case 1");
        break;
      default:
        Serial.println("In default case");
    }
    Serial.println("After switch statement.");
  }
}

Examine the output on the serial monitor of your computer. You should find that the "After switch statement" line always appears after the "before switch..." line in both versions of the code.
Break breaks from the innermost scope. If you have nested levels of scope, like a function and then a switch statement inside the function, the break statement breaks out of that inner level. In the second example, the break broke out of the switch but the for loop kept running.
This is very basic C programming and not specific to Arduino.

The thing is, I'm running the MCU of my arduino in a completely different board, so I can't use the serial monitor.

Uh-oh. Hook up an LCD display then? Or better yet, get a C compiler for your computer and learn the basics of C that way. As I say, your questions are on vanilla C, and not at all specific to the Arduino. You're going to spin yourself in circles trying to develop when you don't know the language and can't even add debugging statements. (I do my day job with an integrated symbolic debugger that lets me add breakpoints, examine variables, etc. The Arduino with it's limited debugging tools is a step backwards. Take away print statements and you're stumbling around in the dark.)

Never mind!! I just realized the sketch isn't broken, but instead one of my SD cards was corrupted.