message:
Why these specific voltage divider resisters needed for Arduino Uno RX TX pins?

I have an Arduino Uno attached to a Parallax Boe-Bot shield, and plugged into the shield breadboard, the Parallax WX ESP8266 Wi-Fi SIP.

When I attach the DO/DI pins of the ESP8266 board to the RX/TX pins of the Uno, it does not work without a very narrow range of resisters in a voltage divider configuration. I'm trying to learn more about electronics and I would like to know, why these specific values in this specific case?

The DI/DO pins of the SIP are documented as "SIP - output high (set by Vin voltage, either 3.3 or 5.0 V), low 0 V. Input high >Vin/2, input low <Vin/2"

When I attach the Parallax shield 5V to the SIP Vin, and the DO to a 220 resister to RX, and also DO to a 1K resister to ground, and DI to 220 to TX and also DI to 1K to ground, serial communications works fine.

If I use the shield 3.3V to SIP Vin, it does not work.

If instead of 220 / 1K, I use 470 / 2K, or 4.7K / 10K, for example, it doesn't work.

If I only set up the voltage divider on the RX pin, it doesn't work.

However, if instead, with either 5V or 3.3V to the SIP Vin, and no resisters, I can run the Uno TX direct to the SIP DI, and the SIP DO to a digital pin, and run that digital pin with SoftwareSerial, for example.

I can run both DI and DO directly with SoftwareSerial, and either 5V or 3.3V to supply Vin.

