message:
DHT22 and DS18B20 together

I am trying to get DHT22 and DS18B20 to work together. The code below is the one I am using:

    #include <SD.h>
    #include "SPI.h"
    #include "DHT.h"
    #include <RTClibExtended.h>
    #include <Wire.h>
    #include <LowPower.h>
    #include <stdlib.h>
    #include <avr/interrupt.h> // library for interrupts handling
    #include <avr/sleep.h> // library for sleep
    #include <avr/power.h> // library for power control
    #include <OneWire.h>
    #include <DallasTemperature.h>

    #define DHTPIN 7 // what pin we're connected to
    #define DHTTYPE DHT22 // DHT 22  (AM2302)
    #define wakePin 2 //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    #define ONE_WIRE_BUS 4  //DS18B20 is plugged into pin 4

    RTC_DS3231 rtc;
    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    const int chipSelect = 10;
    int interval_sec=0; //An alarm interval in seconds
    int interval_min=5; //An alarm interval in minutes
    int interval_hr=0; //An alarm interval in hours
    char file_name[25]="Readings.csv"; //
    DHT dht(DHTPIN, DHTTYPE);
    OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature.

    void setup () {
      Serial.begin(9600);
      delay(3000); // wait for console opening
      /**RTC**/
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

      /**INTERRUPT**/
      //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
      pinMode(wakePin, INPUT_PULLUP);
      Wire.begin();
      //clear any pending alarms
      rtc.armAlarm(1, false);
      rtc.clearAlarm(1);
      rtc.alarmInterrupt(1, false);
      rtc.armAlarm(2, false);
      rtc.clearAlarm(2);
      rtc.alarmInterrupt(2, false);
      //Set SQW pin to OFF (in my case it was set by default to 1Hz)
      //The output of the DS3231 INT pin is connected to this pin
      //It must be connected to arduino D2 pin for wake-up
      rtc.writeSqwPinMode(DS3231_OFF);
      //Initialize DS18B20 libraries
      sensors.begin();
      /**SD CARD**/
      Serial.print("Initializing SD card...");
      // make sure that the default chip select pin is set to
      // output, even if you don't use it:
      pinMode(10, OUTPUT);
      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        // don't do anything more:
        return;
      }
      Serial.println("card initialized.");
      //Remove File from SD card and create a new one
      SD.remove(file_name);
      File dataFile = SD.open(file_name, FILE_WRITE);
      dataFile.println("Date,Hour,Minute,Air_Temp,Humidity,Surface_Temp");  //Write the header
      dataFile.close();
       Serial.println("Initialisation complete.");
      delay(100); //Allow for serial print to complete.
    }

    void loop () {
      DateTime now = rtc.now();
      Serial.print(now.year(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.day(), DEC);
      Serial.print(" (");
      Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
      Serial.print(") ");
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();
      /**Temperature and Humidity**/
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit
      //float f = dht.readTemperature(true);
      // Check if any reads failed and exit early (to try again).
      //if (isnan(h) || isnan(t) || isnan(f)) {
        if (isnan(h) || isnan(t)) {
          Serial.println("Failed to read from DHT sensor!");
          return;
        }
        // Compute heat index
        // Must send in temp in Fahrenheit!
        //float hi = dht.computeHeatIndex(f, h);
        Serial.print("Humidity: ");
        Serial.print(h);
        Serial.print(" %\t");
        Serial.print("Temperature: ");
        Serial.print(t);
        Serial.println(" *C\t");
        delay(3000); // wait for console
        /**DS18B20**/
        // call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus
        sensors.requestTemperatures(); // Send the command to get temperatures
        float surface_temp=sensors.getTempCByIndex(0);
        Serial.print("Temperature for the device 1 (index 0) is: ");
        Serial.println(surface_temp);
        delay(3000); // wait for console

        /**Store on SD**/
        // open the file. note that only one file can be open at a time,
        // so you have to close this one before opening another.
        File dataFile = SD.open(file_name, FILE_WRITE);
        String dataString = now.day() + String("/") + now.month() + String("/") + now.year() + String(",") + now.hour() + String(",") + now.minute() + String(",") + t + String(",") + h + String(",") + surface_temp;
        //String dataString = now.day() + String("/") + now.month() + String("/") + now.year() + String(",") + now.hour() + String(",") + now.minute() + String(",") + t + String(",") + h + String(",") + String("surface_temp");
        //Serial.println(dataString);
        // if the file is available, write to it:
        if (dataFile) {
          dataFile.println(dataString);
          dataFile.close();
          // print to the serial port too:
          //Serial.println(dataString);
        }
        // if the file isn't open, pop up an error:
        else {
          Serial.println("error opening file to log data");
        }
        /**INTERRUPT Based sleep**/
        DateTime nextAlarm = now + TimeSpan(0, interval_hr, interval_min, interval_sec);
        //Format is TimeSpan(day,hour,min,sec). Either use interval_min or interval_sec
        Serial.print("Alarm at:");
        Serial.println(nextAlarm.hour());
        Serial.println(nextAlarm.minute());
        Serial.println(nextAlarm.second());
        rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour (), 1); //set wake-up time here
        rtc.alarmInterrupt(1, true);
        delay(3000); // wait for console
        attachInterrupt(0, wakeUp, LOW); //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
        LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
        //Arduino enters sleep mode here
        detachInterrupt(0);
        //execution resumes from here after wake-up
        //When exiting the sleep mode we clear the alarm
        rtc.armAlarm(1, false);
        rtc.clearAlarm(1);
        rtc.alarmInterrupt(1, false);
        Serial.println();
        delay(3000);
    }

    void wakeUp() {
      // here the interrupt is handled after wakeup
    }

The above code ideally should read and store the temperature from DS18B20, and temperature and humidity from DHT22 and then go to sleep for a pre-determined time (5mins now) and then wake up when an interrupt is generated from the RTC.

However, I am unable to get both DHT22 and DS18B20 to work together. The code above works as expected if I comment out the code for DS18B20. Similarly, if I just run the examples (named Single and Simple) for DS18B20 as provided by DallasTemperature on the same Arduino keeping all the connections intact (DHT, RTC, SD Card, along with DS18B20) the DS18B20 also work as expected. Hence, I think I can be certain that the connections are proper. However, if I run the code above which include both DHT22 and DS18B20, then the output I get is as follows:

    Initializing SD card...card initialized.
    Initialisation complete.
    201Initializing SD card...card initialized.
    Initialisation complete.
    2⸮

I would appreciate if someone can point me to where I am going wrong.

P.S.: I have also successfully tried a simple program like the one below to ensure that there are no conflicts in libraries of DHT22 and DS18B20.

    #include <DallasTemperature.h>
    #include <OneWire.h>
    #include <DHT.h>

    #define ONE_WIRE_BUS 4
    #define DHTPIN 7     // what pin we're connected to
    #define DHTTYPE DHT22   // DHT 22  (AM2302)

    DHT dht(DHTPIN, DHTTYPE);
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    void setup(void) {
      Serial.begin(9600);
      Serial.println("Dallas Temperature IC Control Library Demo");
      sensors.begin();
    }

    void loop(void) {
      sensors.requestTemperatures();
      Serial.print("Temperature1: ");
      Serial.print(dht.readTemperature());
      Serial.print(" Temperature 2 : ");
      Serial.println(sensors.getTempCByIndex(0));
    }

body:
My first thought was that sram is being overwritten. That seems to be the case, as you have confirmed.

The SD library uses a lot of sram memory, because it has to handle a table of the FAT data structure from the SD memory card.

You don't use the 'PSTR()' or the 'F()' macro and not the [`PROGMEM`][1].
For example this code:
`Serial.println("Dallas Temperature IC Control Library Demo");`
creates that text in Flash memory and during startup that text is also copied to sram memory. You can avoid that by forcing that text to stay in flash memory only with the 'F()' macro:
`Serial.println(F("Dallas Temperature IC Control Library Demo"));`

Perhaps you have already seen sketches that use the 'F()' macro a lot.

The names of the days of the week can be placed in Flash code with [PROGMEM][1]. It requires special functions to read data from PROGMEM, since the AVR microcontrollers can not read data from flash directly.

[**ADDED**] The 'F()' macro, the 'PSTR()' and the PROGMEM are explained here: [Nick Gammon about PROGMEM][2]

  [1]: https://www.arduino.cc/en/Reference/PROGMEM
  [2]: http://www.gammon.com.au/progmem


sender: user

message:
PIR with Arduino - detects only first motion

The following is an Arduino sketch for 3 PIR sensors. Two PIRs can activate 1 buzzer and show status in an LCD. The third PIR activates a relay.

The problem is only the first motion gets detected and the "L" indicator stays on. After that there is no activity.

The same Arduino Uno board is working fine with other sketches. PIR sensors are also working. The sketch seems to be working on simulation as well.

[Link to simulation][1]

"L" LED is the LED close to the 13th pin. above the TX,RX LEDs. The PIRs are set for the lowest time, sensitivity medium. The issue exists even without connecting the PIRs/relay. There is one beep from the buzzer, it happens 4-5 seconds after turning the board on, with that the "L" led goes on - forever.

The LCD also has an issue, it shows filled blocks on the first row, nothing else.

I tried connecting only one PIR and 1 buzzer to the board.