It's only when I want to connect DO/DI direct to use the Uno's UART (because I don't want serial-driving interrupts to interfere with servo pulses) that I have to carefully select these resisters (through trial and error) and be sure to power with the 5V. Some combinations get communication with errors, but just these specific values (out of the resisters I happen to have on hand) work.

I understand that it is something to do with 3.3V vs TTL serial, but I would like the details. (I will be picking up a logic level converter to try in place of the voltage divider.)

EDIT:

By "not working" -- in all but two cases, with fresh batteries, the SIP seems to get data from the Uno TX, and the DO lamp on the SIP flashes, but Serial.read() sees nothing on the Uno regardless of configured rates. In one of the two cases (I can't recall which) unintelligible, incomplete data is read on the RX pin, and in the last, good case -- where *both* pins have voltage dividers and the SIP is powered by the 5V line of the Arduino shield (for the Boe-bot) -- with those specific resister values -- the data from the SIP DO is received on the Serial, from pin RX.

body:
The output of a voltage divider is:

Vout = Vin * R2 / (R1 + R2)

Where R2 is the resistor in your case which is connected to ground.

See: [Sparkfun - voltage dividers](https://learn.sparkfun.com/tutorials/voltage-dividers)

Now in your example of 220 / 1k you have a multiplier of:

    Vout = Vin * 1000 /1220 = Vin * 0.82

If both boards are running at 5V you don't need the voltage divider at all, but if you do use it the output would be:

    Vout = 5 * 0.82 = 4.1

Now the Atmega328P chip on the Uno has the electrical characteristics defined in the datasheet, amongst others is that a digital pin high has to have a minimum of 0.6 * Vcc (if Vcc is in the range 2.4V to 5.5V)

So if Vcc is 5V (which it is on the Uno) you have to have 0.6 * 5 (that is, 3V) as the minimum for it to be recognised as high.

So, using the voltage divider of 220/1k you have a high still being 4.1V which is in the range 3 to 5V.

However if you have the board set to 3.3V then the output of the voltage divider will be 3.3 * 0.82 = 2.76V which is too low to be recognized as high.

For sending serial from a 3.3V board to a 5V board, simply omit the voltage divider, and then the 3.3V (for high) is in range (it has to be 3+ volts).

However for sending *from* a 5V board *to* a 3.3V board you *do* need a voltage divider (or level shifter) because 5V is too much for a 3.3V board. You can use a [voltage divider calculator](http://www.ohmslawcalculator.com/voltage-divider-calculator) to simplify the maths.

Something like 1k/1.8k would be about right.

    Vout = 5 * 1800 / 2800 = 3.21

---

According to [the documentation for the Parallax WX ESP8266 Wi-Fi Module](https://www.parallax.com/sites/default/files/downloads/32420-Parallax-WX-WiFi-Module-Guide-v1.0.pdf):

> **(9) Level shifters and buffers**
>
> To ensure maximum compatibility with a wide range of 3.3V and 5V microcontrollers and development boards, the Parallax Wi-Fi module includes voltage level shifters and buffers to ensure that the logic voltage levels at the SIP header are set by the VIN voltage level. If you
supply 3.3V to VIN, then the IO pins logic voltage level will be 3.3V. If you supply 5V to VIN, then the IO pins logic voltage level will be 5V

I don't see why you need to use a voltage divider or level shifter in the first place.

---

## References

* [Atmega328P datasheet](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) (32.9 MB)

* [Sparkfun - voltage dividers](https://learn.sparkfun.com/tutorials/voltage-dividers)

* [Voltage divider calculator](http://www.ohmslawcalculator.com/voltage-divider-calculator)

* [Another voltage divider calculator](https://www.allaboutcircuits.com/tools/voltage-divider-calculator/)

* [Voltage dividers - Wikipedia](https://en.wikipedia.org/wiki/Voltage_divider)


sender: user

message:
Adafruit 128x64 OLED not turning on

I ordered a 128x64 pixel OLED display from Adafruit and wired it according to their [guide][1]. (To an Arduino Uno) I'm using SPI right now and the display will not turn on or do anything. I haven't tried i2C, but I don't think that should make a difference. Maybe I will if nothing else works. I've installed the two [libraries][2] from the guide and am running the SPI 128x64 example. I've tried to find people with this same issue but I haven't found that much about it. Any help would be greatly appreciated!

Edit: Added pictures. I've used header pins in the past in case anyone is wondering if the connection using these wires isn't good, but the pins did not work either, so it's not a bad connection.

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

  [1]: https://learn.adafruit.com/monochrome-oled-breakouts/wiring-1-dot-3-128x64
  [2]: https://learn.adafruit.com/monochrome-oled-breakouts/arduino-library-and-examples
  [3]: https://i.stack.imgur.com/39XWs.jpg
  [4]: https://i.stack.imgur.com/bdF1H.jpg

sender: assistant

body:
I know this issue and understand it well.

If the module is genuine from Adafruit then it should definitely work, if not then once try this library https://github.com/olikraus/U8glib_Arduino

This library has very good documentation. Further if it does not work, attach the picture of wiring.


body: Wiring is your problem. Use soldering iron/solder and flux. Solder your wires. Intermittent connections and accidental shortages with current setup may damage your Arduino and display (and possible your PC/laptop).


body:
Its not every time fault of hardware, check the program as well. Load example test program and try again.
[https://iotforgeeks.com/i2c-oled-display-not-working/][1]
helped me to resolve the same issue.

  [1]: https://iotforgeeks.com/i2c-oled-display-not-working/


message:
Locking ATmega328 from reading back the hex file

I want to completely block the access to an ATmega328. How do I do this?

I have Atmel ICE, AVR studio 7 and Arduino.

Bootloader - optiboot_atmega328
Fuses(without lock) - 0x05, 0xDE, 0xFF

Steps I am executing:

1. Program fresh ATmega328 with bootloader using Atmel Studio.
2. Burn the fuses as mentioned above.
3. Go to Arduino and program the code.
4. Come back to Atmel Studio >> lock bits >> enable no further programming and verification.>> Fuse bits>> disable reset.

Is the above way OK? Or should I add something to the above?

I have programmed the fuse bit with "Further programming and verification disabled". I read out the hex file and it does not match even I programmed the same hex into a different micro and it didn't work. This seems to be fine. But will high Voltage programmer brick this wall?

Note: When I program the above fuse bit. I am unable to disable the RESET or SPI. It says **one or more register differ**

I want avoid a readback via high voltage programmer too.

**I have too many people to steal my code I want to avoid it. Kindly help**

Siddharth

body:
Locking out programming prevents writing, and locking out verification prevents reading, via all programming methods.

Note that there is no way to prevent *erasing* the chip, which will clear both the lock bits and the flash.


body:
"Locking" the chip only has any effect when using one of the hardware programming interfaces. Yes, it prevents anyone with a programmer from reading the data from the chip (verify disabled).

However, it does not stop software on the chip itself from reading the contents of the chip. And that includes the bootloader.

Since you use a bootloader it is possible (if implemented in your bootloader, I am not familiar with what is implemented in Optiboot) to use the bootloader to read the contents of the chip through USB.

To properly protect your software you will have to either remove the bootloader and only program through a hardware programmer or ensure that the bootloader has no method to read or otherwise access the flash memory of the chip (intentional or otherwise).


message:
Stop Buzzer after some seconds/time?

This is a "water level alarm/display" sketch using and Arduino and ultrasonic sensor.
The buzzer gets on when the water level hits 100% or more.
But most of the time the water level will stay @ 100%, and I dont want the buzzer to run for long time.
How can I set the buzzer to make sound only for 15 seconds ?
It should turn off after 15 seconds, even if the water level is @ 100%

    #define trigPin 8
    #define echoPin 9
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    int BUZZER = 10 ;

    void setup(){
          int duration,distance,percentage,heightTank;
          Serial.begin (9600);
          pinMode(trigPin,OUTPUT);
          pinMode(echoPin,INPUT);
          lcd.begin(16,2);
          lcd.print("HELLO");
            pinMode(BUZZER,OUTPUT);
    }

    void loop(){
          int duration,distance,percentage,heightTank,deviation;
          //You'll probably want to change the next 2 lines.
          // The first one is the max. level of the water.
          // The next one is how high the sensor is above that max. level.
          heightTank=65;
          deviation=4;

          digitalWrite(trigPin,HIGH);
          delayMicroseconds(1000);
          digitalWrite(trigPin,LOW);
          duration=pulseIn(echoPin,HIGH);
          distance=(duration/2)/29.1;
          percentage=100-(((distance-deviation)*100)/heightTank);
          Serial.println(distance);
          Serial.println(percentage);
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Current tank");
          //lcd.print(distance);
          //lcd.print(" cm");
          lcd.setCursor(0,1);
          lcd.print("level: ");
          lcd.print(percentage);
          lcd.print(" %");
          delay(1000);

          digitalWrite(BUZZER,HIGH);
      if (percentage > 99) {digitalWrite(BUZZER,HIGH); delay(100); digitalWrite(BUZZER,LOW); delay(100);}
      else  {digitalWrite(BUZZER,LOW);}
      }

body:
Try this at the end of `loop`

    static unsigned long lastBuzzer = 0;

    if(percentage > 99 && lastBuzzer == 0) {
     lastBuzzer = millis();
    }

    if(percentage > 99) {
     if(millis() - lastBuzzer < 15000L) {
      digitalWrite(BUZZER,HIGH);
      delay(100);
      digitalWrite(BUZZER,LOW);
      delay(100);
     }
    } else  {
     digitalWrite(BUZZER,LOW);
     lastBuzzer = 0;
    }

lastBuzzer is the last buzzer activation time (in ms). It's use to control that buzzing stop after 15 seconds. It's zero when the percentage is < 99; it's not zero when percentage >= 100.

(Not tested).
(Two `if's` instead of one for clarity).


body:
For this you will have to implement a _finite state machine_. This is a
very common paradigm in the embedded world. I recommend you start by
studying this tutorial: [The Finite State Machine][FSM], by Majenko.

Four your particular problem, I would implement a machine with three
states: IDLE, ARMED and ALARM, the ALARM state being the only one in
which the buzzer is on. The transitions would be:

* ARMED → ALARM when the level hits 100%
* ALARM → IDLE after 15 seconds spent in the ALARM state
* IDLE → ARMED when the level gets below 90%

Note that the only difference between IDLE and ARMED is that the IDLE
state will not go into ALARM when the level reads 100%, as you have to
go through the ARMED state before. The threshold at 90% percent is meant
to add some [hysteresis][]. You can tweak the threshold value to your
taste.

I leave the implementation to you. It should be easy one you have
studied Majenko's tutorial.

[FSM]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/
[hysteresis]: https://en.wikipedia.org/wiki/Hysteresis

------------------------------------------------------------------------

**Edit**: Just to illustrate the generality of the concept, I would like
to point out that the code in Look Alterno's answer can be thought of as
a finite state machine where the state is implicitly encoded into the
variables `lastBuzzer` and `percentage`. The implicit state is:

* ARMED when lastBuzzer == 0
* ALARM when percentage > 99 && millis() - lastBuzzer < 15000L
* IDLE when  percentage > 99 && millis() - lastBuzzer >= 15000L

The line `lastBuzzer = 0` establishes the ARMED state as soon as
percentage ≤ 99. Note that this lacks hysteresis: if the reading
fluctuates between 99% and 100%, the alarm will sound again and again.

I personally prefer using an _explicit_ state variable, as it makes the
code clearer to me. But then, the best approach is whichever makes the
code clearer _to you_.


message:
Checksum is wrong - Air Quality Monitoring Station PMS5003, BME280 | Code review

I working at air quality station. I measure particulate matter with PMS5003 and meteorological parameters with BME280. Everything seems to work just fine, but sometimes program hangs on checksum calculations.

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

I wonder if the problem lies either in my software or in hardware. Can anyone have a look at my code and tell me how I can improve it. Thanks in advance :)

Here's my code:
<!-- language-all: lang-cpp -->

    #include <Arduino.h>
    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

    // needed for library
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
    #include <PubSubClient.h>
    #include <Wire.h>
    #include <SPI.h>

    // BME280 Sensor
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>

    //Constants
    #define TOKEN "TOKEN"
    char thingsboardServer[] = "SERVER_ADDRESS";

    // Settings for PMS5003
    #define LENG 31  //0x42 + 31 bytes equal to 32 bytes
    #define TIMEOUT 10000 //Microseconds to wait for PMS do wakeup

    unsigned char buf[LENG];
    char ergebnisstr[50];

    struct dustvalues {
     unsigned int PM10Val=0; // Byte 4&5
     unsigned int PM2_5Val=0; // Byte 6&7
     unsigned int PM01Val=0; // Byte 8&9
     unsigned int Beyond03=0; // Byte 16&17
     unsigned int Beyond05=0; // Byte 18&19
     unsigned int Beyond1=0; // Byte 20&21
     unsigned int Beyond2_5=0; // Byte 22&23
     unsigned int Beyond5=0; //Byte 24&25
     unsigned int Beyond10=0; //Byte 26&27
    };

    struct dustvalues dustvalues1, dustvalues2;

    //unsigned char gopassive[]={ 0x42, 0x4d, 0xe1, 0x00, 0x00, 0x01, 0x70 }; //don't need here
    //unsigned char readinpassive[]={ 0x42, 0x4d, 0xe2, 0x00, 0x00, 0x01, 0x71 };
    unsigned char gosleep[]={ 0x42, 0x4d, 0xe4, 0x00, 0x00, 0x01, 0x73 };
    unsigned char gowakeup[]={ 0x42, 0x4d, 0xe4, 0x00, 0x01, 0x01, 0x74 };

    // BME280 init
    Adafruit_BME280 bme;

    // Connection to PubSubClient
    WiFiClient espClient;
    PubSubClient client(espClient);

    int status = WL_IDLE_STATUS;
    unsigned long lastSend;

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

        wifiManager.autoConnect("AP", "pass");
        Serial.println("Connected to the network :)");
        delay(500);
        //  pins for RGB diode
        pinMode(12, OUTPUT);
        pinMode(13, OUTPUT);
        pinMode(14, OUTPUT);
        //BME280 sensor check
        if (! bme.begin(0x76)) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
        while (1);
        }
        // set server for MQTT PubSubClient Library
        client.setServer( thingsboardServer, 1883 );
        lastSend = 0;

    }

    void loop() {

        if (!client.connected()) {
        reconnect();
        }
        if ( millis() - lastSend > 30000 ) { // Update and send only after 1 seconds
        getpms5003();
        getAndSendTemperatureAndHumidityData();
        lastSend = millis();
        }
        client.loop();
    }

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Connecting to ThingsBoard node ...");
        // Attempt to connect (clientId, username, password)
        if ( client.connect("Stacja3", TOKEN, NULL) ) {
          Serial.println( "[DONE]" );
        } else {
          Serial.print( "[FAILED] [ rc = " );
          Serial.print( client.state() );
          Serial.println( " : retrying in 5 seconds]" );
          // Wait 5 seconds before retrying
          delay( 5000 );
        }
      }
    }

    void getAndSendTemperatureAndHumidityData()
    {
      Serial.println("Collecting temperature data.");

      // Reading temperature or humidity takes about 250 milliseconds!
      float humidity = bme.readHumidity();
      // Read temperature as Celsius (the default)
      float temperature = bme.readTemperature();

      float pressure = bme.readPressure() / 100.0;

      // Check if any reads failed and exit early (to try again).
      if (isnan(humidity) || isnan(temperature) || isnan(pressure)) {
        Serial.println("Failed to read from BME sensor!");
        return;
      }

      Serial.print("Humidity: ");
      Serial.print(humidity);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(temperature);
      Serial.print(" *C ");
      Serial.print("Pressure: ");
      Serial.print(pressure);
      Serial.print("hPa");

      String temperature1 = String(temperature);
      String humidity1 = String(humidity);
      String pressure1 = String(pressure);

      // Just debug messages
      Serial.print( "Sending temperature, humidity & pressure : [" );
      Serial.print( temperature1 ); Serial.print( "," );
      Serial.print( humidity1 ); Serial.print( "," );
      Serial.print( pressure1 );
      Serial.print( "]   -> " );

      // Prepare a JSON payload string
      String payload = "{";
      payload += "\"temperature\":"; payload += temperature1; payload += ",";
      payload += "\"humidity\":"; payload += humidity1;  payload += ",";
      payload += "\"pressure\":"; payload += pressure1;
      payload += "}";

      // Send payload
      char attributes[150];
      payload.toCharArray( attributes, 100 );
      client.publish( "v1/devices/me/telemetry", attributes );
      Serial.println( attributes );
    }

    bool checkValue(byte *buf, byte leng){
        int receiveSum, checkSum;
        for(byte i = 0; i < (leng - 2); i++){
            receiveSum += int(buf[i]);
        }
        receiveSum += 0x42;
        checkSum = (buf[leng-2] << 8) + buf[leng-1];
        testCheckValue(receiveSum, checkSum);
        if(receiveSum == checkSum){
            return true;
        }
        return false;
    }

    void testCheckValue(int calc, int found){
        byte strSize = 64;
        char strOut[strSize];
        snprintf(strOut, strSize, "Checksum Calculated: %d\nChecksum Found: %d\n", calc, found);
        Serial.print(strOut);
    }

    unsigned int transmitPM(char HighB, char LowB, unsigned char *buf){
     unsigned int PMValue;
     PMValue=((buf[HighB]<<8)+buf[LowB]);
     return PMValue;
    }

    void getpms5003(void){
      unsigned char found=0;

      Serial.println("PMS5003 Wakeup: ");
      Serial.write(gowakeup,7);
      Serial.println();
      Serial.println("gowakeup ist out");
      delay(30000); //Stable data should be got at least 30 Second from wakeup (Datasheet!)
      while (found<2){
       delay(TIMEOUT);
       if(Serial.available()>0){
        if(Serial.find(0x42)){  //start to read when detect 0x42
         Serial.println("0x42 found");
         Serial.readBytes(buf,LENG);
         if (buf[0] == 0x4d){ //second byte should be 0x4D
           found++;
           if(checkValue(buf,LENG)){
            Serial.println("Checksum okay");

            if(found==1){
             dustvalues1.PM01Val=transmitPM(3,4,buf);
             dustvalues1.PM2_5Val=transmitPM(5,6,buf);
             dustvalues1.PM10Val=transmitPM(7,8,buf);

             if (dustvalues1.PM2_5Val <= 36) {
               // digtal write green pin
               digitalWrite(12, LOW);
               // digitalWrite(13, HIGH);
               digitalWrite(14, HIGH);
             }

             if ((dustvalues1.PM2_5Val > 36 ) && (dustvalues1.PM2_5Val <= 80)) {
               // diode change to yellow
               digitalWrite(12, LOW);
               // digitalWrite(13, HIGH);
               digitalWrite(14, LOW);
             }

             if(dustvalues1.PM2_5Val > 84) {
               // diode change to red
               digitalWrite(12, HIGH);
               // digitalWrite(13, HIGH);
               digitalWrite(14, LOW);
             }

             sprintf(ergebnisstr,"PM2.5:Mug/m3\nPM10: Mug/m3\n",dustvalues1.PM2_5Val,dustvalues1.PM10Val);
             Serial.println(ergebnisstr);
             Serial.flush();

             // Just debug messages
             Serial.print( "Sending air quality PM2.5 & PM10 values: [" );
             Serial.print( dustvalues1.PM2_5Val ); Serial.print( "," );
             Serial.print( dustvalues1.PM10Val);
             Serial.print( "]   -> " );

             // Prepare a JSON payload string
             String payload = "{";
             payload += "\"pm25\":"; payload += String(dustvalues1.PM2_5Val); payload += ",";
             payload += "\"pm10\":"; payload += String(dustvalues1.PM10Val);
             payload += "}";

             // Send payload
             char attributes[100];
             payload.toCharArray( attributes, 100 );
             client.publish( "v1/devices/me/telemetry", attributes );
             Serial.println( attributes );
           }
            if(found==2){
             dustvalues2.PM01Val=transmitPM(3,4,buf);
             dustvalues2.PM2_5Val=transmitPM(5,6,buf);
             dustvalues2.PM10Val=transmitPM(7,8,buf);
             sprintf(ergebnisstr,"PM1: Mug/m3\nPM2.5:Mug/m3\nPM10: Mug/m3\n",dustvalues2.PM01Val,dustvalues2.PM2_5Val,dustvalues2.PM10Val);
             Serial.println(ergebnisstr);
             Serial.flush();
            }
          }else{
           Serial.println("Checksum not okay");
           Serial.flush();
           if(found>0)found--;
           delay(500);
          }
         }
       }
       }
       }

      found=0;
      Serial.println("PMS5003 - go to sleep");
      Serial.write(gosleep,7);
      Serial.println();
     }

My hardware:

[![enter image description here][2]][2]

PMS 5003 Datasheet - [http://www.aqmd.gov/docs/default-source/aq-spec/resources-page/plantower-pms5003-manual_v2-3.pdf][3]

  [1]: https://i.stack.imgur.com/GPzMM.png
  [2]: https://i.stack.imgur.com/WPIi6.jpg
  [3]: http://www.aqmd.gov/docs/default-source/aq-spec/resources-page/plantower-pms5003-manual_v2-3.pdf

body:
Cited from the documentation

> Check code=Start character1+ Start character2+……..+data13 Low 8 bits

Please try to change the code as follows:

<!-- language-all: lang-c -->

    ...
    bool checkValue(byte *buf, byte leng){
        int receiveSum, checkSum;
        receiveSum += 0x42;
        for(byte i = 0; i < (leng - 2); i++){
            receiveSum += int(buf[i]);
            receiveSum = receiveSum & 0xFFFF;
        }

        checkSum = (buf[leng-2] << 8) + buf[leng-1];
        testCheckValue(receiveSum, checkSum);
        if(receiveSum == checkSum){
            return true;
        }
        return false;
    }
    ...

Or use the updated code by the same author :[PMS7003-on-Particle][1]

  [1]: https://github.com/MartyMacGyver/PMS7003-on-Particle/blob/master/pms7003-photon-demo-1/pms7003-photon-demo-1.ino


message:
Will a genuine Arduino board have the same issues with High Sierra as other non genuine ones?

I think my question is quite specific to High Sierra. I am very new and have bought a starter Elegoo kit to learn the basics. I did not realise that their boards are not the real thing.

I have an iMac running High Sierra and although the Mac recognises the board (I checked this through the apple menu) every time i try to upload code i get the error message:

*avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00*

I have watched several videos on line that have taken me through installing drivers including one specific to High Sierra. However the problem continues.

Does anyone know if i buy a genuine Arduino board, will i have the issues? Will Arduino just not work with High Sierra.

Any help or advice would be so appreciated by someone very new and trying to learn!

Thank you

Paddy

body:
As long as the firmware on the ATMega16U2 chip is the same as on a Genuine Arduino and the bootloader on the ATMega2560 chip is the same as on a Genuine Arduino then your boards should function exactly the same as a Genuine Arduino.

If you find a Genuine Arduino works but your boards don't then there must be a difference, and that can really only be in the software on the chips - so reprogramming the chips to match a Genuine Arduino would probably help.

I haven't heard reports of High Sierra not working with Genuine Arduino boards, but given the severity of some of the bugs that have crept in recently, it seems likely that more problems are hidden away under the hood that no one really knows about yet.


body:
I use High Sierra on my ageing 2011 MacBook and it works with reputable Arduino clones (it is difficult to get a genuine Arduino in Australia, although compatible Freetronics boards are available from a major retailer).

There were some problems with ARDUINO 1.8.4 but the latest works flawlessly.

Anything with a CH340G chip is out, but then the CH340G don't seem to last anyway.


body:
From reading both your questions, I'm not sure whether you've gotten your board to upload yet.

But here's another data point: I just tried an Arduino Mega r2 and iMac with High Sierra - worked perfectly, first try. Arduino IDE 1.6.12.

In your other question, you said you were getting a solid green LED and a blinking yellow one. The green LED is the power LED. The yellow one is programmable so it sounds like the Blink sketch is already loaded and running.

If you're still getting upload errors, check the Arduino IDE Tools menu and check you hardware selections in the Arduino IDE Tools menu. Here are mine; your /dev/cu.usbmodemxxx number might be different but there should only be one of those if you only have one Arduino plugged in:

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

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


message:
Arduino Servo with Serial

I have an interesting problem. I want to control ESC and servo with Arduino. I'm using HC-12 to communicate with 2 Arduino and I'm using SoftwareSerial on the nano.
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    #include <Servo.h>

    SoftwareSerial mySerial(2, 3); // RX, TX
    Servo esc,servo1;

    String okunan;
    int escval;

    void setup() {
      okunan="";
      esc.attach(9);
      servo1.attach(10);
      mySerial.begin(2400);
      Serial.begin(9600);
    }

    void loop() {
       while (mySerial.available()) {
        delay(3);  //delay to allow buffer to fill
          char c = mySerial.read();  //gets one byte from serial buffer
          okunan += c; //makes the string readString
       }

      if(okunan.length()>0)
      {
        Serial.println(okunan);
        //escval= map(okunan.substring(0,okunan.indexOf(',')).toInt(),0,1023,,2000);

        servo1.writeMicroseconds(map(okunan.toInt(),0,179,1000,2000));

        okunan="";

    mySerial.flush();
      }
      delay(20);
      }

When I use a potentiometer, It works successfully. But When I use with serial and if three digit value(between 0-179, for example, 120) comes from serial(HC-12), motor works and stops continuous and irregular. If the value is under three digit there is no problem.

Also, if I delete the ESC variable(servo) or add a new servo to code, it always starts and stops interestingly(Using or not it doesn't matter. If I add Servo servo2 etc., it is going crazy.

I've tried on Uno. That is the same.

Thanks in advance...

body:
Like Mikael Patel said, `SoftwareSerial` disables interrupts for the entire character receive time.  Bad juju.

[This answer](https://arduino.stackexchange.com/questions/26240#26277) lists the alternatives:

* `HardwareSerial` is always the best.  Simply connect the device to pins 0 & 1 and use the pre-defined `Serial` variable.  On some Arduinos, there are extra HardwareSerial ports, called `Serial1`, `Serial2`, etc.  The UNO only has `Serial`.  `Serial` would not interfere with the Servo.

* [`AltSoftSerial`](https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html) is the best of the software serial libraries.  Only one instance is allowed, and it is must be used on the Input Capture pins (pins 8 & 9 for a Nano).  It would not interfere with the Servo.

*  My [`NeoSWSerial`](https://github.com/SlashDevin/NeoSWSerial) is next best.  It works on any two pins, but only at baud rates 9600, 19200 and 38400.  Receiving characters does not disable interrupts, but transmitting does (i.e., TX would interfere with the Servo).

*  `SoftwareSerial` is the worst choice.  It works on any two pins, but it is very inefficient.  It disables interrupts for the entire time that a character is being sent **OR** received, and it cannot transmit and receive at the same time (unlike all other choices).  This can interfere with other parts of your sketch, other device communications, or with libraries (e.g., Servo).

In your case, I would suggest connecting the HC-12 to pins 0/1 and use `Serial`.  No software serial library required, but you will have to disconnect pin 0 to upload new sketches over USB.  Some people put a switch in that wire so it's easy to upload a new sketch.

If you need debug prints, I would suggest using AltSoftSerial and an extra TTL Serial-to-USB adapter (aka FTDI module) to your PC.  Then print your debug messages to the `AltSoftSerial` variable:

    #include <AltSoftSerial.h>
    AltSoftSerial debugPort; // always pins 8 & 9

       ...

    void loop()
    {
      if (something) {
        debugPort.println( F("something happened!") );

Or, if the HC-12 connection is receive only, don't connect pin 1 (TX).  Then your debug prints won't go to the HC-12.

BTW, don't use `delay` and don't use `String`.  They will get you into trouble sooner or later.


message:
Why would anyone use Arduino in 2017?

Sorry for clickbait question but it really bugs me why Arduino is still a thing in the age of ARM based boards like Pine64, Raspberry Pi, Bannana Pi, Whatever Pi etc.

I'm more or less aware of Arduino capabilities as I used to program PLC controllers but I don't really see any rational reason to use Arduino platform over ARM devboards (unless we need mission-critical level reliability however I believe commercial realtime OSes for ARM boards also exist). Even PLC and in general industrial controllers seem to shift towards platforms driven by actual RT OSes underneath running on powerfull hardware.

Getting 30$ quad core 1.2 ghz ARM board with 512M RAM, ethernet, GPIO, I2C, SPI, USB, SD card and actual Linux OS which can do virtually everything whatsoever over 25$ Arduino Uno board with abacus level performance, similar or inferior i/o, capable of only pretty basic stuff sounds to me like no brainer. Arduino sounds to me like **extremely** cost ineffective solution for almost anything. And I can't seem to find any rational explanation to why people still use such thing now? Maybe as Linux engineer I'm a bit biased towards Unix based solutions because I feel "safe" in this ecosystem but still I think my points are kind of objective no matter if availability of unix itself on platform is considered serious advantage or not.

body:
An arduino board is really a breakout for a micro processor. Microprocessors you can get separately. A rPi is really a full system without that modularity.

There are also other size factors for that breakout board, many of which are much smaller than a rasberry pi and will have a much better battery life. And very often the abacus-level perf and half a dozen GPIO pins is all you really need.

Also some people enjoy having direct control over the chip in a way that a semi-stripped linux OS on a poorly documented platform just doesn't give. Hard realtime when you don't have full control over the system means you need to trust the RT-OS writers to actually hold to their documented deadlines.


body:
This is the ATtiny.

[![ATtiny85][1]][2]

It costs < $1 and is completely capable of *most* tasks that a hobbyist requires of a chip. Truthfully, it’s more than capable of many tasks a pro requires as well. It’s *perfect* for adding just a little bit of smarts to a project. Not every project needs an ARM chip, dual cores, or a Linux distro running. In fact, in *low power* situations, that’s likely the last thing I want. How long does your smart phone battery last? A day? I’ve heard of people powering ATtiny based projects on 3 AAs for over a year!

The Arduino is an excellent little dev board for these micros. For the cost of a few cups of coffee I can have one for my work bench. Heck, I’ve used them at work as dev boards for prototyping. It’s cheap enough to put one on the desk of *every* dev on a project. We can verify our code works *on the target architecture* very early in the dev process. That was unheard of just a decade ago.

  [1]: https://i.stack.imgur.com/o4lZY.jpg
  [2]: http://www.microchip.com/wwwproducts/en/ATtiny85


message:
Does a Sparkfun Redboard Arduino Uno have built-in RTC?

I have a [Sparkfun Redboard][1] (an Arduino Uno like board based on the Atmega328P and programmed with the Arduino bootloader).

I have been trying to make an accurate clock without an RTC with an LCD screen and it's been hard.

Does the Sparkfun Redboard have built-in RTC?

  [1]: https://www.sparkfun.com/products/13975

body: Sparkfun Redboard and Arduino Uno do not have built-in RTC.


body:
The new "[Sparkfun Redboard Turbo][1]" does have an RTC on pins A5 and AREF

  [1]: https://www.sparkfun.com/products/14812


message:
AT Commands HM10 BLE Module - Not working

I got the ble module to work fine following online guide. However when i changed the baud rate: AT+BAUD1 which changed to 19200 however ever since i was not able to get at commands to work.

tried: arduino nano, FTDI programmer, software serial, normal tx, rx

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(8,9); //RX|TX

    void setup(){
      Serial.begin(9600);
      BTSerial.begin(9600); // default baud rate
      while(!Serial); //if it is an Arduino Micro
      Serial.println("AT commands: ");
    }

    void loop(){
      //read from the HM-10 and print in the Serial
      if(BTSerial.available())
        Serial.write(BTSerial.read());

      //read from the Serial and print to the HM-10
      if(Serial.available())
        BTSerial.write(Serial.read());
    }

body:
You changed the baud rate that the Bluetooth module uses to communicate with your Arduino but you forgot to change the baud rate that the Arduino uses to communicate with the Bluetooth module. These must match. From consulting the SoftwareSerial library's [reference page](https://www.arduino.cc/en/Reference/SoftwareSerialBegin), you can see that is set by this line of your code:

<!-- language-all: lang-cpp -->

    BTSerial.begin(9600)

That sets the software serial communication rate at 9600 baud. You need to change it to this:

    BTSerial.begin(19200)


message:
16x2 LCD showing blocks under text

I have a LCD connected to a Arduino Mega 2560 using the instructions in `LiquidCrystal` library. It is not the first time I am using a 16x2 LCD but I never have encountered a problem like this. When I first connect the Arduino Mega to PC I see a row of blocks in first row of LCD which looks like normal to me. Then after that there is a block of white under each character.

Now I have searched a little and saw whole blocks which was due to bad soldering or bad wiring or etc. I have checked soldering and wiring twice. used 3 different LCD's and 2 different Mega's and it is still the same.

Any suggestions?

These are the images from when I turn it on:

[![image1][1]][1] [![image2][2]][2]

**[SOLVED] Update :**

Looks like the POT was broken and did not respond the way it used to. So i replaced `V0` with a 2.5k resistor and connected them to GND.
Here is the updated image :
 [![image][3]][3]

  [1]: https://i.stack.imgur.com/B4eOUm.jpg
  [2]: https://i.stack.imgur.com/kOyOEm.jpg
  [3]: https://i.stack.imgur.com/YluSa.jpg

body:
The row of white blocks is what you get before the screen's initialized. It's normal.

The shadow behind the characters is because you have the contrast turned up too high. Adjust it down a little.


body: If your contrast is not adjustable by a pot, there's a resistor that goes on the contrast pin that controls the level of contrast, which is what is causing the dark blocks.


message:
Programmer only uploading with its own power source

Can anyone explain to me why the following occurs (See image below)?

When I connect the pins according to situation 1, everything works fine and I am able to upload my project. However when I connect the pins according to situation 2 it gives me the following error:

> wrong direction/command: 0x00 0x08, expected 0x01 0x08 esp8266

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

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

Both supply the same constant 3.3V and after the project is uploaded it runs with the pins connected as in both scenarios.

(All the other factors are constant in both scenarios. Think of pulling down IO0 etc.)

body: There's no problem with supplying a separate power supply to the ESP8266 but you always need to connect the grounds between the "programmer" and the ESP8266.


body:
You *must always connect the grounds*. Without the grounds connected, even when using a separate power supply, there can be no circuit. With no circuit, no electrons can flow.

I cover it in detail in [this blog post](https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/).


body:
This will not work for the same reason you can not measure the voltage of a battery by only connecting the measurement device to the positive battery terminal. You always need a ground reference.

Perhaps you were thinking all grounds, no matter where they come from, are the same. This is only true if all your power supplies are grounded. But this is usually not the case. In fact it can be dangerous and can lead to other problems such a [ground loops][1].

So, connect your grounds together and try your circuit again.

  [1]: https://en.wikipedia.org/wiki/Ground_loop_(electricity)


message:
Accesing the USART registers by Arduino

I'm having a hard time understanding how the Arduino libraries are defining the address for accessing the registers of the USART modules.

I cant find definition for `udr(pointer)` as used in the delegated constructor for Hardware Serial. So how does the class gets the underlying address? And what type of declaration is this?

    HardwareSerial::HardwareSerial(
      volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
      volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
      volatile uint8_t *ucsrc, volatile uint8_t *udr) :
        _ubrrh(ubrrh), _ubrrl(ubrrl),
        _ucsra(ucsra), _ucsrb(ucsrb), _ucsrc(ucsrc),
        _udr(udr),
        _rx_buffer_head(0), _rx_buffer_tail(0),
        _tx_buffer_head(0), _tx_buffer_tail(0)
    {
    }

body:
It is handed the addresses when the object is constrcted:

     HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);

`&UDR` is passed as `*udr`. That is then assigned to `_udr` in the initialiser list.


message:
Problem communicating between arduino UNO R3 and Mega 2560 via MAX485

I want to send data between Arduino Uno and Mega via MAX485.

When I set the data Enable pin to HIGH on Mega (to transmit data) and set the same pin on UNO to LOW (to receive data) I can read data from Mega into Uno properly. However, when I want to do it vice versa (send data from uno to mega) can't get any data from Uno into Mega. Tried different pins on both boards but still no answer.

This problem happens when I want to change data Enable pins to low or high inside loop(), I mean when I use for example Uno as permanent master and mega as permanent slave, it works properly but when I try to change them from slave to master on runtime, data cannot be sent from uno to mega!

PS: Im newbie on RS485 and MAX485. Here is my code in MEGA side:

    #include <SoftwareSerial.h>'
    SoftwareSerial mySerial(2, 3);
    String inputS = "";
    boolean stringComplete = false;
    int i = 0;
    bool b= false;

    void setup() {
      mySerial.begin(9600);//Using SoftwareSerial Port
      Serial.begin(9600);
      pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
      digitalWrite(8, HIGH);//DE/RE=HIGH Transmit Enabled M1
    }

    void loop() {
      mySerial.println("MEGA:Hi");
      Serial.println("Hi Sent");
      digitalWrite(8, LOW);
      CheckAndReceive();
      if(stringComplete)
      {
      stringComplete = false;
      inputS.trim();
      Serial.print(inputS);
      Serial.println(": " + String(i++));
      inputS = "";
      }
      digitalWrite(8, HIGH);
        delay(1000);
    }

    void CheckAndReceive()
    {
      while (mySerial.available()) {
        // get the new byte:
        char inChar = (char)mySerial.read();
        // add it to the inputString:
        inputS += inChar;
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
        if (inChar == '\n') {
          stringComplete = true;
        }
      }
    }
This code is supposed to send a string to UNO and listen to it.

**UPDATE:**
UNO cannot send data to MEGA at all. I think there is a problem with my UNO

body:
You have forgotten to add [`mySerial.flush()`][1].

`mySerial.flush()` waits for the transmission of outgoing serial data to complete.

Add it right after you have sent the data and want to change the DE pin status.

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/flush/


message:
How to identify RGBW LED pins?

I have a RGBW LED but I don't know how to identify the negative and the colors pins.

I tried different combinations with an Arduino Uno but it never produce light.

I never used it so I am not sure if its name name RGBW LED.

[![RWBW LED][1]][1]

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

body:
Brand Name: LEDGUHON

Model Number:JH-4RGBW14G

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

  [1]: https://i.stack.imgur.com/5ExcC.jpg
  [2]: https://i.stack.imgur.com/tpqS2.jpg


body:
The pin with a + is the anode of one colour. The three next to it are also anodes.

Each anode is connected to one LED. The cathode of that LED is connected to the pin directly opposite the anode.


message:
Serial monitor in Arduino IDE for RobotDyn ESP8266-Pro via CP2102

I bought a couple of "ESP8266-Pro" micro-controllers from a Chinese company named RobotDyn.  There's no real documentation with them, but I've bought a lot of other stuff from them in the past that worked out really well, so I took a chance.

After some work, I am [finally able to program the board][1] with the Arduino IDE 1.8.1.

The problem is that I am unable to get the serial monitor working to see what's going on with the code.

What do I need to do to get this to work, or is it simply not possible?  In order to program the board, I need to connect EN to VIN, and both IO0 and IO15 to GND.  I assume I have to disconnect that to actually run the board after programming, but I don't know and haven't gotten anything to work yet.

Here's a photo of the board hooked up for programming.  What do I need to do to restart it with the serial monitor working?

[![RobotDyn ESP8266-Pro connected for programming with CP2102][2]][2]

  [1]: https://stackoverflow.com/a/47742473/1480995
  [2]: https://i.stack.imgur.com/H7mXD.jpg

body: You applied connections like it was a plain esp8266. The board has the necessary pull-ups and pull-downs. Connect it at first only to GND, VCC, TX, RX. The button pulls gpio0 LOW to enter flashing mode at power up.


body:
So it seems that the trick to being able to monitor serial output on the RobotDyn ESP8266-Pro is to **NOT** have `DTR` and `CTS` from the CP2102 programmer connected to the board's `RST` and `IO12` pins.

With only the four remaining lines connected (`VCC`, `GND`, `TXO`, and `RXI`), you will see normal serial output on the the Arduino IDE's serial monitor **after uploading firmware completes**.

This works for me with the board set as "Generic ESP8266 Module" or as "NodeMCU 1.0 (ESP-12E Module)".

This still doesn't get you serial monitoring when you just plug in the device, though.  It only works after firmware has been uploaded.  Still working on that.


message:
WS2811 LEDs have the wrong color unless I touch the data wire

This is an electrical/hardware issue, but for background, here's my setup:

I'm using a [Wemos D1 mini](https://www.amazon.com/gp/product/B01N3P763C/ref=oh_aui_detailpage_o00_s03?ie=UTF8&psc=1)
in conjunction with Home Assistant running on a RPi3.  The MQTT setup works fine and the commands are being executed perfectly, but the colors are completely off unless I'm touching the data wire.

For instance, if I request solid blue and am touching the wire, they all turn blue.  If I let go of the wire, the first LED turns red and the rest are a strong green.  If I touch the wire, they go back to blue.
Any colors or patterns requested show likewise confusing changes.

What kind of effect is causing this, and what can I do to fix it?

Using a [Tanbaby 5V 60A](https://www.amazon.com/dp/B017YEOAPA/ref=pd_luc_rh_bxgy_02_01_t_img_lh?_encoding=UTF8&psc=1) for power

Lights are [Alitove WS2811 5V 12mm RGBs](https://www.amazon.com/gp/product/B01NCAG8KV/ref=oh_aui_detailpage_o00_s01?ie=UTF8&psc=1)

body:
It sounds like the bits are getting garbled. There is more than one wire, which one do you mean? Data? Earth? Power?

From the [Adafruit NeoPixels best practices guide](https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices):

*    Before connecting NeoPixels to any large power source (DC “wall wart” or even a large battery), add a capacitor (1000 µF, 6.3V or higher) across the + and – terminals.

*    Place a 300 to 500 Ohm resistor in series between the Arduino data output pin and the input to the first NeoPixel. This resistor must be at the NeoPixel end of the wire to be effective!

*    Try to minimize the distance between the Arduino and first pixel.

*    Avoid connecting NeoPixels to a live circuit. If you simply must, always connect ground first, then +5V, then data. Disconnect in the reverse order.

*    If powering the pixels with a separate supply, apply power to the pixels before applying power to the microcontroller.


message:
Do I have to wire up my WS2812 LED strip in "series", if I want to address each LED individually?

Let's assume I want to make an asterisk (`*`) out of LED strips. I want to control each leg individually, while still being connected to only one GPIO pin. The layout I had in mind, looks like this:

Since it's an LED strip with individually addressable LEDs, I can't just supply 5V, GND, and DATA to the middle and expect it to work (I highly assume).

If I want to do this, I assume I need to keep running them in "series", basically meaning I hook up one of the strips to the Arduino, then at the end of the strip I run a long wire to the start of one of the others and then repeat. Something like this:

but only for the data wire, as I can simply power all of them in the middle. If not, how can I do this? What happens if I hook up 5 strips' DATA to a single GPIO pin on the Arduino? Are all 5 strips shared then, so each strip's first LED is also the first I would turn on?

body: The LEDs are "addressed" in series; if you address the first LED then you address *all* connected first LEDs. So yes, you must connect the Data Out of the previous LED/strip to the Data In of the next in order to address all of them individually.


message:
avrdude flash issues

I want to burn a hex file to a custom ATmega2560 board. I use [this USBasp programmer][1] for flashing (firmware version 1.01) on my Mac OS X 10.12.6 system. All hex files are compiled with avr-gcc (GCC) 4.9.2.

I use this command to burn fuses (without bootloader):

<!-- language-all: lang-none -->

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -U lfuse:w:0xff:m -U hfuse:w:0xd9:m -U efuse:w:0xfd:m -s -F

What is working fine: I can flash smaller (43,266 bytes) programs and they work straight away without bootloader. If I flash **bigger programs (99,986 bytes)** they do not run. I can verify if the program runs because they spit out data via TTL. The smaller program does work but the bigger one does not produce anything.

I turned on "Code verify" and I can see for smaller programs:

    avrdude: 43264 bytes of flash verified

big programs:

    avrdude: verification error, first mismatch at byte 0x0001
             0x90 != 0x94
    avrdude: verification error; content mismatch

**Any hints on this side?**

Secondly: after deleting the whole flash, when I flash a custom bootloader (from Atmel Studio - fuses are Ext. 0xFD, High: 0xD2, Low: 0xFF), command:

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -U flash:w:ATmega_Example.hex:i

and afterwards read the flash, the bootloader ended up in several blocks within the flash.

From the readout hexfile (data blocks):

Line 1

    >:20000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00

All the flash is 0xFF until Line 1921

>:20F0000077C000009BC0000099C0000097C0000095C0000093C0000091C000008FC0000066

Some more data until Line 1995.

>:20F940000895F894FFCF65300000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF31

All the flash is 0xFF until Line 3970.

>:20F0000077C000009BC0000099C0000097C0000095C0000093C0000091C000008FC0000066

Some more data until Line 4044.

>:20F940000895F894FFCF65300000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF31

And so on... I can find similar data 4 times in the file.

**Is this a problem with the flashing or with reading the data from the chip?**

Let me know if you need more information to help me here.

  [1]: https://www.ebay.de/itm/311719627217

body:
Personally I use [AVRDUDESS][1] for uploading sketch on atmega328p and attiny85. Try to use it and run detect.
I answer this because AVRDUDESS is very easy to use and it can help you to show more info of your error.
I think you maybe have a bad wiring or a defect cable.

  [1]: https://github.com/zkemble/AVRDUDESS?files=1


body:
I'm not certain that it's going to fix your problem, but few years ago I had similar issue. I was trying to upload program to ATTiny13A using cheap e-bay USPasp and got verification errors. One step of my solution was changing programmer id from "`-c usbasp`" to "`-c usbasp-clone`"

More here: https://www.nongnu.org/avrdude/user-manual/avrdude_4.html

[![USBasp vs USBasp-clone][1]][1]

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


body:
I am familiar with that issue. I don't have an USBasp but an USBtinyISP but I think the problem is the same.

The USBtinyISP cannot read or write past 64kiB. Since AVR are 8-bit machines with 16-bit addressing they cannot address past 64kiB on their own. A special addressing schema is used on runtime and also during flash. (I think it was larger page sizes during flash.)

I could manage to get around the issue by using an original [Atmel AVRISP mkII][1].

  [1]: https://www.microchip.com/developmenttools/ProductDetails/PartNo/atavrisp2


message:
Moving a character around an LCD screen - is there a better way?

I have some basic programming experience but I am a novice at both C and Arduino.

I messed around with the example LCD code to try to move a character around with the onboard keypad. I also wanted the actual move to occur only once the button is released, like you would expect from a keypad.

The code works, but I have a feeling all the empty WHILE loops inside the main loop() function I used are not the best practice.. :)

How did I do? Is there a more convenient/elegant solution I missed and can learn from?

Thanks, and sorry for the messy code!

    void loop()
    {
      lcd.clear();
      lcd.setCursor(posCol,posRow);      //initialized beforehand
      lcd.print("O");                    //random char to move
      lcdOld = btnNONE;

      while (read_LCD_buttons() == btnNONE)     //do nothing while nothing is pressed
      {
      }

      lcdOld = read_LCD_buttons();

      while (read_LCD_buttons() == lcdOld)     //do nothing while button is down
      {
      }

      switch (lcdOld)               // depending on which button was pushed, we perform an action
       {
       case btnRIGHT:
         {
         posCol++;
         break;
         }
       case btnLEFT:
         {
         posCol--;
         break;
         }
       case btnUP:
         {
         if (posRow == 1)
         {
            posRow = 0;
            break;
         }
         else
         {
         break;
         }
         }
       case btnDOWN:
         {
         if (posRow == 0)
         {
            posRow = 1;
            break;
         }
         else
         {
         break;
         }
         }
       case btnSELECT:
         {
         break;
         }
         case btnNONE:
         {
         break;
         }
     }
    }

body:
You could encapsulate the logic of detecting a button release into its
own function:

<!-- language: lang-c++ -->

    // Return the button that was just released, or btnNONE.
    int releasedButton()
    {
        static int last_button = btnNONE;
        int previous_button = last_button;
        last_button = read_LCD_buttons();
        if (last_button == btnNONE)
            return previous_button;
        else
            return btnNONE;
    }

Then the logic in the loo gets simplified:

    void loop()
    {
        switch (releasedButton()) {
            ...
        }
    }


message:
Connecting multiple component's VCC wires to one Arduino UNO R3 5V Pin

Apologies for the title gore and whether this seems to be a fairly basic question, I'm an Arduino noob.

I'm working on a wearable sensor system project at my university using an Arduino UNO R3 to handle all the sensors and power them. I'm currently powering the board with a USB connection and will be powering my components from the board's 5V pin as they can all safely operate with that voltage. The individual components do not exceed their I/O pins max current and their combined current usage doesn't exceed the boards maximum current.

My question comes in here: in the past if I've needed to connect multiple components to the ground and 5V pins of an Arduino board, I was always taught to use a matrix board to solder my component's 5V and GND wires to, where they could then be powered from two soldered wires from the microcontrollers 5V and GND pins.

Given that this is a wearable system, I would like to minimise any unnecessary hardware and so proposed to my supervisor that we cut out the matrix board and simply solder the VCC wires of the components together to one header pin which we can then plug into the 5V pin on the board to draw power. He strongly cautioned against this but wasn't able to provide a concrete reason as to why it would be a problem; as far as I can see the fundamental theory is the same and we are simply cutting out an unnecessary middle man.

Is there something I'm missing here or does this solution seem like it would work fine? Additionally, if this solution works for VCC, would the same principle work for sharing a grounded connection?

body:
Assuming you have suitable soldering skill, there are some considerations when you solder lots of wires to one header:

 - Lots of wires means lots of weight. The strain of several wires may degrade your connection or header over time, especially for a wearable system, where I assume the parts would be subject to some movement.
 - The width of the connection when all the wires are soldered to it. It might touch adjacent pins, or lean on them, creating mechanical stress. Heatshrink or sleeving can help with the electrical contact issue, but won't remove the mechanical risk.
 - Lots of wires soldered to one point may make the system more difficult to service. Instead of desoldering the wire to one component, you have to either desolder them all, or cut the wire to the one suspect component and then solder together wire stubs later to replace it.

When referring specifically to power supply pins, you'll need to consider the peak current requirements of anything you power from it. Based on https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations it seems like you shouldn't be pulling more than 200mA from the Vcc PIN. Check the *maximum* current draw of all of your components that you want to power, add them together, and make sure it's under the limit of the Arduino board.


message:
How to connect RFID Module to Arduino UNO

I brought 860mhz-960mhz UHF rfid reader module for chip card skimmer from follow link:

https://www.alibaba.com/product-detail/860mhz-960mhz-UHF-rfid-reader-module_60312310172.html

I want to do communication with arduino uno so is it possible to connect
[![enter image description here][1]][1]

VCC to VCC
GND to GND
RX to TX
TX to RX

and what is meaning of EN and GPIO if any one know please help me to do serial communication.

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

body: Its just a simple RFID module based on UART working on 5V.  EN stands for enable, to enable the chip. It has to be connected to VCC too. Because its active high signal. GPIOs are general purpose io pins. No need of them if you are just reading from RFID.


message:
Arduino Uno Keeps Resetting (Power issue)

Arduinites!

Hoping you can help a newbie. I'm putting together a board for a Christmas present this year. It's replacing the factory board that comes on a beer fridge/vending machine, with minimal interactions.

Basically, when the beer can falls into an outlet chute, it trips a switch that triggers some LEDs and audio. Pretty simple stuff. The fridge supplied +5v to the previous board, so I thought I could remove it and simply swap in the Arduino.

The code runs fine when the Arduino is powered by USB/laptop. I spliced a USB header onto the +5v wire supplied by the fridge and plugged it all in. Now, it will boot up, play some weird fuzz out of the speaker, and reset after about 10 seconds.

How can I use the +5v to power my nutty creation? The previous board had a capacitor on it which I removed (I know next to nothing about some of this stuff but it seems like maybe that would help?)

Here's a photo of what I'm working with. If I need to provide any additional information or photos I can do that.

[![My board][1]][1]

[![Fridge Schematic][2]][2]

[![Power][3]][3]

[![enter image description here][4]][4]
If you have any advice, please ELI5 with regards to what I might be able to place in my circuit to get this working (links or definitions are incredibly helpful!)

Any help is appreciated!

  [1]: https://i.stack.imgur.com/WxWCb.jpg
  [2]: https://i.stack.imgur.com/hJTqZ.jpg
  [3]: https://i.stack.imgur.com/b6EnD.jpg
  [4]: https://i.stack.imgur.com/i3D2D.jpg

body:
How much current takes your board with all components? Maybe the 5V power supply can not give you the wanted current.

- You can use a oscilloscope to see what is happening with the 5V when you use your board (maybe not enough current) for example interruptions on your connection or the voltage is not stable.
- Maybe you can find a datasheed for the power supply for more information
- try your board with another power supply to see if this is a problem of the board or the power supply

I just recognized in the third picture that the transformers output have 5V and 200mA. Your speaker will maybe have 8 Ohm (please write us the resistance). This means it will take 5V/8 Ohm this equals a current of 0,625 or 625mA. This current is 3 times higher than the output current of the transformer.

My theory 1 is:

Your circuit worked on your computers USB because you have got usb 3.0 and the max current for it is 900mA wich is much greater than 625mA and enough for leds, speaker and arduino. Your speaker is not connected directly to a pin and gnd. Some seperate electronics manages the pulses and takes directly the 5V of the USB.

My theory 2 is:
You used USB 2.0 (500mA) or USB 3.0 (900mA) and the speaker is connected directly to a pin (the resistance is ok or you added some resistance). The sound was probably not loud because the power was low. The current for both USBs were enough for leds, speaker and arduino.

Now to your problem with the resetting.

The solution:

Switch off the speaker and test your circuit without it. (I think it will work fine).

If it works: You took too much current and this current heated the pin and  influenced the charecteristics of the pin and finally the voltage at your pin (weird fuzz). Add a variable resistor in series to your speaker an try it.

If it not works: Measure the output voltage of the transformer and wirte us the value.


message:
understanding timer overflow detection code

I am trying to understand in details the (great tutorial and) code of Nick Gammon **''Improved sketch using Timer 1''**, available here: http://www.gammon.com.au/forum/?id=12075 . I post the whole code at the end of this in the case the web page would go down.

I find the code quite clear: Nick wants to estimate the value of a capacitor by measuring its characteristic discharge time. For this he uses one of the Arduino timers, together with an interrupt raised by the analog comparator. As the Arduino timer he uses is only 16 bits and he uses a pre-factor of 1 at 16MHz, he expects overflow of the timer to occur so he keeps track of the number of overflows that happened:

    ISR (TIMER1_OVF_vect)
    {
      ++overflowCount;               // count number of Counter1 overflows
    }  // end of TIMER1_OVF_vect

However, what I do not understand is why he tries to find a 'missed overflow' in the ISR raised by the analog comparator (this is in the ```ISR (ANALOG_COMP_vect)``` function body):

    // if just missed an overflow
        if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
          overflowCopy++;

So my questions are:

- How could a missed overflow happen? 'Naively' I would guess that, as soon as the analog comparator ISR is called, the timer stops incrementing so that it should not overflow after the comparator ISR fires, am I wrong?

- If there is a timer overflow happening, I understand why one wants to check TIFR1 at TOV1 (this is the overflow flag, set automatically at timer overflow, which should be cleared as a side-effect of execution of ```ISR(TIMER1_0VF_vect)``` according to datasheet), why add also the ```&& timer1CounterValue < 256``` in the if condition? I understand that ```256``` is a 'small' value, any reason for this exact numerical value?

# Copy of the whole code:

    /*
    Capacitance meter

    Author: Nick Gammon
    Date:   27 June 2013

    Pulse pin (D2): Connect to capacitor via 10K resistor.

    Reference voltage of 0.632 of output pin (pulsePin) connected to D7.
    In my case I used 3.06V because I measured 4.84 on the 5V pin.

    Measure pin (D6) connected to first leg of capacitor, other leg connected to Gnd.

    Like this:

    Capacitor to test:

    D2  ----> 10K ----> D6 ----> capacitor_under_test ----> Gnd

    Reference voltage:

    +5V ----> 1.8K ---> D7 ---> 3.1K ----> Gnd

    */

    const byte pulsePin = 2;
    const float resistance = 10000.0;

    volatile boolean triggered;
    volatile boolean active;

    volatile unsigned long timerCounts;
    volatile unsigned long overflowCount;

    ISR (TIMER1_OVF_vect)
    {
      ++overflowCount;               // count number of Counter1 overflows
    }  // end of TIMER1_OVF_vect

    ISR (ANALOG_COMP_vect)
      {
      // grab counter value before it changes any more
      unsigned int timer1CounterValue;
      timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
      unsigned long overflowCopy = overflowCount;

      if (active)
        {
        // if just missed an overflow
        if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
          overflowCopy++;
        // calculate total count
        timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
        triggered = true;
        digitalWrite (pulsePin, LOW);  // start discharging capacitor
        }
      }  // end of ANALOG_COMP_vect

    void setup ()
      {
      pinMode (pulsePin, OUTPUT);
      digitalWrite (pulsePin, LOW);

      Serial.begin (115200);
      Serial.println ("Started.");
      ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
      ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
            | bit (ACIE)    // Analog Comparator Interrupt Enable
            | bit (ACIS0) | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on rising edge)
       }  // end of setup

    void startTiming ()
      {
      active = true;
      triggered = false;

      // prepare timer
      overflowCount = 0;            // no overflows yet
      // reset Timer 1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;      // Counter to zero
      TIFR1 = bit (TOV1);  // clear overflow bit
      // Timer 1 - counts clock pulses
      TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

      // get on with it
      digitalWrite (pulsePin, HIGH);  // start charging capacitor
      // start Timer 1, no prescaler
      TCCR1B =  bit (CS10);

      } // end of startTiming

    void finishTiming ()
      {
      active = false;
      Serial.print ("Capacitance = ");
      float capacitance = (float) timerCounts * 1000.0 / 16.0 / resistance;
      Serial.print (capacitance);
      Serial.println (" nF");
      triggered = false;
      delay (3000);
      }  // end of finishTiming

    void loop ()
      {
      // start another test?
      if (!active)
        startTiming ();

      // if the ISR noted the time interval is up, display results
      if (active && triggered)
        finishTiming ();

      }  // end of loop

body:
>  'Naively' I would guess that, as soon as the analog comparator ISR is
>  called, the timer stops incrementing

It doesn't. The timer stops only when you ask it to stop.

Now, consider this scenario:

* `overflowCount` = 0, `TCNT1` = 0xfffc
* the `ANALOG_COMP` interrupt fires, which automatically disables
  servicing nested interrupts
* while `ISR(ANALOG_COMP_vect)` is executing its prologue (saving the
  execution context), Timer 1 overflows, which sets the `TOV1` flag, but
  the corresponding interrupt is for now pending
* when `timer1CounterValue = TCNT1;` gets executed, `TCNT1` is now
  0x0008.

At this point, we have `overflowCount` = 0 and `timer1CounterValue` =
0x0008. If we have no provision for detecting the overflow, we will
grossly underestimate the time. This can be fixed by accounting for the
missed overflow as

<!-- language: lang-c++ -->

    // if just missed an overflow
    if (TIFR1 & bit(TOV1))
        overflowCopy++;

The is still an issue however. Think of what would happen if the timer
overflows after executing `timer1CounterValue = TCNT1;` but before
reading the `TOV1` flag. Then we would unduly increment `overflowCopy`.
This is why the code tests for
`(TIFR1 & bit(TOV1)) && timer1CounterValue < 256`. There is no reason
for choosing this particular small value, other than the test being
easier to perform in assembly. The compiler is probably smart enough to
notice it doesn't need to do a subtraction for this particular value.


message:
5v input on ATmega328p running on 3.3v

The ATmega328p can run on 5v but will it cause problems if it runs on 3.3 v and one input signal is 5v?

body: The voltage at any input *must* be less than VCC+0.3V unless it is restricted to only a few milliamperes (so it doesn't burn out the clamping diode). Use a proper voltage translator if it is available, otherwise use a 1kohm or greater resistor (at the cost of life expectancy for the MCU).


body:
Logic levels can be different across differently made integrated circuits and processors.  You should not directly connect differently powered devices together.  Logic level differences (as described [here][1]) should be dealt with using logic level converting devices such as [this one][2].

  [1]: https://learn.sparkfun.com/tutorials/logic-levels
  [2]: https://www.sparkfun.com/products/12009


message:
Connect a sensor to Arduino without knowing much info about the sensor

I am planning to buy a [formaldehyde sensor][1] and I would like to connect it to an **Arduino Uno** board (and later to a Raspberry). As far as I know, the sensor comes in a small box/bag without any other external components (e.g. amplifiers etc.). So I will end up having in my hand a sensor with two copper terminals for connection (see image below):

[![enter image description here][2]][2]

Is it possible to connect this to an Arduino board without having a connection scheme? If yes, where do I connect the two terminals of this sensor to the 5V, GND and the A## ports? Also, how to translate the voltage coming from the sensor to ppm (parts per million) only by having general specifications from the [manufacturer][3] and not some kind of table of conversion? Also, would I need an external component for this? If yes, which component?

I know that this question sounds very stupid, but so far I've used sensors that come with a code on [Seeed Grove][4] with a clear description and I assumed that the code is there because there is a link between the producer of a certain sensor and Groove. Thank you!

FYI: The producer writes some things about the sensor but that doesn't help me a lot:

> This sensor is of the two-electrode electrochemical type, operating by the
diffusion principle and as such requires no external sampling hardware. In
the presence of formaldehyde gas a small direct current is produced; the
sensor requires no power supply of its own but this current requires
amplification to make it readable using external data collection
equipment.

  [1]: https://www.dart-sensors.com/product/economy-formaldehyde-sensor/
  [2]: https://i.stack.imgur.com/DZBwe.png
  [3]: https://dart-sensors.com/wp/wp-content/uploads/2014/10/HCHOSensorDatasheet.pdf
  [4]: http://wiki.seeed.cc/Grove-HCHO_Sensor/

body:
You have linked to the [datasheet][1] of the sensor.

In the datasheet, look at the "Application Circuit" section. You must build this circuit. The sensor produces a very small electric current, and the application circuit is high-gain amplifier to translate that very small electric current to a varying voltage you can sample with the Arduino ADC.

Note on the circuit, the wire labled "To ADC" -- that is the part which you connect to your arduino.

As for calibration, the datasheet itself notes that the process is non-trivial, or that they can perform a calibration, for an additional fee, at the time you order a batch of sensors. Presumably their calibration will include the precise resistor values used to set the gain of the amplifier, and also an equation to associate PPM values to the analog voltage provided at the "To ADC" wire.

As for reading the circuit diagram (schematic), you may already know resistors and capacitors. For the other items, search online for the part numbers given, to find out what they are.

The datasheet also notes that the application circuit is available pre-built from the sensor manufacturer. You may want to contact them to determine how to purchase one for yourself.

Most electronics products have a datasheet that explains all you typically need to know about the device, such as it's operating parameter minima and maxima, typical values, typical outputs, etc. This sensor is no different, except that the calibration procedure is not described in great detail due to the complexity.

  [1]: https://dart-sensors.com/wp/wp-content/uploads/2014/10/HCHOSensorDatasheet.pdf