What is wrong?

    #include <LiquidCrystal.h>

    unsigned long time;
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
    int pir1Pin =9;
    int pir2Pin =10;
    int pir3Pin =11;
    int buzzerPin =8;
    int relayPin = 12;
    int backlightPin = 13;
    long previousMillis = 0;
    long interval = 1000;

    void setup() {
      lcd.begin(16, 2);
      pinMode(pir1Pin, INPUT);
      pinMode(pir2Pin, INPUT);
      pinMode(pir3Pin, INPUT);
      pinMode(relayPin, OUTPUT);
      pinMode(buzzerPin, OUTPUT);
      pinMode(backlightPin, OUTPUT);
      digitalWrite(relayPin,HIGH);
      delay(1000);
      digitalWrite(relayPin,LOW);
      Serial.begin(9600);
    }

    void loop() {
      if(digitalRead(pir1Pin)== HIGH) {
        digitalWrite(backlightPin,HIGH);
        lcd.setCursor(0, 0);
        lcd.print("Pir 1 Active");
        beep();
      } else {
        lcd.setCursor(0, 0);
        lcd.print("Pir 1 is off");
        digitalWrite(backlightPin,LOW);
      }
       if(digitalRead(pir2Pin)== HIGH) {
         digitalWrite(backlightPin,HIGH);
         lcd.setCursor(0, 1);
         lcd.print("Pir 2 Active ");
         beep();
       } else {
         lcd.setCursor(0, 1);
         lcd.print("Pir 2 is off");
         digitalWrite(backlightPin,LOW);
      }
      if(digitalRead(pir3Pin)== HIGH) {
         while(digitalRead(pir3Pin)==HIGH) {
           digitalWrite(relayPin,HIGH);
         }
       } else {
         digitalWrite(relayPin,LOW);
       }
     }

    void beep() {
      unsigned long currentMillis = millis();
      if(currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;
        for (int i=0; i<500; i++) {
          digitalWrite(buzzerPin, HIGH);
          delayMicroseconds(500);
          digitalWrite(buzzerPin, LOW);
          delayMicroseconds(500);
        }
      }
    }

  [1]: https://circuits.io/circuits/5153140-the-unnamed-circuit

sender: assistant

body:
Make sure that all the PIR sensors and the LCD display are effectively powered.
this might fix your problem.

i'm saying this because the same thing seems to work in the simulation. Powering 3 PIR sensors and a LCD display with a USB is not a good idea.


body:
I don't really know what the problem is with your setup, but here are a few suggestions to try:

1. Several PIR guides ([1](https://learn.sparkfun.com/tutorials/pir-motion-sensor-hookup-guide),[2](http://bildr.org/2011/06/pir_arduino/),[3](https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor),[4](https://www.wired.com/2012/09/using-motion-detectors-with-an-arduino/)) recommend using a pullup resistor on the open-collector signal pin of some models of PIR sensors.  You could also (or instead) say `pinMode(pir1Pin, INPUT_PULLUP);` (and so forth) rather than `pinMode(pir1Pin, INPUT);`.  Note, for each PIR, attach a voltmeter to its output (or, to its input on the Uno).  Trigger the PIR and verify that the signal acts as you expect it to.

2. Use a different pin number than 13 for your `backlightPin`.  The Uno's digital pin 13 corresponds to the on-board LED (presumably the LED your question calls 'L').  If you use separate pins for the backlight and the on-board LED, you can then use the on-board LED as a debugging aid.

3. Your code arrangement `if(digitalRead(pir1Pin)== HIGH){ ... `
`lcd.print(...); ... beep(); }else { ...`
`lcd.print(...); ... }` (and similarly for `pir2Pin`) will print stuff to the LCD on every pass through `loop()`, that is, every few milliseconds.  It might make sense to have variables that record previous readings on those pins, and only update the LCD when a pin reading changes.  (Without other changes, this change would lead to only one beep when the PIR triggers, rather than a train of beeps at one-second intervals.  In this case if you want a train of beeps, you would need a beep-status variable.)


body:
To supplement, use an I2C backpack for the LCD and fmalpartida's newLiquidCrystal library. Set the jumper to autoreset the trigger.

Wire VCC to 5V

Wire S+ (outputs 3V3 when tripped) to D2 (INT0) - or whatever you use...

Wire GND to GND


body:
This is not a complete answer because I couldn't figure out why the beep only happens once. But if I'm not mistaken, if your code would work as you intend the first motion gets detected and the code jumps to beep. There it will be stuck for 500x(500+500) ms. You would never get results for pir2 or pir3 if the setup is in a way that you can't trigger pir2 independently from the others.

Therefore:

Use pulldown resistors as mentioned by others.

Read all the pir states and save them, and afterwards run the LCD code and then the beep code.

Your system will be unresponsive for as long as the beep code runs.


message:
Problem with using pure C code to program default UART (UART0) in Arduino Mega

Can I code default serial port in Arduino Mega (USART0, I assume) in pure C? I mean to set up it and configure directly by ATmega's registers?

I'm asking because I'm trying to do it and I have a problem. Below is code which I use and Arduino doesn't transfer anything...

    #include <avr/io.h>

    #define F_CPU 16000000
    #define BAUD_RATE 9600
    #define MY_UBRR (F_CPU+BAUD_RATE*8UL)/(16UL*BAUD_RATE)-1

    void setup() {

        UART_Init(MY_UBRR);
    }

    void loop() {
        UART_Transmit('a');

     }

    void UART_Init(unsigned char ubrr)
    {
       UBRR0H = (unsigned char)(ubrr >> 8);
       UBRR0L = (unsigned char)ubrr;
       UCSR0B = (1<<RXEN0) | (1<<TXEN0);
       UCSR0C = (1<<USBS0) | (1<<UCSZ00);
    }

     void UART_Transmit(unsigned char data)
     {
        while(!(UCSR0A & (1<<UDRE0)))
        UDR0 = data;
     }

That code I created following the datasheet for ATmega 2560. It has been compiled and programmed but doesn't work at all...

Please give me any advice. It's important for me use just C code in that case.

body:
I suggest to use existing code and copy that or use that.

This is the Arduino HardwareSerial : [HardwareSerial.cpp][1]
You can find more code at [avrfreaks.net][2]. Click on "Projects", search for "uart" and "usart" and try to find code that is compatible with the ATmega2560. Some projects have buffers and many functions, others are very simple.

The result might not be compatible with other Arduino code (for example with interrupts). Why do you not want to use the Arduino Serial library ?

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp
  [2]: https://community.atmel.com/projects


body:
I tried your program on an Uno, and it worked as expected once I fixed
three problems:

* Removed `#define F_CPU 16000000`. This is not a big issue, but it
  fixes a warning about that constant being already defined by the
  Arduino environment.
* Added the `UCSZ01` bit to `UCSR0C` in order to work in 8-bit mode
  instead of the uncommon 6-bit mode.
* Added the semicolon after `while(!(UCSR0A & (1<<UDRE0)))`.

Note also that there is no point in loading `UBRR0` in two steps. You
can just `UBRR0 = ubrr` and trust the compiler to do the right thing.


message:
Arduino open door (outdoor) tonemelody

My problem lies in the fact that I can not stop the "void loop" function and more accurately "StatInDoor". I have to make sure that the "ButtonOpenDoor" works independently of "ButtonCall". If someone presses the "ButtonCall" button then the "ButtonOpenDoor" button must work in progress, and if the "ButtonCall" button is pressed, the "ButtonOpenDoor" button must stop playing the melody.

My idea for this this:

    int StatOutDoor = digitalRead(ButtonCall && ButtonOpenDoor);

or:

    if(StatOutDoor == LOW && StatInDoor = LOW){
       PlayMelody();
    }

But it does not work :(

Full code:

    #include "pitches.h"

    int melody[] = {
      NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
    };
    int noteDurations[] = {
      4, 8, 8, 4, 4, 4, 4, 4
    };
    int ButtonCall = 4;
    int buzzer = 8;
    int ButtonOpenDoor = 7;
    int RelayModule = 12;

    void PlayMelody() {
      for (int thisNote = 0; thisNote < 8; thisNote++) {
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(buzzer, melody[thisNote], noteDuration);
        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);
        noTone(buzzer);
      }
    }

    void setup(){
      pinMode(ButtonCall, INPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(ButtonOpenDoor,INPUT);
      pinMode(RelayModule,OUTPUT);
    }

    void loop() {
      int StatOutDoor = digitalRead(ButtonCall);
      if(StatOutDoor == LOW){
        PlayMelody();
      }
      int StatInDoor = digitalRead(ButtonOpenDoor);
      if (StatInDoor == HIGH) {
        digitalWrite(RelayModule, HIGH);
      } else {
        digitalWrite(RelayModule, LOW);
        delay(3300);
      }
    }

Can someone help with this? (Sorry for my bad English).

body:
I'm not quite sure I understand the logic of what you're asking. Your description is a little vague. Maybe if you provided more information about what the signals are, what they mean, and where they come from, it may help.

However - if you want the melody to play when both inputs are LOW you should change:

    if(StatOutDoor == LOW && StatInDoor = LOW){
          PlayMelody();
    }

to:

    if(StatOutDoor == LOW && StatInDoor == LOW){
          PlayMelody();
    }

Note the use of `==` not `=` to denote equality (`=` is assignment).

Also the use of a 3.3 second delay in your `else` will show everything down to a crawl when `StatInDoor` is `HIGH`.


body:
The Arduino doesn't multitask. So when you execute `PlayMelody()` the `loop()` function can't do anything else until the song ends.

You could use interrupts to play the song, but to keep things simple, here's a way to do it without interrupts.

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

    // Struct to hold the song data (simpler than 2 arrays)
    struct note {
        int pitch;
        int duration;
    };

    // Class to play songs
    class song_player {
    protected:
        note *melody;   // Array of all the notes
        int note_count;  // How many notes in song
        int current_note;
        bool am_playing;  // Playing song?
        unsigned long last_event;  // Time of last note
        unsigned long next_event;  // Time to play next note
        byte speaker_pin;

        // is it time to play the next note?
        bool elapsed()
        {
            unsigned long m = millis();
            if (m >= next_event) {
                last_event = m;
                return true;
            }
            return false;
        }

        // play one note
        void play_next_note() {
            if (elapsed()) {
                // Play next note unless at end of song
                if (current_note < note_count) {
                    unsigned long duration = 1000 / melody[current_note].duration;
                    tone(speaker_pin, melody[current_note].pitch, duration);
                    next_event = millis() +  1.3 * duration;
                    current_note += 1;
                }
                else {
                    // Finished...
                    noTone(speaker_pin);
                    am_playing = false;
                }
            }
        }
    public:
        // ctor
        song_player(byte speaker_pin, note *melody, int note_count) :
            am_playing(false),
            speaker_pin(speaker_pin),
            note_count(note_count),
            melody(melody)
        {
            // Note: does not make local copy, so array should be
            // valid for lifetime of this object
        }

        // Start the song
        void start() {
            // Initialize
            current_note = 0;
            am_playing = true;
            last_event = millis();
        }

        // Call this every loop()
        void loop() {
            if (am_playing) {
                play_next_note();
            }
        }
    };

Then you would change the rest of the program to something like:

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

    // Song data
    note the_song[] = {
      {NOTE_C4, 4},
      {NOTE_G3, 8},
      {NOTE_G3, 8},
      {NOTE_A3, 4},
      {NOTE_G3, 4},
      {0, 4},
      {NOTE_B3, 4},
      {NOTE_C4, 4}
    };
    // Create a player object
    song_player player(9, the_song, sizeof(the_song) / sizeof(the_song[0]));

    //....

    void loop()
    {
        // other stuff .....

        if(StatOutDoor == LOW && StatInDoor == LOW) {
            // Start the song
            player.start();
        }
        // Important: Call this every time
        player.loop();

        // Other stuff here....
    }


message:
Avoid overflowing of counter

I have a global uint32_t that keep tracks of used Bytes:

    uint32_t usedBytes;
    int bytesWritten;

    byteWritten = myFile.print(data, FILE_WRITE);

    if (byteWritten > 0) {
      usedBytes += bytesWritten;
    }

What happen if usedBytes is close to the maximum (0xFFFFFFFF)? Will incrementing it make it 0, or stuck at 0xFFFFFFFF?

body:
It will wrap around though 0.

    0xFFFFFFFF + 1 = 0

You can add a higher order word to track more data:

    if (byteWritten > 0) {
        uint32_t newUsed = usedBytes + byteWritten;
        if (newUsed < usedBytes) {
            fourGigsUsed ++;
        }
        usedBytes = newUsed;
    }

Or you could use `uint64_t` to automate it - however none of the Arduino print routines cope with the `uint64_t` variable type.


message:
Corrupted characters with an OLED displaying thermocouple output

I'm super new to Arduinos but I'm learning as I go. I'm in the first stages of a small temperature control project and so far I've been able to display the output of a MAX31855 thermocouple breakout board on 124x64 spi OLED through my Arduino micro.

My problem is that the characters of the temperature are corrupted looking. As I think I understand it, the temperature is changing while it's being written to the display therefore you get overlapping values. I've attached an image of the display.[![enter image description here][1]][1]

I've tried making the temp output an integer but that didn't work.

Any input would be greatly appreciated as I'm just banging my head against the wall.

Here's my code:

    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_MAX31855.h>
    #include <U8glib.h>

    //Constructor line for OLED

    U8GLIB_SH1106_128X64 u8g(13, 11, 10, 9, 8);  // D0=13, D1=11, CS=10, DC=9, Reset=8

    // Default connection is using software SPI, but comment and uncomment one of
    // the two examples below to switch between software SPI and hardware SPI:

    // Example creating a thermocouple instance with software SPI on any three
    // digital IO pins.
    #define MAXDO   3
    #define MAXCS   4
    #define MAXCLK  5

    // initialize the Thermocouple
    Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);

    // Example creating a thermocouple instance with hardware SPI
    // on a given CS pin.
    //#define MAXCS   10
    //Adafruit_MAX31855 thermocouple(MAXCS);

    void draw() {
      double c = thermocouple.readCelsius();
      u8g.setFont(u8g_font_profont29);  // select font
      u8g.setPrintPos(5, 45);  // set position
      u8g.print(c);  // display temperature from MAX31855

    }

    void setup(void) {

    }

    void loop() {

      // picture loop
      u8g.firstPage();
      do {

        draw();
      } while (u8g.nextPage());

      // rebuild the picture after some delay
      delay(5000);
    }

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

body:
The U8G2 library saves RAM by drawing the screen in smaller chunks (i.e., a "page").  Because you are taking a reading for each chunk, the temperature can change.  Just pull the reading out of `draw` and do it once in `loop`:

    double c; // a global variable used in draw and loop

    void draw() {
      u8g.setFont(u8g_font_profont29);  // select font
      u8g.setPrintPos(5, 45);  // set position
      u8g.print(c);  // display temperature from MAX31855

    }

    void loop() {

      c = thermocouple.readCelsius(); // set the global variable once

      // picture loop
      u8g.firstPage();
      do {
        draw();
      } while (u8g.nextPage());

      // rebuild the picture after some delay
      delay(5000);
    }


message:
Converting array to char

I'm trying to convert a char array to a char. i used this code

    char code[4] = {'1','2','3','4'};

    char strcode[4];

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

    void loop()
    {
        memcpy(strcode, code, 4);
        Serial.println(strcode);
        Serial.println("done");
        delay(1000);
    }

But for some reason when i read my serial monitor i get this:

    1234
    done
Why are there 2 squares behind it?  Am I doing it wrong?

EDIT: For some reason stackexchange doesn't show the 2 squares but there are 2 squares behind 1234

body:
C strings need to be NUL-terminated.

    char strcode[5];

     ...

     ...
         ...
        strcode[4] = '\0';
         ...


message:
Arduino Human Infrared Sensor

I started out again with Arduino (beginner), but I wanted to know if I could connect another human infrared sensor like [this](https://www.banggood.com/180-Degree-Human-Infrared-Sensor-Switch-Light-Sensor-Monitoring-Spotlights-Pir-Switch-p-981659.html?) to the Arduino Uno. I know how to connect a simple pir [like this one](https://www.banggood.com/Wholesale-Mini-IR-Pyroelectric-Infrared-PIR-Motion-Human-Body-Sensor-Detector-Module-New-p-49018.html?), but I dont know for sure how to connect the 12V one (if its possible). Guess the red wire goes to a seperate 12V power supply, brown goes to ground and blue then goes to a digital pin on the arduino arduino? I didnt really understand the description that was available for the 12V sensor, so thats why I am asking (I want to be entirely sure before buying).

Thanks

body: I think it should be compatible with Arduino with a bit of support. Now the first issue is this that we don't really know that what sensor is this detaily. So we can't really find a datasheet that could say it's pinout or its electrical characteristics. Now assuming those pinouts are similar to those of the any sensor that are **VCC Data Out GND** Then you could probably use it but according to that page it says it needs 12V So according to that Data Out also must be fluctuating with voltage near 12V. So the solution would be to use a voltage divider circuit. Now you could find the resistor values from the Google. I think that setup should be ***Okay***  but I can't tell anything up to you provide us with any data sheet.


body:
Blue - Ground, connect to Arduino GND

Brown - Power, connect to external 12V source.

Red - 12 V output. Connect via a diode to arduino input pin. Enable pullup on arduino pin.

This way when the sensor output is low it will pull the arduino pin low. When the output is high the diode blocks the 12V from frying the arduino while the internal pullup ensures the input pin goes to a safe voltage for a high pin.

Don't put the diode the wrong way around or things will go bang.

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


message:
When I see the red RX LED flash I am wondering if it means there is an error?

Each time I press a particular button in my circuit the red RX light flashes briefly.

I have been having trouble with making this button perform the command it should, I and am wondering if the RX flash has something to do with that, or is at least reporting some sort of error?

body:
The TX LED is there to show that some data or signal has been received on your Arduino. When you press the button on your circuit, it briefly sends a signal which then triggers the RX LED on your Arduino. Most often, the RX LED is used to troubleshoot whether you are receiving an input and, in your case, it seems you are.

Therefore, the RX LED is not an error and shouldn't be the source of your problem.


message:
If statement comparing array to value list throws error

In my program I have the following lines of code:

    if (invest == {0, 1, 0, 0})
       {
          //code
       }
However, upon attempting to compile the code, I receive the following error:

    exit status 1
    expected ';' before '}' token
"Invest" is a bool array originally defined with`

    bool invest[] = {0, 0, 0, 0};
How can I prevent this error from ocurring?

body:
You cannot compare like that... you have to do it one by one (and check the length of the array).

    if ((sizeof(invest) / sizeof(bool) == 4) &&
        (invest[0] == 0) &&
        (invest[1] == 1) &&
        (invest[2] == 0) &&
        (invest[3] == 0))
    {
         ...
    }

If you need to do such a compare often (with possibly different values), you of course can always write a dedicated function passing the array, and the array to check against and check the length and use a loop for checking all values.

Note that if invest is a boolean array, it's best to use false and true instead 0 and 1.


body:
Unfortunately you cannot do that.

In addition to Michel Keijzers, another possible way is to use binary manipulation of an integer.

Your declaration of the variable would look like this:

    unsigned int invest = 0x00;    // B0000 or 0 would be acceptable also

(See https://www.arduino.cc/en/Reference/IntegerConstants for notation reference.)
So your `if` statement would be very close to what you had originally wrote.

    if (invest == B0100)
    {
       //code
    }

Using this method you cannot reference each bit in the same way as an array (ie `invest[3]`). Instead to **view** the 4th bit:

    result = (invest && 0x08) >> 3;

To **set** the 4th bit you would need to write:

    invest |= 0x08;    // ie. B1000

And to **clear** the 4th bit:

    invest &= 0x07;    // ie. B0111


body:
You have a syntax error in that code; in C99, you would need to declare the type of the anonymous array `{0, 1, 0, 0}`, for example via  `(bool[]){0, 1, 0, 0}`.  So the following code compiles ok in C:

    int main() {
      char invest[] = {0, 1, 0, 0};
      if (invest == (char[]){0, 1, 0, 0})
        printf("Yes yes yes\n");
      else
        printf("No no no\n");
      return 0;
    }

However, if you compile and run this code, it will output "No no no" rather than "Yes yes yes" because the logical test `invest == (char[]){0, 1, 0, 0}` says to compare the address of the `invest` array to the address of the anonymous array, and of course they differ.

Note, if you try to compile the above as a C++ program, the result will be “error: taking address of temporary array” due to different type checking.

---

All that said, the straightforward way to compare arrays of bytes or in some cases arrays in general is to use the `memcmp()` function.  From its man page:

    SYNOPSIS
       #include <string.h>
       ...
       int memcmp(const void *s1, const void *s2, size_t n);
    DESCRIPTION
       The  memcmp()  function compares the first n bytes (each
       interpreted as unsigned char) of the memory areas s1 and s2.
    RETURN VALUE
       The memcmp() function returns an integer less than, equal to,
       or greater  than zero  if  the  first  n  bytes of s1 is found,
       respectively, to be less than, to match, or be greater than
       the first n bytes of s2.

The following code compiles ok both in C99 and C++ and prints out "Yes yes yes.".

    #include <stdio.h>
    #include <string.h>
    int main() {
      char invest[] = {0, 1, 0, 0};
      char others[] = {0, 1, 0, 0};
      if (memcmp(invest, others, sizeof invest)==0)
        printf("Yes yes yes.\n");
      else
        printf("No no no.\n");
      return 0;
    }

Note, when compiling code like this in the Arduino IDE, you may be able to leave out one or both of the `#include` statements.


message:
basic_insert with WAMP server doesn't connect with MySQL database

I'm trying to establish a connection with a MySQL database on a local server wirelessly using the following script:

The wireless connection with my router is successful but then connection with database results in

I'm using a WeMos D1 mini ESP8266, Windows 10, WAMP64, MySQL 5.7.14.

I get ping responses from MySQL at 127.0.0.1, and my host computer and also the ESP8266.  I've disabled my Windows Firewall to test it temporarily.  After the wifi connects with the ESP8266 and confirms the correct WiFi.localIP, 'Connection failed' error with additional text below.

I can manually enter data into the test_arduino table so I think it's a connection issue with the database server. Maybe something to do with my router's handling of of Port 80.

I am able to send sensor data to remote sites such as ThingSpeak.

Any help would be appreciated.

    // Created by: Dr. Charles A. Bell

    #include "ESP8266WiFi.h"
    #include <MySQL_Connection.h>
    #include <MySQL_Cursor.h>

    IPAddress server_addr(192,168,0,10);  // IP of the MySQL *server* here
    char user[] = "root";              // MySQL user login username
    char password[] = "PASSWORD";        // MySQL user login password

    const char* SSID = "MYSSID";         // Your network SSID
    const char* PASS = "MYPASSWORD";

    // Sample query
    char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

    WiFiClient client;
    MySQL_Connection conn((Client *)&client);

    void setup() {
      Serial.begin(115200);
      while (!Serial); // wait for serial port to connect

      Serial.print("Connecting to "+*SSID);
      WiFi.begin(SSID, PASS);
      Serial.println("going into wl connect");

      while (WiFi.status() != WL_CONNECTED) //not connected,  ...waiting to connect
        {
          delay(1000);
          Serial.print(".");
        }

      Serial.println("wl connected");
      Serial.println("");
      Serial.println("Credentials accepted! Connected to wifi\n ");
      Serial.println(WiFi.localIP());
      Serial.println("");

      if (conn.connect(server_addr, 3306, user, password)) {
        delay(1000);
      }
      else
        Serial.println("Connection failed.");
    }

    void loop() {
      delay(2000);

      Serial.println("Recording data.");

      // Initiate the query class instance
      MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
      // Execute the query
      cur_mem->execute(INSERT_SQL);
      // Note: since there are no results, we do not need to read any data
      // Deleting the cursor also frees up memory used
      delete cur_mem;
    }

The following is the Serial COM4 readout:

    Connected to wifi
     going into wl connect
    .......wl connected

    Credentials accepted! Connected to wifi

    192.168.1.XX (intentionally deleted)

    Connection failed.
    Recording data.

    Exception (3):
    epc1=0x402050ea epc2=0x00000000 epc3=0x00000000 excvaddr=0x402315cc depc=0x00000000

    ctx: cont
    sp: 3ffef5a0 end: 3ffef7d0 offset: 01a0

    >>>stack>>>
    3ffef740:  0a00a8c0 00000001 3ffe8785 402050f4
    3ffef750:  3ffee524 0000000e 3ffe850e 3ffee79c
    3ffef760:  3fffdad0 00000000 3ffee770 402048fd
    3ffef770:  402315cc 00000000 3ffee770 3ffee79c
    3ffef780:  3fffdad0 00000000 3ffee770 40204945
    3ffef790:  402010ae 00000000 3fff061c 4020292e
    3ffef7a0:  3ffe8780 00000000 3fff061c 40201d3e
    3ffef7b0:  3fffdad0 00000000 3ffee794 40204c34
    3ffef7c0:  feefeffe feefeffe 3ffee7b0 40100718
    <<<stack<<<

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

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v09f0c112
    ~ld

body:
I figured it out.  I needed to set up a User (IP  server) in the database.
In phpMyAdmin I created a new user (esp) and set the Host name to the IP address of the ESP8266.  In the sketch I changed the user from "root" to "esp".


message:
2.8 Touchscreen does not work with Proto Screw Shield

I am using the Arduino Mega and the 2.8 touch screen by Adafruit, and I can't get the screen to work on my Proto R3 Screw Shield

Here are the tools I am using:

 - [2.8 inch touch screen][1]
 - [Proto R3 Screw Shield][2]

When I put the touch screen onto the Arduino Mega, no wiring needed, and run the graphic test [provided by the Adafruit_ILI9341][3], everything works perfectly. The touch screen runs the animation, and my serial monitor outputs the information of my touch screen.

However, when I put the touch screen on the screw shield, which I place on the Arduino Mega, **the touch screen stays white**, no matter if I press either reset button, unplug and replug the Arduino, restart the IDE, take off and put everything back on.

I explicitly followed the instructions by Adafruit [here][4] that say how to get the screw shield working.

There is no contact between each soldered pin, and I cut and soldered the ICSP and MEGA jumpers on the bottom of the touch screen accordingly, as shown in the picture on the bottom right:

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

I tried using an SD card as a test to see if the proto R3 screw shield was not working at all, and reading an image off of the SD card. I got **proper, working results**, so everything worked fine with the screw shield then. This means that the screw shield still works with it's 5V pin.

What could be the cause of the touchscreen staying white? Thanks in advance!

  [1]: https://learn.adafruit.com/adafruit-2-8-tft-touch-shield-v2/overview
  [2]: https://learn.adafruit.com/adafruit-proto-screw-shield/intro
  [3]: https://learn.adafruit.com/adafruit-2-8-tft-touch-shield-v2/graphics-test
  [4]: https://learn.adafruit.com/adafruit-proto-screw-shield/solder-it
  [5]: https://i.stack.imgur.com/kejSn.jpg

body:
You are set to use the ICSP header for communication with the screen. That is good, when you are directly connected to a Mega.

However that is bad when you are going via a shield that *doesn't have an ICSP header*.

The ICSP header is the 6-pin (3x2) header in the right of your picture. It has SPI signals that the screen needs. Your screw shield lacks those pins.

You need to pass those signals through. The simplest way would be to add a 3x2 stackable header (or two 3x1 stackable headers) upside down through the correct holes to line up with the ICSP header.


message:
HC-05 Bluetooth Module Blinking Red Light-Arduino Uno

I have looked on google for an answer to my problems to no avail. The you tube video I am following is here: https://www.youtube.com/watch?v=f1v0IMegCvU
So basically on my android, I can't see the HC-05 device show up and the module itself is flashing red unlike the video's flashing blue light. I have connected the circuit exactly like he has in the video with the 2 10K resisters. I am using the same app. What is wrong? Here is my code as I copied from the video.

    void setup()
    {
      pinMode(13, OUTPUT);
      Serial.begin(9600);
      Serial.println("Connection Successful!");
    }
    void loop()
    {
      if(Serial.available()>0){
        int data=Serial.read();
        switch(data){
          case 'a': LEDON();break;
          case 'b': LEDOFF();break;
          default : break;
        }
      }
      delay(50);
    }
    void LEDON(){
      Serial.println("Led On!");
      digitalWrite(13,HIGH);
    }
    void LEDOFF(){
      Serial.println("Led Off!");
      digitalWrite(13,LOW);
    }

I also get the error avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 when connected through usb. I do not get any errors when just flashing the arduino without any wires connected to the arduino. I know that the port is correct. Any ideas would be helpful. Thanks.

body:
There are several issues to consider:
• Program downloading
• HC-05 serial communication
• Bluetooth pairing

For the first issue:  The serial-over-USB connection between the development computer and the Uno ties up the Uno's hardware serial RX and TX pins.  There will be a conflict if the development computer transmits when the HC-05's TX is connected to the Uno's RX.  This can be resolved by disconnecting the HC-05 TX when downloading a program.

For the second issue:  The Uno schematic shows 1KΩ resistors between TX and RX on the ATmega328P and RX and TX on the USB chip (ie on an ATmega16U2, or a CH340, etc).  If the HC-05's TX drive is strong enough, it will overcome the drive from the USB chip and work ok.  Note, I would leave out the voltage divider (on the HC-05 RX line) that the video shows.

For the third issue:  The HC-05 in the [video mentioned in the question](https://www.youtube.com/watch?v=f1v0IMegCvU) has a blue LED that blinks steadily when the HC-05 isn't paired, and blinks at a long interval when it is paired.  Many HC-05's have red LEDs instead of blue; the LED color is not an issue.  Some HC-05's don't blink at all when paired; that's not an issue either.  What is an issue is that (according to description in question) your HC-05 keeps on blinking, so apparently isn't paired up.

Whether the HC-05 pairs with an Android app is more or less independent of whether you have the HC-05 connected to an Arduino; you should be able to pair your phone with the HC-05 when just Vcc and ground are connected to the HC-05.  If you are having trouble with pairing, try another app; try powering the HC-05 down and up; and try a different HC-05.  I mention trying another app because one serial-terminal app I installed on my Android phone needed the app or the HC-05 to be restarted to pair up after loss of pairing, and the serial-terminal app I replaced it with did not need those actions.  Note, pairing takes a few steps on my phone:  in Settings / Wireless, search for Bluetooth devices; select device; enter its passcode; run an app and tell the app which Bluetooth device to use.


body:
Try this code(it's simpler):

    char data ;
    void setup()
    {
        Serial.begin(9600);
        pinMode(13, OUTPUT);
    }
    void loop()
    {
       if(Serial.available() > 0)
       {
          data = Serial.read();
          Serial.print("\n");
          if(data == '1')
          {
             digitalWrite(13, HIGH);
             Serial.print("on");
          }
          else if(data == '0')
          {
            digitalWrite(13, LOW);
            Serial.print("off");
          }
       }
    }
Upload this to your Arduino. Open your phone, go to bluetooth settings and connect to HC05 with password 1234. Download an app from here: https://github.com/Mayoogh/Arduino-Bluetooth-Basic
Now your circuit should work.
Arduino to HC05 connections:
   5V -> 5V
   GND-> GND
   RX -> TX
   TX -> RX
LED connection: connect LED to pin 13 and the GND pin beside it(it's fine if you don't use resistor).


message:
How to control continuous rotation servo via HC-12 rf module

I am working on a project to wirelessly control a continuous rotation servo...something like a wireless vending machine.
The problem I am having is controlling how many revolutions the servo is making. During testing I used a button and had no issues getting the delay to work properly. Now that it's connected to the HC-12 RF module I can't get the delay to control how many rotations the servo makes. The servo I'm using is the FS90R.

    #include <SoftwareSerial.h>
    #include <Servo.h>
    SoftwareSerial mySerial(2, 3); // RX, TX
    Servo badservo;

    int pos = 92;
    unsigned long last = millis();

    void setup() {
      mySerial.begin(9600);
      badservo.attach(9);
      badservo.write(pos);
    }

    void loop() {
      if(mySerial.available() > 1){
        int input = mySerial.parseInt();//read serial input and convert to integer (-32,768 to 32,767)
        int servpos = badservo.read();
        if(millis() - last > 250){
          if(servpos == 92 && input == 1234){
            badservo.write(0);
            delay(470);
            //mySerial.println(8894);
          }
          else{
            badservo.write(pos);
            //mySerial.println(8894);
          }
        }
      mySerial.flush();//clear the serial buffer for unwanted inputs
      last = millis();
      }
      delay(20);//delay little for better serial communication
    }

With the servo that I'm using has a stop position of 92, meaning when I do
servo.write(92);
it will stop the servo. Also, the 470 delay was tested with a button and was a single full rotation.

Now, with the HC-12 module, I can't get the servo to rotate less than 2.5 times.
Anyone have any idea what I'm doing wrong? The goal is to get the servo to rotate only once when the RF module receives the proper signal.

body:
You can't rely on a specific delay being one rotation - especially when you are using SoftwareSerial. SoftwareSerial breaks many things, and anything that uses interrupts (such as the Servo library) gets broken by it. It's a real interrupt hog.

The proper way of doing it is to use a rotary encoder on the servo to report the position (or *change* in position) so that you know where the servo is. That's really the only reliable method of getting the servo to perform precise operations.

By the way:

    mySerial.flush();//clear the serial buffer for unwanted inputs

does absolutely nothing. The operation of `flush()` changed when the Arduino API turned one. It is now supposed to wait until both the TX circular buffer and the UART TX FIFO are empty. It has nothing to do with emptying any inputs.  Instead you want:

    while (mySerial.read() != -1);


message:
Where are RX and TX pins on the GT2560?

I'm adding WiFi (ESP8266) to my GT2560 board. Does anyone know where on the board are the RX and TX pins and the best place to connect to them?

This is all, no more info on the board in the internet and forums: https://www.geeetech.com/Documents/Users Manual of GT2560.pdf

body: The GT2560 uses USB for communications and USB has a combined RX/TX and not individual pins.


body:
> Does anyone know where on the board are the RX and TX pins

The serial Rx and Tx signals from the ATmega2560, go to the nearby FT232RQ USB-to-serial adapter. You can look at the part numbers on the ICs and find those two devices on the PCB.

> no more info on the board in the internet and forums

It's good news that there does seem to be more information available :-) After a few minutes with Google (searching for GT2560 schematics) I found this [download link for the schematics](http://www.geeetech.com/forum/download/file.php?id=532) on this [forum page](https://www.geeetech.com/forum/viewtopic.php?f=13&t=17443).

Although it would be possible to reverse-engineer the PCB (or at least the relevant part of it) the schematics are still helpful, since the white coating makes the actual copper traces harder to follow visually.

The schematic shows that two 1k resistors, R3 and R13, are in series with serial signals:

 - R3 between ATmega Tx -> FT232 Rx
 - R13 between ATmega Rx <- FT232 Tx

You may want to confirm that the linked schematic still applies to your specific PCB (since PCB and schematic versions could have changed). With the power disconnected, you could check with a multimeter that there is continuity between the appropriate ATmega pin and one end of each resistor R3 & R13, and between the other end of each resistor and the appropriate FT232 pin, as shown on the schematic.

I have put a red ring around those 2 resistors on the GT2560 top view below, to help you to find them:

[![GT2560 PCB top view][1]][1]

<sub>[(original image source)](https://www.geeetech.com/forum/download/file.php?id=2438&sid=af93cfea19ecca62c70261bffa0ec77a)</sub>

>  best place to connect to them

If you are going to drive those serial signals from an ESP8266, you must first *disconnect* them from the on-board FT232, to avoid contention and so the ESP8266 *replaces* the FT232. Removing those two resistors would make each resistor's (now vacant) pads leading to the ATmega serial port, an ideal place to connect the ESP8266. (Of course you could attach wires directly to the pins of the ATmega or FT232, but I don't see any advantage to doing that.)

One issue which you need to consider, is the voltage compatibility of the serial port signals. The ATmega2560 uses 5V signal levels, whereas the ESP8266 is a 3.3V device. There have been discussions on various websites ([example](https://ba0sh1.com/blog/2016/08/03/is-esp8266-io-really-5v-tolerant/)) that suggest the ESP8266 is 5V-tolerant on I/O pins. You will need to satisfy yourself whether to use voltage translation, or to rely on information discussed on web pages like that one.

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


message:
How to get ip information of arouter/AP with ESP8266

i, I would like to get ip number, DHCP ip range subnet mask information of an external AP/router autonomusly through the ESP8266 sketch, so the ESP8266 code can determine a suitable static ip range to configure. Any example code or references would be appreciated.

body:
All you can do is get what DHCP gives you.

1. Connect to the AP
2. Use DHCP to get an IP address
3. Store the IP, netmask and gateway in variables
4. Use the netmask to determine the "fixed" bits in the IP address.
5. Replace the "unfixed" bits of the IP with your own chosen IP portion
6. Re-set the IP information with your static information.

What you *cannot* do is determine what the DHCP *range* is. Only the router knows that, and it doesn't broadcast it.

The proper way of handling it, though, is to get the router to provide a fixed DHCP IP address for the MAC address the ESP8266 has. Most routers have this functionality available.


message:
Arduino Leonardo as USB Keyboard with WiFi module

I have two PCs: the first is connected to the Arduino via WiFi, this will instruct the Arduino what keys to send, and the second PC is connected to the Arduino via USB that will act as a USB Keyboard for the PC to receive keystrokes. Is it possible to use Arduino Leonardo as a USB Keyboard connected to a PC with WiFi module connected to another PC? Do I need other components or modules for this to work?

I have searched the possibility of keystrokes and WiFi connection as separate projects but can't seem to find a project that has this scenario.

I also consider using Teensy with WiFi module if it is feasible. If this is not possible, are there any workarounds? Or other devices I can use? Thanks in advance.

EDIT: I am also checking Raspberry Pi Zero as an alternative. Is the project more probable with this or is it better to stick with Arduino?

body:
Its always very unlikely that someone will have done exactly the same project as you, which is why you need to break it down.

1. You want to talk to an Arduino over Wifi.
2. You want he PC to send commands to the Arduino.
3. You want to make the Arduino act as a keyboard.

I know each of those three parts in on this site, so that should help answer a lot of questions on how to do it, but obviously some of the solutions may conflict so you'll have to discard them.

1. You can use an ESP8226 - the Arduino talks to it via serial (software serial).
2. You will need an application (c# will be easiest for Windows) that will send data to the Arduino.  You need to design and implement a protocol, using REST may be a good idea.
3. I've never done it and don't know how, but I think I read there is a HID Library (Human Interface Device aka Keyboard or rat) and that makes thinks easier.

As to what hardware you could use there may well be performance constraints, that affect what hardware you can use.  I suspect the lower spec Arduiano's may introduce a lag that may not be acceptable.  Since you want to do it over Wi-Fi, you might want to have a look at the ESP8226, which can be programmed like an Arduino and has native Wi-Fi.  I'm not sure if you can use it as a HID though.


body:
Further to what @CodeGorilla says:

1. You don't need SoftwareSerial on the Leonardo - the UART pins 0 and 1 are independent of any other hardware and can be used directly without any interference.
2. The Arduino IDE has Keyboard examples for the Leonardo built in and full software support for the USB interface acting as HID is built in to the API. No need for any extra libraries on that front.
3. The ESP8266 has no USB interface. It *may* be able to bit-bang it, but I don't think anyone has written software to do that (it's a horrible thing to do anyway).

So you would use pins 0/1 to talk to an ESP8266 which would be your WiFi interface. The Leonardo can directly talk "keyboard" with the wired PC.

A better choice of host board may be the [Pro Micro 3.3V](https://www.sparkfun.com/products/12587) since it runs at the same voltage as the ESP8266 so you don't have any issues of logic level translation. True, it runs at half the speed of the Leonardo, but you're hardly doing any intensive processing here.


message:
Can I use NodeMCU 12E (ESP8266) as wifi shield for arduino Nano?

Update:
Point 1- I don't want to program ESP, I just want to use it as a wifi shiled. cause I'm not familiar with flashing or writing sketch for ESP, so still feel comfortable with arduino. beside my existing projects need to upgrade to wifi version. Not possible to turn everying into esp instead of arduino.
Point 2- If anyone can provide me a complete working sketch, where arduino sending a value to ESP, ESP receiving it and then sending to some data server (even sparkfun type will do).

I was working on Arduino based project for last couple of months, where I had to read several sesor data (e.g. temp, humidity, light, sound, motion etc) and save these data to a remote mysql server. I was doing well with Arduino Uno and Ethernet shield, where I connect through RJ45 cable to make my Arduino UNO able using internet.
here is the code for that:

    #include <SPI.h>
    #include <Ethernet.h>
    #include <MySQL_Connection.h>
    #include <MySQL_Cursor.h>

    byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    IPAddress server_addr(1.1.10.);  // IP of the MySQL *server* here
    char user[] = "root";              // MySQL user login username
    char password[] = "007";        // MySQL user login password

    // Sample query
    char INSERT_DATA[] = "INSERT INTO database (message, sensor_num, value) VALUES ('%s',%d,%s)";
    char query[128];
    //char temperature[10];

    int potPin = 4;
    float temperature = 0;
    long val=0;

    EthernetClient client;
    MySQL_Connection conn((Client *)&client);

    void setup() {
      Serial.begin(115200);
      while (!Serial); // wait for serial port to connect
      Ethernet.begin(mac_addr);
      Serial.println("Connecting...");
      if (conn.connect(server_addr, 3306, user, password)) {
        delay(200);
        // Initiate the query class instance
        MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
        // Save
        //dtostrf(50.125, 1, 1, temperature);
        sprintf(query, INSERT_DATA, "test sensor", 24, temperature);
        // Execute the query
        cur_mem->execute(query);
        // Note: since there are no results, we do not need to read any data
        // Deleting the cursor also frees up memory used
        delete cur_mem;
        Serial.println("Data recorded.");
      }
      else
        Serial.println("Connection failed.");
      conn.close();
    }

    void loop() {
      val = analogRead(potPin);
        temperature = (val*0.0048828125*1000);
        delay(2000);
    }

Later, I found it's not convenient to use a whole bunch of cable around, so I was thinking to make it wireless. At beginning I was thinking of RF24OL but it also can't connect internet directly. Then I found ESP8266 module which can directly connect to wifi.
Now, I bought some ESP8266 12e (not ESP-01), which got one USB port to connect with computer, which made things way more sipmle comparing previous versions of ESP. I also installed ESP supporting files on my Arduino IDE, tested and it's working fine.
But, the problem is, whenever I upload the code only for ESP(like connectiong to wifi), it compile and upload proerply.

Like this code works:

    void setup() {
      pinMode(BUILTIN_LED, OUTPUT);

    }

    void loop() {
      digitalWrite(BUILTIN_LED, LOW);

      delay(500);
      digitalWrite(BUILTIN_LED,HIGH);
      delay(300);

    }

this also works fine,

    /*
     *  This sketch trys to Connect to the best AP based on a given list
     *
     */

    #include <ESP8266WiFi.h>
    #include <ESP8266WiFiMulti.h>

    ESP8266WiFiMulti wifiMulti;

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

        wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
        wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
        wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

     Serial.println("Connecting Wifi...");
        if(wifiMulti.run() == WL_CONNECTED) {
            Serial.println("");
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());
        }
    }

    void loop() {
        if(wifiMulti.run() != WL_CONNECTED) {
            Serial.println("WiFi not connected!");
            delay(1000);
        }
    }

That means, my Arduino IDE, ESP8266 12e all got no problems. But whenever I add something more, like DHT11 library, it shows error compiling.

this code doesnt compile:

    #define SSID       "Itead_1(Public)"                //type your own SSID name
        #define PASSWORD   "27955416"                                //type your own WIFI password

    #include "uartWIFI.h"
    #include <SoftwareSerial.h>
    WIFI wifi;

    extern int chlID;        //client id(0-4)

    // for yeelink api
    #define APIKEY         "3a362e99d6f1daf974561163a8c99a85" // replace your yeelink api key here

    //replace the device ID and sensor ID for temperature sensor.
    #define DEVICEID0       15483 // replace your device ID
    #define SENSORID0       26660 // replace your sensor ID

    //replace the device ID and sensor ID for humidity sensor.
    #define DEVICEID1       15483 // replace your device ID
    #define SENSORID1       26661 // replace your sensor ID

    char server[] = "api.yeelink.net";   // name address for yeelink API

    unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
    boolean lastConnected = false;                 // state of the connection last time through the main loop
    const unsigned long postingInterval = 5*1000; // delay between 2 datapoints, 5s
    String returnValue = "";
    boolean ResponseBegin = false;

    int DHT11PIN=25;                        //Connect D25 to data pin of DHT11

    int humidity;
    int temperature;

    int post_number;

    void setup()
    {

      wifi.begin();
      bool b = wifi.Initialize(STA, SSID, PASSWORD);
      if(!b)
      {
        DebugSerial.println("Init error");
      }
      delay(8000);  //make sure the module can have enough time to get an IP address
      String ipstring  = wifi.showIP();
      DebugSerial.println(ipstring);                //show the ip address of module

    }
    void loop()
    {
      char message[400];
       // if you're not connected, and ten seconds have passed since
      // your last connection, then connect again and send data:
      if((millis() - lastConnectionTime > postingInterval)) {

      //read dht11
      int chk = dht11_read(DHT11PIN);
      if(chk==0)
      {
            if(post_number==0)
            {
                    sendData(DEVICEID0,SENSORID0,temperature);
                    post_number++;
            }
            else
            {
                    post_number = 0;
                    sendData(DEVICEID1,SENSORID1,humidity);
            }

      }

      }

      // if there's incoming data from the net connection.
      // send it out the serial port.  This is for debugging
      // purposes only:
      if(wifi.ReceiveMessage(message))
      {
          DebugSerial.println(message);
      }

      delay(10);

    }

    // this method makes a HTTP connection to the server:
    void sendData(int device_id,int sensor_id,int thisData) {
      // if there's a successful connection:
      if (wifi.ipConfig(TCP,server, 80)) {
        DebugSerial.println("connecting...");
        // send the HTTP PUT request:
        String cmd;
            cmd = "POST /v1.0/device/";
            cmd += String(device_id);
            cmd += "/sensor/";
            cmd += String(sensor_id);
            cmd += "/datapoints";
            cmd += " HTTP/1.1\r\n";
            cmd += "Host: api.yeelink.net\r\n";
            cmd += "Accept: *";
            cmd += "/";
            cmd += "*\r\n";
            cmd += "U-ApiKey: ";
            cmd += APIKEY;
            cmd += "\r\n";
            cmd += "Content-Length: ";
            int thisLength = 10 + getLength(thisData);
        cmd += String(thisLength);
            cmd += "\r\n";
            cmd += "Content-Type: application/x-www-form-urlencoded\r\n";
            cmd += "Connection: close\r\n";
            cmd += "\r\n";
            cmd += "{"value":";
            cmd += String(thisData);
            cmd += "}\r\n";

            DebugSerial.println(cmd);

        wifi.Send(cmd);
        // note the time that the connection was made:
        lastConnectionTime = millis();
      }
      else {
        // if you couldn't make a connection:
        DebugSerial.println("connection failed");
        DebugSerial.println("disconnecting.");
        wifi.closeMux();
      }
    }

    int getLength(int someValue) {
      // there's at least one byte:
      int digits = 1;
      // continually divide the value by ten,
      // adding one to the digit count for each
      // time you divide, until you're at 0:
      int dividend = someValue /10;
      while (dividend > 0) {
        dividend = dividend /10;
        digits++;
      }
      // return the number of digits:
      return digits;
    }

    int dht11_read(int pin)
    {
            // BUFFER TO RECEIVE
            int bits[5];
            int cnt = 7;
            int idx = 0;

            // EMPTY BUFFER
            for (int i=0; i< 5; i++)
            {bits[i]= 0;}[/i]

    [i]        // REQUEST SAMPLE[/i]
    [i]        pinMode(pin, OUTPUT);[/i]
    [i]        digitalWrite(pin, LOW);[/i]
    [i]        delay(18);[/i]
    [i]        digitalWrite(pin, HIGH);[/i]
    [i]        delayMicroseconds(40);[/i]
    [i]        pinMode(pin, INPUT);[/i]

    [i]        // ACKNOWLEDGE or TIMEOUT[/i]
    [i]        unsigned int loopCnt = 10000;[/i]
    [i]        while(digitalRead(pin) == LOW)[/i]
    [i]                if (loopCnt-- == 0) return -2;[/i]

    [i]        loopCnt = 10000;[/i]
    [i]        while(digitalRead(pin) == HIGH)[/i]
    [i]                if (loopCnt-- == 0) return -2;[/i]

    [i]        // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT[/i]
    [i]        for (int i=0; i<40; i++)[/i]
    [i]        {[/i]
    [i]                loopCnt = 10000;[/i]
    [i]                while(digitalRead(pin) == LOW)[/i]
    [i]                        if (loopCnt-- == 0) return -2;[/i]

    [i]                unsigned long t = micros();[/i]

    [i]                loopCnt = 10000;[/i]
    [i]                while(digitalRead(pin) == HIGH)[/i]
    [i]                        if (loopCnt-- == 0) return -2;[/i]

    [i]                if ((micros() - t) > 40) bits[idx] |= (1 << cnt);[/i]
    [i]                if (cnt == 0)   // next byte?[/i]
    [i]                {[/i]
    [i]                        cnt = 7;    // restart at MSB[/i]
    [i]                        idx++;      // next byte![/i]
    [i]                }[/i]
    [i]                else cnt--;[/i]
    [i]        }[/i]

    [i]        // WRITE TO RIGHT VARS[/i]
    [i]        // as bits[1] and bits[3] are allways zero they are omitted in formulas.[/i]
    [i]        humidity    = bits[0]; [/i]
    [i]        temperature = bits[2]; [/i]

    [i]        int sum = bits[0] + bits[2];  [/i]

    [i]        if (bits[4] != sum) return -1;[/i]
    [i]        return 0;[/i]

So, I decided to use ESP and arduino nano together. so that, ESP will work as wifi shiled to connect to internet, like ethernet shield was doing before, arduino will handle parts of sensors data reading and so on. I tried to connect to internet through connecting RX-TX and TX-RX between Arduino-ESP, but it doesn't work. I uploaded wifi connecting script to ESP and it connects to wifi properly, then i uploaded sensor data reading and saving to mysql script to arduino, then conneted arduino tx & rx to esp rx & tx. but arduino can't connect to internet.
Now, my problem is, how I can use ESP8266 12e NodeMCU only as ethernet shield so that my arduino can connect to internet and upload data to my sql server? My ESP will only act as a wifi shield, i don't want to configure esp to read sensor data, cuase it got lack of GPIO pins, most importantly it doesn't work as smoothly as arduino does. So please don't suggest me to use only esp with sensors, because i also wanted to upgrade my existing projects to wifi which done with ethernet shields.
Thanks in advance

body:
OK you have made it very clear that, you want to use the ESP as a serial to WIFI bridge.  You have a Node-MCU ESP12 board, which is normally configured for programming using Luna.

 1. You need to have the correct firmware for this "AI Thinker AT Firmware" and you need to find the correct tool chain for loading this on your board.  It would be easier to but an ESP7 (or lower) to be honest that already comes with the correct firmware.

 2. You want to communicate with the ESP from the Nano.  To do this you will need to use Software Serial on the Nano and cross connect the software serial port to the ESPs serial port.  You must not connect to the nano's serial port, you need this to program the nano.

 3. To configure the ESP to talk to a wireless network you will need to send it AT commands (from the nano) these will need to be part of the setup of you program.  Technically this is programming the ESP, but I'm guessing you'll be OK with this.

 4. Now you can add in your DHT-11 sensor and library and it will work.

**However**

You would find it so much easier to download the board support package for the ESP, take one of the Web server/client examples and add the DHT-11 code to that.  You'll find, since it is all written in the same dialect of C++ as the Arduino uses, very easy.  In fact the biggest problem you will have is finding something to weight the USB cable down to stop it from rolling the Node-MCU over.

BTW your code doesn't compile because you have left the italic mark-up tags in when you copied it off the website.  Try removing all the [i] and [/i] tags.


message:
Arduino serial plotter with independent Y axis, is it possible?

The Arduino IDE has a built in functionality that allows the user to plot a value (such as temperature) over time.

I would like to plot two variables with different ranges on the y-axis (pressure in the range of thousands and temperature which varies from 20°C to 40°C).

I could make it work to have both being plotted, but the range differences does not allow me to see small changes in one/both quantities. Is there a way to two, or more, Y axis each one with its own scale?

body:
No. The Arduino Serial Plotter only supports one Y axis.

An alternative would be to capture the data into a file as CSV data and use some other software to plot it - you could import the data into Excel / LibreOffice, or (as I prefer for quick graphing) use something like GnuPlot (or whatever is similar for your chosen OS).

For instance, this is a GnuPlot configuration for plotting two independent axis datasets and the results:

    set datafile separator ","
    set terminal png enhanced size 1360,768
    set output 'testCharge.png'
    set ytics nomirror
    set ylabel "Current (A)"
    set y2label "Voltage (V)"
    set y2tics nomirror
    plot "testCharge.csv" using 3 smooth bezier title "Current" w l, \
         "testCharge.csv" using 4 title "Cutoff" w l dashtype 2, \
         "testCharge.csv" using 2 smooth bezier title "Voltage" w l axes x1y2

The data I use is formatted thus:

    Phase,Voltage,Current,Cutoff
    0,3.58,1.098,0.033
    0,3.59,1.098,0.033
    0,3.59,1.098,0.033
    0,3.59,1.098,0.033
    0,3.6,1.098,0.033
    0,3.6,1.098,0.033
    0,3.6,1.098,0.033
    0,3.61,1.098,0.033
    0,3.61,1.098,0.033
    ... etc ...

And the results:[![enter image description here][1]][1]

Incidentally, that's me charging a Li-Ion battery and monitoring the voltage and current.

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


body:
The Serial Plotter from within the Arduino IDE is quite limited. Not to mention the lack of documentation on the Arduino website. So, no the Serial Plotter cannot do what you require.

However, there is a very good selection of serial data plotter programs over at this question: [Serial data plotting programs][1]

 [1]: https://arduino.stackexchange.com/q/1180/19409


message:
cannot get low power with Adafruit Trinket

I want to get as low power use during sleep as possible with an Adafruit Trinket. Based on results presented on various places in the internet (blogs etc), I expect to be able to go down to 50 - 100 micro amps on the ATTiny85 of the Trinket. I am aware of the fact that using a board such as Trinket may add a bit of consumption, and I physically removed the power LED and the power regulator. I am feeding 5V directly on the 5V pin.

I am using the simplest sketch I can think about for low power, with nothing connected to any pin:

    #include <avr/sleep.h>          // library for sleep

    #define adc_disable() (ADCSRA &= ~(1<<ADEN)) // disable ADC (before power-off)

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

      // power_all_disable();
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      adc_disable();
      sleep_enable();
      sleep_mode();

    }

    void loop() {

    }

But I cannot get less than around 1.3 milli amps consumption during sleep. Do you know what may be the cause of using ~1mA instead of ~100 microA? Any idea how I can decrease this further?

*Edit 1: it should be even much less than ~50 - 100 micro Amps*: https://arduino.stackexchange.com/questions/13983/attiny85-power-consumption-vs-clock-speed?rq=1 ; even though this the libraries are maybe primary intended for the ATMega328P, it looks like it should work also with ATTiny85 as well: http://www.technoblogy.com/show?KX0

*Edit 2: I had an ATMega328P-based Adafruit Metro Mini lying around. I took away the ON LED, and then using exactly this sketch, feeding power directly on the 5V pin of the Metro Mini, leads to a power consumption of around 150 micro Amps during sleep, which is more like what I expect. Strange it is 10 times more with the ATtiny while it should have been less (?). Am I missing something or is it maybe just broken library on ATtiny? This is a bit ironic, as I went for the lesser ATtiny85 based board for saving current compared with the ATMega328P...*

body:
Please have a look at the schematics:

https://cdn-learn.adafruit.com/assets/assets/000/010/774/original/adafruit_products_trinket5.png?1378223478

The USB connector uses a resistor (1500 Ohms) against the 5V net and a 3.6 Volt Z-Diode on it's (D-)-Pin. In addition to the current that is drawn by the microcontroller, this part of the circuit draws some extra current. (5[V] - 3.6[V])/1500[ohm] = 0.0009333... ~= 0.001 [A].

Even though I'm not completely sure without making some tests, that seams plausible to me.

__EDIT__
(Answer to the OPs comment below.)

The schematics uses a normal diode symbol but has a 3.6 Volt label next to it. I assume that it should be a Zener diode with a reverse voltage drop of 3.6 Volts. If I'm right, the Diode is used to limit the 5 Volts to 3.6 Volts (for what reason ever). The Zener Diode effectively limits  the Voltage over it to 3.6 Volts. The rest of the voltage of 5 Volts must be dropped over the resistor. i.e. 5V - 3.6V = 1.4V. This voltage drop tells us  by Ohms Law that the current through the  resistor is:

    I = U / R
    I[A] = 1.4[V] / 1500[Ohm]  = (about) 1 mA.

This value is very reasonable for your observations and the current is drawn from the 5V connect, hence you can measure it, even if you would desolder the microcontroller.


message:
What is importance of the reflow profile?

I was reading the MPU6050 datasheet to understand all the type of errors that affect the accelerometer, after finding information on the Reflow Profile i look up on wikipedia the [Reflow Soldering Definition][1]

As a noob i can't understand the importance, initially i though it was correlated with the temperature effect on the accelerometer bias, but i was wrong.

**Why is important?**

**How do you read this values?(or when you use this data)**
[![enter image description here][2]][2]
[![enter image description here][3]][3]

  [1]: https://en.wikipedia.org/wiki/Reflow_soldering
  [2]: https://i.stack.imgur.com/A1aQS.png
  [3]: https://i.stack.imgur.com/aIW8D.png

body:
[Reflow soldering][1] is an assembly process for printed circuit boards (PCBs) in which surface-mount parts are placed on a PCB prepared with solder paste.  The solder is melted by heating in a temperature-controlled oven, which then electrically connects component leads to pads on the PCB.  ICs can be damaged by high temperatures/rapid changes in temperatures, so the thermal profile defines the acceptable limits on the temperature of the reflow to avoid damaging the component.

  [1]: https://en.wikipedia.org/wiki/Reflow_soldering


message:
Arduino uno and 1602A I2C not working

I'm a newbie in engineering.

I bought this with arduino learning kit.

It's simply not working.

There are several possible problems:

 - The display is not working due to a hardware problem. It could need to be repaired or soldered better.
 - The library that I chose could be buggy (software problem)

How can I check this? Thanks!

PS Build-in led is blinking as expected.

Here is the code:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27, 16, 2);

    void setup()
    {
      lcd.init();
      lcd.begin(8,2);

      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop()
    {
      digitalWrite(LED_BUILTIN, HIGH);
      lcd.setCursor(0, 0);
      lcd.print("TEST");
      delay(1000);
      digitalWrite(LED_BUILTIN, LOW);
      lcd.setCursor(0, 0);
      lcd.print("   ");
      delay(1000);
    }

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

  [1]: https://i.stack.imgur.com/hyCrQ.jpg
  [2]: https://i.stack.imgur.com/04oZa.jpg

body:
Try with this address 0x3F or 0x27

    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // or 0x27
    void setup() {
    lcd.begin(16, 2);
    }
    void loop()
    {
      digitalWrite(LED_BUILTIN, HIGH);
      lcd.setCursor(0, 0);
      lcd.print("TEST");
      delay(1000);
      digitalWrite(LED_BUILTIN, LOW);
      lcd.setCursor(0, 0);
      lcd.print("   ");
      delay(1000);
    }


message:
How to identify Adafruit Feather 32u4 via mac id/UUID/etc

I'm working with a couple Feather 32u4 devices and I've had success so far in setting them up as transmitters and receivers as well as hooking up one of them to a Featherwing Ethernet and talking over MQTT. My problem is that I'm trying to find out how I can implement some sort of identification system among them so that I can send packets to a specific radio. The approach I'd like to avoid is that of writing different versions of the code with different IDs hardcoded in each and uploading them to a radio (so ideally I'm wondering if there's a way to access an inherent mac ID/UUID of each radio). Each radio did come with what appears to be a mac ID printed on a piece of paper but I don't know how to access that directly from the device.

Thanks!

body:
I'm quite sure the reason they print a mac address on a sticker and put it in the package is that they have no way of storing the address in the the feather wing, or at least don't bother to do so if there is a place to store it.

It's up to you to get that address to your Ethernet.begin() call.

FYI, I have been trying to use EEPROM to store the mac address, but the bootloader appears to blow away EEPROM with every reboot.  If I figure that one out I'll update.


message:
Connect Arduino to an external microSD card reader

I have a camera with a microSd card reader that is the only output type.
I want to read the microSd when the camera makes a photo.
How can I read it with an Arduino?
Duplicating the reader connections and join it to my Arduino microSd reader?
Or I can try to connect to the circuit (its very very small)?
Do you think I can put an ESP8266 to the camera?

Thanks for all!!!

body:
**You cannot**

SD cards cannot be shared between masters in operation, and it is unsafe to disconnect the card from the camera with an electronic switch when the camera is not expecting that.

Nor is an ordinary Arduino fast enough to passively snoop the data being written to the card by the camera (while a card will let an Arduino write to it quite slowly, any camera would do so far, far faster)

Nor is an ordinary Arduino able to do much of anything meaningful with the image files produced by a typical camera in real time.

Nor can an ESP8266 while running Arduino-based software; it apparently does have some high-speed I/O capabilities but that would require low-level rather than Arduino-port-based programming.

For all practical purposes, you'd need to power off the camera, remove the card, and place it in the Arduino reader.


message:
Powering a DC motor with an external battery

I'm working on a project where i need to control a 6 volt motor with an Arduino. The motor that I'm using requires 6 volts so I'm using a 9 volt with a voltage divider to get those 6 volts. My problem is that when I use the external power, the motor keeps spinning and ignores the input from the Arduino. If I use a 5 V battery and draw the 5 V from the Arduino, it works fine. I made sure that the voltage divider sends out 6 volts and the current code should have the motor not spinning. Here is the circuit: [Motor Schematic][1].

What could I do to make the motor take the input from the Arduino?

Note: The schematic isn't like my actual circuit. In reality I have 6 V power supply instead of a 9 V and a voltage divider. I also am using a motor that requires 6 volts, while the one in the schematic requires 5 V.

  [1]: https://circuits.io/circuits/4931324-motor-schematic

body:
Your schematic is bad - the motor is connected betveen base and power, emitor is connected to ground.That keeps the transistor open, and B-E voltage is like 0.7V, rest is for the motor to rotate.
More over the transistor is open, so if you send pulses from pin 3, they are shortcuted to ground thru the transistor, not affecting the motor at all.

Switch the wires to Base and to Colector (lines 48 and 49) and it should work better.

(Still I would not use divider 9->6 volts, losing a lot of power constantly, I would rather change the PWM little down (and have it relatively fast, 1kHz or more) and the motor should be OK, if effective voltage ther would be under 6V - so the PWM under like 66% HIGH. Also shortcutting pin3 to ground with resistor is not optimal, the resistor should be between pin3 and Base.)


body:
In power application like motor driver you can not use voltage divider for step down the voltage because resistor drop the voltage when current flowing from the resistor increase. You can used voltage regulator or buck converter. The motor will work fine. Even you can use 9V battery and control the speed of dc motor using PWM.[![enter image description here][1]][1] you use the following schematic both will work fine. The 2n2222 is the general purpose npn transistor which is used for power amplification. The arduino board can not provide large current at output pins to drive motors directly having a current rating more than 250mA.

In above schematic the LM2596 buck converter is used which current rating is about 3A. and you can adjust the desired output voltage.
[![enter image description here][2]][2]

The second option which shows in schematic is to use 6V battery.

  [1]: https://i.stack.imgur.com/1IrTa.jpg
  [2]: https://i.stack.imgur.com/coB5d.png


message:
Drawing specific RGB on touch screen

I have the Arduino MEGA and an adafruit touch screen 2.8 inches.

**My goal is to draw a pixel given a specific RGB**

I am using the `ILI9341`, `GFX`, and `TFT.h` libraries to draw and control the touch screen. I noticed the `drawPixel` function given, in which it takes in three parameters and draws the pixel:

    tft.drawPixel(4,4,ILI9341_BLUE);

But, I am trying to draw a pixel with specific a RGB. So instead, the function would ideally need 5 parameters instead of 3, x, y, and then R, G, and B:

    tft.idealDrawPixel(5,6,89,234,76);

I tried putting in a number as the third parameter and not `ILI9341_COLOR`, and the screen just prints blue:

    tft.drawPixel(45,67,255);

Is there a function that allows me to draw RGB pixels specifically? Thanks for any help!

body:
As noted in the second paragraph on [Adafruit's Graphics Library webpage](https://learn.adafruit.com/2-8-tft-touchscreen/graphics-library),

>First thing to note is that color is 16-bit, and that includes Red, Green and Blue in a 16-bit variable. The way the color is packed in is the top 5 bits are red, the middle 6 bits are green and the bottom 5 bits are blue.

If you want to specify 8-bit color components, you could write an intermediary routine to translate from that form to the 565 form.  For example:

    #define rgbDrawPixel(x,y,r,g,b) drawPixel(x,y,(((r)&0b11111000)<<8)|(((g)&0b11111100)<<3)|(((b)&0b11111000)>>3))

Note, this assumes the TFT library you're using has the same specs as Adafruit's.  That might or might not be; I don't know how to account for a 255 color number showing up as blue rather than white.


message:
Serial.Write(buf,Len) how to read Serial sended array of byte

hello i'm trying to send array of byte with `Serial.Write(buf,Len)` but don't know hot to read this code with receiver.

SENDER code:

    byte buf[4]={1,2,3,4};
    void setup(){
    Serial.begin(250000);
    }

    void loop(){
    Serial.write(buf,4);
    }
RECEIVER code (WRONG)

    byte buf[4];

    void setup() {
      Serial.begin(250000); // how suggest

    }

    void loop() {
      int i = 0;

      if (Serial.available()) {
        Serial.readBytes(buf,4);
        Serial.print(buf[0]);
        Serial.print(buf[1]);
        Serial.print(buf[2]);
        Serial.print(buf[3]);
      }
    }

How to receive this ??

body:
You have two issues:

Firstly the transmitter is set to 250000 baud (a non-standard rate) while the receiver is set to 9600 baud. Both need to be set to the same rate.

Secondly the transmitter is constantly sending data and the receiver is constantly reading it, there is no way to ensure the two are synchronized. So your receive buffer could well end up being the end of one set of data and then the start of the next e.g. 3,4,1,2. If all you are sending is the same loop over and over this doesn't matter but for real world data it's an issue. If you have a value which you know will never be in your data (e.g. 0 or 0xff) then you can use that as a start of data marker, if not then things get a little more tricky.