text:
16 bit register addressing through i2c
Note: I'm using just the atmega chip and atmel studio. Not exactly a full arduino.
I have been using the atmega168 with a MAX17040 fuel gauge in a project. The I2C interface between the atmel and the fuel gauge is working fine and I am able to read data from the fuel gauge.
Due to the power requirement of the project, the fuel gauge requires its compensation value to be adjusted. This is a 16 bit register, so according to the manufacturer I have to write 0x1234 across address 0x0C and 0X0D in one go. Otherwise the values are discarded.
All the datasheet and online forums talk about 8-bit I2C addressing (which I have working), but instruction on addressing 16 bit register is limited. I was wondering if anyone can help me on this.
My basic code is pasted below. The I2C_start takes care of TWCR, TWDR, etc. It could be something to do with Repated_Start, but not sure.
uint8_t I2C_write_register(uint8_t device, uint8_t address, uint8_t value)
{
    device <<= 1;

    uint8_t ret = I2C_start(device | TW_WRITE);
    if (ret)
        return 1;

    if (!ret)
        ret = I2C_write(address);
    if (!ret)
        ret = I2C_write(value);
    I2C_stop();

    return ret;
}

uint8_t I2C_start(uint8_t address){
    // reset TWI control register
    TWCR = 0;
    // transmit START condition
    TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);
    // wait for end of transmission
    while( !(TWCR & _BV(TWINT)) );

    // check if the start condition was successfully transmitted
    if((TWSR & 0xF8) != TW_START){ return 1; }

    // load slave address into data register
    TWDR = address;
    // start transmission of address
    TWCR = _BV(TWINT) | _BV(TWEN)|_BV(TWEA); //|_BV(TWEA) added
    // wait for end of transmission
    while( !(TWCR & _BV(TWINT)) );

    // check if the device has acknowledged the READ / WRITE mode
    uint8_t twst = TW_STATUS & 0xF8;
    if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) return 1;

    return 0;
}

How does Wire not handle this already?

I should add, i'm not using a full arduino, just  the atmega168 chip. And i'm using twi.h library from atmel studio.

So... then I don't understand why you asked this here.

Arduino and the atmega168 are essentially the same core. If the arduino can address 16-bit word over I2C, the atmega can do it too.

But why ask in the community where they use Wire, when your needs would be better served by a wider audience?

@IgnacioVazquez-Abrams you don't have to use Wire on Arduino, since as tsf144 pointed out, they are both using pretty much the same core. There doesn't happen to be a stack exchange site dedicated to AVR or even just microcontrollers, so this is probably not a bad place to ask.

Ahh, was just able to solve it. Essentially, do not use TW_REPEATED_START. Just keep sending data 8 bit at a time. 1 bit at the beginning of each 8 bit will be lost, so make sure you shift them first.
Wire library uses a very similar concept for use with arduino.
uint8_t I2C_write_register(uint8_t device, uint8_t address, uint8_t value, uint8_t value)
{
    device <<= 1;

    uint8_t ret = I2C_start(device | TW_WRITE);
    if (ret)
        return 1;

    if (!ret)
        ret = I2C_write(address);
    if (!ret)
        ret = I2C_write(value);
    if (!ret)
        ret = I2C_write(value2);
    I2C_stop();

    return ret;
}


text:
How to add Attiny13 to Attiny board profile in Arduino IDE 1.6?
Several months ago, I asked how to add (or where to get) Attiny13 to the list of boards in the Attiny package available in github: https://github.com/damellis/attiny In post 1.5 IDE, the package is installed by adding repo's JSON file to boards manager, as described in this post: https://arduino.stackexchange.com/a/23056/2955
Nowhere it says how to modify the files, not at all. And the package doesnot contain Attiny13 info.
The answer to my question was to do it myself and make a pull request. So ok, but how do I do it? I don't understand those files. The JSON file refferences some SHA-256 named zip files. That's hardly something that can be clearly and simply edited.
Can anyone tell me clearly what do I have to do to get Attiny13 working within that profile?

Did you manage to fit an Arduino core inside the smallish ATtiny13 ? :-O

this is the official Arduino IDE 1.5 3rd party Hardware specification. It is still valid for 1.6.
It is probably lots easier to just copy past a similar board; rename the board ID and try.
Note that for a change in the boards.txt to be seen in the Arduino IDE you need to stop and start the Arduino IDE.

But where can I find the boards.txt file? Won't it get overwritten upon next update?

The first part of the document is about the folder structure so that tells you where you can find the boards.txt. Unless you upgrade or deinstall and reinstall the boards.txt will not be overwritten. But it is always safe to have your own copy (for instance on github)

You can easily add entries for the ATTiny13 to the IDE, but won't show in the same listing as damelis's ATTiny cores, as he hasn't added the ATTiny13 yet.
Here is what I have found for ATTiny13 Arduino core files, working with  boards.txt, loading them into the IDE, etc.  The boards.txt is all laid out, just drop it into your personal workspace per the directions provided.
https://github.com/MCUdude/MicroCore
How to install
Boards Manager Installation
This installation method requires Arduino IDE version 1.6.4 or greater.
Open the Arduino IDE.
Open the File > Preferences menu item.
Enter the following URL in Additional Boards Manager URLs: https://mcudude.github.io/MicroCore/package_MCUdude_MicroCore_index.json
Open the Tools > Board > Boards Manager... menu item.
Wait for the platform indexes to finish downloading.
Scroll down until you see the MicroCore entry and click on it.
Note: If you are using Arduino IDE 1.6.6 then you may need to close Boards Manager and then reopen it before the MicroCore entry will appear.
Click Install.
After installation is complete close the Boards Manager window.

This will get you quite a lot of functions, configurable clock speeds, etc. The readme for this project helped me quite a lot  in understanding what is going on inside the box and how I can enable only the Arduino core functions that I want, to save space.
Microcore is based upon :
sourceforge.net/projects/ard-core13/files/latest/
And both projects have code updates as of this summer.
For other ATTiny (I'm using an ATTiny85 sometimes since for some things I ran out of space on the ATTiny13)
github.com/damellis/attiny
This will get you:
ATtiny 25 (8 pin)
ATtiny 45 (8 pin)
ATtiny 85 (8 pin)
ATtiny 24 (14 pin)
ATtiny 44 (14 pin)
ATtiny 84 (14 pin)

source: Stack Exchange

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

sort: votes


text:
Directly read analog voltage using PWM duty cycle timer registers
I'm outputting an analog voltage by setting an 8-bit duty cycle using analogWrite. Once set, I'd like a way to read back this duty cycle. I've managed to read the duty cycle back from the OCR4D register, which matches the value set, e.g.:
pinMode(6, OUTPUT);
analogWrite(6, 123);
Serial.print(OCR4D);   // 123

However, when setting the duty cycle to 0 or 255, OCR4D is not actually set at all; instead analogWrite calls digitalWrite behind the scenes and the pin is digitally set to LOW or HIGH. This is seen in the source for analogWrite:
if (val == 0)
{
    digitalWrite(pin, LOW);
}
else if (val == 255)
{
    digitalWrite(pin, HIGH);
}
else
{
// set PWM duty cycle as normal...

The problem with this is that OCR4D is simply left at its previous value, so it's not always possible to tell the actual output by reading OCR4D alone. In other words there is no way to tell the difference between:
- PWM is active and OCR4D reflects the duty cycle
- PWM is disabled and OCR4D reflects a previous duty cycle (which is not useful)
Which register(s) can I read to crosscheck the PWM is active?
I'm also aware of the pulseIn function, but would rather read the PWM register directly.

digitalRead(pin) will tell you if it's 0 or 1

Unfortunately it also turns off PWM for that pin: if (timer != NOT_ON_TIMER) turnOffPWM(timer);. I want to read the value without changing it @dandavis.

i thought you said that PWM was already turned off for those values? you would only use the digitalRead if the other failed.

Ah, sorry @dandavis my question wasn't very clear, I've since updated it. PWM does get disabled for those values, but it's not possible to tell if OCR4D is "wrong" as it always returns a valid duty cycle (it just keeps the old value). What I'm after is a way to tell if the PWM is active and that value is being applied.

ahh. the way i do this in my projects is to define analogWrite2(pin, val), which sets an external array of values by the pin number, then calls the real analogWrite() with the passed values. You can refer to the array from anywhere for a fast reliable read. Just run a replaceAll w/ analogWrite2...

Thanks @dandavis I wanted to avoid caching, but that's also a nice solution.

In the end I managed to do this by reading the timer/counter control register relevant to pin 6:
// read the voltage on an analog output pin
int analogReadOutput(int pin) {
    switch(digitalPinToTimer(pin)) {
        case TIMER4D:
            if (TCCR4C & (1 << COM4D1)) {   // PWM active
                return OCR4D;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        case TIMER4A:
            if (TCCR4A & (1 << COM4A1)) {   // PWM active
                return OCR4A;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        default:
            return -1;
    }
}

Note that this assumes two things that possibly aren't always true (outside of my simple program):

COM4D1 bit is a reliable way of telling if PWM is enabled,
duty cycle value is 8 bit with a max of 255.

arduino turns on/off the COMx bits for pwm controls -> take a look at turnOffPWM(). So a more reliable way is to read those bits to determine if a pin in in pwm or digital mode. actually a simple modification of turnOffPWM() would be more consistent in my view.

Yes @dannyf that's certainly more reliable. In my case the relevant bit is COM4D1. Edited answer to match.

If your own answer works please accept it.

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


text:
Can Arduino Leonardo use USB port and RX TX serial pins at the same time?
Can I use the TX/RX on pins 0, 1 (to a serial slave device) while also having the USB port dedicated PC communication?

actually When you uploading a sketch to your board through USB programing port that time the skect might go to the serial device which is connected with Arduino through Rx and Tx pin

@Prayuktibid I couldn't see any signal on pins 0 or 1 with a scope when using the USB port, even with those pins set to an output.

@Prayuktibid he is using a Leonardo which has separate USB and hardware serial.

How to use USB and TX/RX at the same time?

32u4 is multi-serial uC. USB connection works on default serial communication which can be used via Serial.print("somevalue"). On the other hand if you want to use RX/TX on pins 0, 1 which are actually RXD1 and TXD1. So, if you use Serial1.print("somevalue"). So the answer is a yes. You can use USB and RX/TX (hardware serial) at the same time.

Great, thanks. Do you know how this compares with other boards? Apparently the Uno can't do use both.

Arduino Uno can't do this, it has only one hardware serial.
Atmega 2560 has 4 hardware serials.
Having multiple serials are always handy. With Uno you just stuck and have to use software serial if the case more than one serial. Most of the time Software Serial doesn't treat you well, it is just a workaround after all.

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


text:
detachInterrupt(0) in arduino not working ? after giving continuous ground to INT0 wakeupnow function should execute once not again and again
#include <avr/sleep.h>

int wakePin = 2;                 // pin used for waking up
int led=13;
int flag=0;

void wakeUpNow()
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
  int count=10;
  while(count!=0)
  {
    delay(1000);
    count--;
    Serial.println(count);
    delay(1000);
  }
}

void setup()
{
  Serial.begin(9600);
  pinMode(wakePin, INPUT_PULLUP);  // wakePin is pin no. 2
  pinMode(led, OUTPUT);          //   led is pin no. 13
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow()
{
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();                        // enables the sleep bit in the mcucr register
                      delay(500);
                      Serial.println("Rajat");
                      delay(500);
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                      delay(500);
                      Serial.println("Rajat");
                      delay(500);
    sleep_mode();     // here the device is actually put to sleep...!!
      // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                      delay(500);
                      Serial.println("Rajat2");
                      delay(500);
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
    sleep_disable();         // first thing after waking from sleep: disable sleep...
                      delay(500);
                      Serial.println("Rajat3");
                      delay(500);
       detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.

}

void loop()
{
      digitalWrite(led, HIGH);
      delay(1000);
      digitalWrite(led, LOW);
      delay(1000);
    /* delay(500);
      Serial.println("jam");
      delay(500);  */
      if (flag==0)
      {
      sleepNow();     // sleep function called here
      flag=1;
      }
}

After Last Rajat I give ground to INT0.
Output in serial monitor :
Rajat
Rajat
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
& so on..!

function should execute once ... are you sure?

after 2 nd rajat is printed, I give ground continously to INT0.
now seeing stepwise..! 1) wakeupnow function will be executed than 2) We detach the interrupt to stop it from continuously firing while the interrupt pin is low using detachinterrupt(0) so now after getting ground wakeupnow should not be exexuted as interrupt is detached from pin 2 even though pin 2 is getting ground

this is not the first thing, is it? sleep_disable();         // first thing after waking from sleep: disable sleep...

Yeah sorry forgot to edit comments, It is written wrong over there..! after getting interrupt 1st thing is wakeupnow  function starts to execute..! but what's wrong in my previous comment..!

but what's wrong in my previous comment ... everything ... you are making an incorrect assumption  about INT0 .... read the documentation ... also look at my first comment ... it is a big red flag

Thanks..! for pointing out mistake will come back after reading document and analysing it again..!

Also; using delay and serial.print inside the interrupt service routine is asking for trouble, as both of them also require interrupts themselves. I'm surprised it even did show you that output.

You're detaching in completely the wrong place. After sleep_mode() returns from sleep and before the interrupt is detached you have an entire second of time where your interrupt can still fire. And it will fire, since a LOW interrupt will keep firing while the input is LOW.
sleep_mode();     // here the device is actually put to sleep...!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                  delay(500);
                  Serial.println("Rajat2");
                  delay(500);
detachInterrupt(0);

Instead you should detach the interrupt within the interrupt routine itself:
void wakeUpNow()
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up

    detachInterrupt(0);

  int count=10;
  while(count!=0)
  {
    delay(1000);
    count--;
    Serial.println(count);
    delay(1000);
  }
}

Also, all those delays and Serial prints in an interrupt are seriously problematic. An interrupt should never delay() and should never Serial.println().

I agree with Majenko. Since interrupts are off inside an ISR, delays won't work. Thus your code will hang indefinitely. Don't do delays inside an ISR. (Nor serial prints).


text:
Connecting two arduinos with wifi over the Internet
I have worked with Arduino before, but not with WiFi modules. I always used RF or other methods.
Now I am working on a project where i need to connect two UNOs, over long distance, but they will have a continuous internet connection.
One board with only send data, and one will only receive.
Will the esp8266 soc suffice for this? They will have fast network connection; at least 4g speeds. So can I send and receive real time data over the internet, and receive it fast? It should feel like there is no delay on the receiving side. Can I do this with the ESP, and if so, can any one point me towards the right material to get started.
thx in advance :)

i don't see why you need the unos for this, just use two ESPs to keep cost and complexity to a minimum.

How long is a "long" distance?

need two uno as one is connected to a senor which gives analog output,whicle the other is used to control a screen(LCDor led)and a few servos.long distance means communication over the internet.

The ESP8266 has one analog port and and supports SPI and I2C which will let you connect to a range of ADC devices.  Look at the ESP8266 12E of 12F.

The ESPs are easy to work with and more than capable, BUT (there's always a "but"): with a public network in the middle, latency, routing, and traffic issues will be beyond your control. Look, for instance, at the variability in page load times when loading over the internet.
If you use an IoT server in the middle, there will be server delays outside your control as well, though connecting to a common server from both ends can make it much easier to get everything talking for the first time. (There may, however, be data-rate limits imposed on you if the server in the middle is a free service.)

So can I send and receive real time data over the internet, and
  receive it fast?

Define "real fast". Do you mean "really quickly" (short delay from start of transmission to start of reception at the other end)? Or "really high throughput" (moving lots of data in a short time, or continuously without falling behind? Or something else?
Since you're working with an Uno, if you need to use a SoftwareSerial port to talk to the ESP, the SS will be limited to 9600 baud (equivalent to 960 Bytes/sec) and your ability to push data through it to somewhat under that. If you can use the built-in hardware UART your data-rate to/from an ESP can be much higher, at least 115200 baud or 11,520 B/sec (again, gross rate; rate of pushing data will be somewhat lower).
tl;dr: The network will be a much greater limitation than the ESP devices.
Update:

the problem i see is the delay with communication over the internet
  between the two uno if i use a server.can i communicate between the
  two with out the use of a server

Of course. Using an intermediate server might be a useful step on the way to getting your devices to talk directly. It would allow you to focus on the clients themselves at first and leave (most of) the networking issues to work out later. But you'll still have the issues of any network and especially a public network. If you have no other choice, you build it and you get whatever you get for performance. How serious are the consequence of a delay or a lost packet? Inconvenience? Delayed system functions? Will it cost someone money? Could someone get hurt? Could someone die? How dire the consequences could be will determine how stringent (and expensive) your solution has to be and what backups might have to be in place.

thx for ur reply, 9600 baud should suffice (need to practically check),but the problem i see is the delay with communication over the internet between the two uno if i use a server.can i communicate between the two with out the use of a server

Have you considered using Particle Photons instead?
They're $19, wifi enabled, Arduino compatible and they come with a very extensive cloud API functions that will allow you to pass information between them really easily:
https://docs.particle.io/reference/firmware/photon/

looks promising but its too costly.


text:
How do i get stored Midi to Play back without the notes sounding sustained?
How can i get my stored midi notes to play back without sounding sustained like in this video : https://youtu.be/zc1zbwheyE0?t=2m30s. Here is some of my code:
// Callback function to for recording note played is called upon reception of a NoteOn.
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {

if ((currentState != STATE_R) || (noteIndex >= MAX_NOTE))
      return;

  // Record the note
  noteList[noteIndex].channel = channel;
  noteList[noteIndex].pitch = pitch;
  noteList[noteIndex].velocity = velocity;
  noteList[noteIndex].deltaT = millis() - lastNoteTime;

  lastNoteTime = millis();
  noteIndex++;

 }

 void StateMachine(void)
{
  static uint16_t  nextNote;

MIDI.read();   // keep this going as fast as possible and empty buffer all the time

  switch (currentState)
  {
    case STATE_I2P:    // Set up for playback

      nextNote = 0;
      lastNoteTime = millis();
      SwitchState(STATE_P);
      break;

    case STATE_P:      // Play the notes back
   lcd.clear();
 lcd.setCursor(5,0);
  lcd.print("Playing Recorded Song");
  if (nextNote >= noteIndex) SwitchState(STATE_P2I);  // we are done

       if ((millis() - lastNoteTime) >= noteList[nextNote].deltaT)
       {
         MIDI.sendNoteOn(noteList[nextNote].pitch, noteList[nextNote].velocity, 1); //noteList[nextNote].channel);  // Send the note
        noteOn(0x90,noteList[nextNote].pitch,100);
         nextNote++;
         lastNoteTime = millis();
       }
      break;
   }

You need to store and send out the 'note off' messages in addition to the 'note on' messages.

how do i add stored midi for note off to what i already have ? am not sure how i would implement that. if the note is on then off wouldn't the note not sound?

A MIDI stream is far more than just a list of notes to play. It's a set of instructions to the musical instrument on exactly how to play the music.
Take the typical MIDI keyboard, for example.  When you press a note a "Note On" message is generated. This contains the note number (pitch) of the note to play along with the velocity (volume) of the note. It's called velocity because it's derived from how fast the key travels between two points - the faster it travels the harder you must have hit it and so the louder it should sound.
Then when you release the key a "Note Off" message is generated. This tells the target to stop playing the note.
Normally if you get two "Note On" messages for the same note without a "Note Off" for that note in between the new "Note On" replaces the old one, and a subsequent "Note Off" will stop all sound for that note, not just the most recent "Note On".
As well as those there are other messages as well detailing various other aspects of the music - patch and bank (instrument) selection, pitch bend, sustain, after-touch, etc. All of these are important to the overall sound of the music. And then there are "SysEx" messages (System Exclusive) which are (to a large extent) exclusive to the system that is generating them (hence the name). To faithfully recreate the music all of these should be stored as well.
The bare minimum though would be to store both the "Note On" and "Note Off" and maybe the velocity. How you store them is up to you, but both of them are required.
In your existing code you would need to expand the structure of your array to include what the instruction is. Not just assume it's all "Note On", but store whether the instruction is a "Note On" or a "Note Off", so when you play the MIDI back you can send the correct sequence of On and Off for the notes.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Serial sensors and the Yun
I am involved in a project that is going to measure PH and chlorine in a swimming pool.  The plan is to use a Arduino Yun. The sensors we are going to use are connected using serial.  Since we may be using multiple sensors, is there any difference in reliability, latency, known issues (bugs) of using software serial versus pin0 and pin1? Is it any way to avoid software serial pitfalls (if there are any)?

The Yun is a bit different to other Arduinos. The main microcontroller is a ATmega32U4 with a build in USB interface. This is used for the connection to the PC so the single USART is not used for this purpose.
However, the single USART is used for connecting to the built in wireless processor. This means that you can't use the wireless and hardware serial at the same time. I presume you are using the Yun for wireless, so disabling this is not desirable.
SoftwareSerial is relatively good, but does consume a lot of cycles. You can only listen on a single port at a time. It is possible to use pin change interrupts to listen for activity on multiple ports and switch to the one required, but this requires that the other end can wait for a response.
SoftwareSerial will tie up the microcontroller whilst sending, which can lead to problems when supporting low baud rates. Conversely, because it is CPU heavy, it can also have problems with high baud rates. There is a window, between 9600 and 38400 baud, where it seems to work best.
There is another software serial version called AltSoftSerial. This works faster than SoftwareSerial and can transmit and receive at the same time.
You can use the USART, SoftwareSerial and AltSoftSerial all at the same time. Be warned that because all three of these use interrupts and some use timers, you are highly likely to end up with complex, hard to debug interactions.
Note than in older versions of Arduino (pre v1), SoftwareSerial was very, very poor. It was replaced entirely with "NewSoftSerial".
Sensors are often have very basic USART hardware with limited buffer sizes, and drop data when they aren't serviced in a timely manner.
I am not a massive fan of the Yun. It isn't popular, the wireless is still relatively hard to use (compared to the TI CC3000), and the wireless interface uses valuable pins. Personally, if I was to work on a project that required multiple serial interfaces, I would either

Use a board with multiple USART, such as a ATmega1280 (2 USARTs) or ATmega2560 (4 USARTs) and a CC3000 (SPI connected) wireless board.
Use SPI/I2C->USART bridges. This allows a single SPI/I2C port to control multiple USARTs. Sparkfun sell one, there are many others available.

Be cautious of falling into the trap of using hardware because it is what you have available.

I don't have any experience with the Yun so I can't comment on that specifically, but the only problem you'll encounter with using SoftwareSerial is that you can only communicate with one device at a time.
This means you'll have to make a call to listen()
sensor1.listen()

before communicating with sensor1. Then when you want to communicate with another sensor, you have to do the same.

I didn't check the circuit diagrams, but on most AVR based Arduino's pins 0 and 1 are used to program the device. By reusing the pins, you may run into problems when trying to program the Arduino from IDE. It is easily solved by detaching the hardware from those pins, but you have to reattach them to test the sketch. I personally try to avoid using those to pins, just for ease of development.


text:
currentbuttonstatus
I'm trying to use momentary push buttons to switch bi color LED between RED and GREEN. I've got one working, but when I try to adapt the code for more buttons, it doesn't work. I'm just changing the buttonnumbers (which are defined).
It compiles and uploads without error.
void loop() {
  byte currentButton1Status = digitalRead(button1);
  if (currentButton1Status == button1Status)
    lastEqualButtonTime = millis();
  else if ((millis() - lastEqualButtonTime) > debounceTimeMs)
  {
    lastEqualButtonTime = millis();
    button1Status = currentButton1Status;

    if (button1Status == LOW) {
      digitalWrite(17, !digitalRead(17));
      digitalWrite(16, !digitalRead(16));
    }
  }

  byte currentButton2Status = digitalRead(button2);
  if (currentButton2Status == button2Status)
    lastEqualButtonTime = millis();
  else if ((millis() - lastEqualButtonTime) > debounceTimeMs)
  {
    lastEqualButtonTime = millis();
    button2Status = currentButton2Status;

    if (button2Status == LOW) {
      digitalWrite(15, !digitalRead(15));
      digitalWrite(14, !digitalRead(14));
    }
  }
}

please post the complete code .... the way it is right now, there are a few definitions missing

You might want to look into using a debounce library  e.g. https://github.com/thomasfredericks/Bounce2

it doesn't work is not a good problem description

Use serial print to debug...

@chrisl there's nothing more to it. If I have the "byte currentButton...." just for button one, it works. If I use it the way I've posted above everything compiles and uploads ok, but when I press any of the two buttons, nothing happens.

@jsotola Everything is defined and I didn't want to bother you guys with other stuff that didn't have to do anything with this problem.

@user31208, you posted a partial program, so there is no way to confirm that the code compiles, and there is no way to pinpoint the failure

They can't all use the same variable, lastEqualButtonTime, to keep up with debouncing.

You've only said "... it doesn't work" which doesn't give much to go on, but the first thing I see that might contribute it not working as (I think) you expect it o, is only one lastEqualButtonTime variable for both buttons (is it a global? I don't see a definition). I think you'll need one for each.

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


text:
The BOOTRST fuse was disabled, but bootloader code is still running after chip reset
I am experimenting with an ATmega328P bootloader, and I created an Intel HEX (.hex) file with a program with an infinite loop in the beginning and with Optiboot code at the end of the hex file. (Code loaded into the chip is here: http://relliks.php5.cz/stackexchange/DUMP.bin.)
Then I disabled the BOOTRST fuse and pressed the restart button on Arduino Uno R3, but the bootloader still blinks with the LED on digital port 13.
How is it possible, that the bootloader is executed after chip restart and BOOTRST is disabled? My fuse settings are: Only SPIEN and BODLEVEL0 are set.
I found that when I disable the BODLEVEL0 fuse, the bootloader turns off.
BODLEVEL0 is used to set the brown-out voltage and shouldn't affect bootloader start. Where is the issue?

Please post the hex values for all your fuses. One way of doing that is to run my chip detector sketch.

Please do not cross-post the same question on different Stack Exchange sites. See Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site?. I refer to your post on Stack Overflow.

Thank you very much!
I found that when I set fuses using program PONYPROG2000 and native RS232 programmer (http://3.bp.blogspot.com/-2D_0B7...) then I read fuses again using another program (eXtreme Burner) and another programmer(USBASP 2.0), there was difference. The PONYPROG2000 probably sets the fuses incorrectly.
Now the Atmega328P works correctly yet.

You don't seem to have filled in all the interrupt vectors. I get this from your .bin file:
00000000 <.sec1>:
       0:       00 c0           rjmp    .+0             ;  0x2
       2:       00 00           nop
       4:       00 00           nop
       6:       00 00           nop
       8:       fc cf           rjmp    .-8             ;  0x2
       a:       fb cf           rjmp    .-10            ;  0x2
       c:       fa cf           rjmp    .-12            ;  0x2
       e:       f9 cf           rjmp    .-14            ;  0x2
      10:       f8 cf           rjmp    .-16            ;  0x2
      12:       f7 cf           rjmp    .-18            ;  0x2
      14:       f6 cf           rjmp    .-20            ;  0x2
      16:       f5 cf           rjmp    .-22            ;  0x2
      18:       ff ff           .word   0xffff  ; ????
      1a:       ff ff           .word   0xffff  ; ????
      1c:       ff ff           .word   0xffff  ; ????
      1e:       ff ff           .word   0xffff  ; ????
      20:       ff ff           .word   0xffff  ; ????
      22:       ff ff           .word   0xffff  ; ????
      24:       ff ff           .word   0xffff  ; ????
...
    7dfc:       ff ff           .word   0xffff  ; ????
    7dfe:       ff ff           .word   0xffff  ; ????
    7e00:       11 24           eor     r1, r1           <--- bootloader
    7e02:       94 b7           in      r25, 0x34       ; 52
    7e04:       14 be           out     0x34, r1        ; 52
    7e06:       89 2f           mov     r24, r25
    7e08:       8d 70           andi    r24, 0x0D       ; 13
    7e0a:       11 f0           breq    .+4             ;  0x7e10
    7e0c:       89 2f           mov     r24, r25
    7e0e:       de d0           rcall   .+444           ;  0x7fcc
    7e10:       85 e0           ldi     r24, 0x05       ; 5

Now I can't quite see the relationship between the brown-out and those higher interrupts, but if one of them happened to fire I think it would waddle its way past all those 0xFF instructions and hit the bootloader.
The Atmega328P has 26 interrupt vectors (including Reset).


text:
need help hooking up an oled display
recently i bought this oled display .

http://www.wvshare.com/product/0.96inch-OLED-A.htm
how can i connect it with arduino . Driver Chip is SSD1306 . Supported Interface are 3-wire SPI, 4-wire SPI, I2C . it's can display two colors Yellow and Blue.
i need some guidance on how to hook it up with arduino lets say using i2c protocol . and is there any existing library ?
Note : on the wvshare website there's only code sample for STM32 Microcontrollers .

Did you read the datasheet? https://www.adafruit.com/datasheets/SSD1306.pdf

Are you prepared to resolder the resistors on the back?

@jippie i read the datasheet. it seems i can use the DIN and CLK pin as SDA and SCL. i tried that but its not working .  Ignacio, which resistor ? i know some basic soldering. thanks

You have to remove the 0-ohm resistor BS1 from the 0 position and move it the the 1 position.

has anyone tried it with i2c? been 2 days now trying to make it work .resolder the resistors but dosn't want to work.
and after the soldering wich library should i choose ?

it's working with u8glib.  but i am using  4-wire SPI.
constructor for U8GLIB
U8GLIB_SSD1306_128X64 u8g(13, 11, 10, 9,8);

Pin configuration was
Arduino -   Oled Display
13 -    CLK
11 -    DIN (SI)
10 -    CS
9 - D/C (A0)
8 - RES

the reset pin is required. i used 3.3v  arduino pin for vcc .

Yes, that is what the silkscreened chart shows the installed resistors as selecting for operating mode.  Gerben had been suggesting you could do i2c if you changed them.


text:
Sensing busy-ness of a restaurant?
I'm planning on an Arduino project for a restaurant I work at that would require determining how busy it is at any point in time, but I'm not sure how I would go about procuring this information.
I don't have access to any of their IT systems or I would have simply pulled the data from their till systems.
I was thinking perhaps measuring the ambient sound of the restaurant as it gets quite loud during peak time but that could be thrown off when the music volume is adjusted.

There are a few ways to  go about it but my initial thoughts would be to detect people entering (and exciting) the front door and simply keep a running total.
Motion detector
http://www.adafruit.com/products/189
IR beam detectors
http://arduino-info.wikispaces.com/InfraredBeamPair

I don't think this is possible as the project must be small and placed in a dedicated corner of the restaurant, which is away from the door. If I were able to move it near the door, how would you distinguish between people entering and exciting?

You could use a variety of sensors but easiest would be a pair of $10 proximity sensors and depending on when they trigger you could work out if which direction the person was travelling. Alternatively use IT beam detectors http://arduino-info.wikispaces.com/InfraredBeamPair

I expect that a direction-of-travel based people counter might often loose track in many restaurants I'm familiar with - too many people waiting in the entryway, holding doors for others in their party, walking in side by side, etc.


text:
Arduino sketch works on ATmega1280, but doesn't work on ATmega328 (Arduino Nano)
I'm working on arduino based RGB LED strip controller.
This simple schematic was used to control 12V channels via 5V PWM signal from arduino:

I have also connected an HC-05 bluetooth module to be able to control it using android phone.
Android application, created for this project, is sending 4 bytes to set mode, red, green and blue colors. It looks like {0,255,0,0} to set static red color, {1,0,0,0} to start fade mode and {2,0,0,0} to start blink mode.
Here is my first demo video of this project:
click here.
The problem is that my code works perfectly on Arduino Mega 1280, but when I use Arduino Nano it works only with manual mode and blink mode. If I send {1,0,0,0} to turn on fade mode, LED strip starts to increase random color brightness and stops, before it gets to max value. In a moment LED strip turns off and doesn't react to bluetooth commands. Reset button helps in this situation.
I'm not sure, but I think there is not enough SRAM (only 2KB) on Arduino Nano to process fade mode data.
Source code:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(12, 13);

#define REDPIN 6
#define GREENPIN 3
#define BLUEPIN 9

#define FADESPEED 10
#define PANICSPEED 425

//0 - red
//1 - green
//2 - blue
int fadeColor = 0;
int panicColor = 0;

//values (brightness) for red, green and blue colors [0; 255]
int colors[] = {0, 0, 0};

long previousTime = 0;

//0 - manual, 1 - fade, 2 - blink
int ledMode = 0;

int fadeAmount = 1;

//if color is selected, it'll change brightness;
//when we got 0 or 255 brightness we'll change
//this flag and select next color in loop()
boolean fadeColorSelected = false;

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
  mySerial.begin(9600);

  randomSeed(0);
}

void loop() {
  long currentTime = millis();

  //data format - 4 bytes {mode, red, green, blue}
  if (mySerial.available() > 3) {
    ledMode = mySerial.read();
    int red = mySerial.read();
    int green = mySerial.read();
    int blue = mySerial.read();
    colors[0] = constrain(red, 0, 255);
    colors[1] = constrain(green, 0, 255);
    colors[2] = constrain(blue, 0, 255);
  }

  switch (ledMode) {
    //manual mode - just set received color on the led strip
    case 0:
      setColor();
      break;
    //fade mode - if color is selected, we'll
    //increase/decrease it's brightness by fadeAmount
    case 1:
      if (currentTime - previousTime > FADESPEED) {
        //change color (we can't choose the same color as previous
        //and we can't choose the color, if it's the last one,
        //because at least 1 color should be always ON
        if (!fadeColorSelected) {
          int randomColor = fadeColor;
          while (randomColor == fadeColor || isColorAlone(randomColor)) {
            randomColor = random(3);
          }
          fadeColor = randomColor;
          fadeColorSelected = true;
        }
        //depending on current brightness of selected color
        //we'll either increase, or decrease it's brightness
        if (colors[fadeColor] == 0) {
          fadeAmount = abs(fadeAmount);
        } else if (colors[fadeColor] == 255) {
          fadeAmount = -abs(fadeAmount);
        }
        colors[fadeColor] += fadeAmount;
        setColor();
        //when we got to max/min brightness, we should change current fadeColor
        if (colors[fadeColor] == 0 || colors[fadeColor] == 255) {
          fadeColorSelected = false;
        }
        previousTime = currentTime;
      }
      break;
    case 2:
      if (currentTime - previousTime > PANICSPEED) {
        int randomColor = panicColor;
        while (randomColor == panicColor || isColorAlone(randomColor)) {
          randomColor = random(3);
        }
        panicColor = randomColor;
        if (colors[panicColor] == 0) {
          colors[panicColor] = 255;
        } else {
          colors[panicColor] = 0;
        }
        setColor();
        previousTime = currentTime;
      }
      break;
  }
}

void setColor(int r, int g, int b) {
  analogWrite(REDPIN, r);
  analogWrite(GREENPIN, g);
  analogWrite(BLUEPIN, b);
}

void setColor() {
  analogWrite(REDPIN, colors[0]);
  analogWrite(GREENPIN, colors[1]);
  analogWrite(BLUEPIN, colors[2]);
}

boolean isColorAlone(int colorNumber) {
  if (colors[colorNumber] == 0)
    return false;
  for (int i = 0; i < 3; i++) {
    if (i != colorNumber && colors[i] > 0) {
      return false;
    }
  }
  return true;
}

Do you have any ideas why it happens?
If there is not enough SRAM, how can I optimize this code to solve the problem?

avr-size on the ELF says?

text 4770, data 22, bss 122, dec 4914, hex 1332

(data + bss) is less than 2KB, but it does not include dynamic memory allocated from the heap at run time...

You don't have any heap allocation. And I certainly don't see more than about 40 bytes in locals from the stack at any time.

I agree with you, but I have no idea, what can be wrong with it

Pin 13 has the Led on it. SoftwareSerial often runs better when using pins with interrupts. On the Uno that is Pin 2 and 3. I also find softwareSerial can be unreliable especially as low and high speed. So try the Uno on pin 2 and 3 and if possible use 19k or 56k which are usually reliable


text:
Hard-resetting an arduino
I need to hard reset (or seriously breathe life into) a stuck Arduino clone (Sunfounder UNO) which doesn't get recognized by Windows (error 43) after installing the wrong sketch. I am using the latest Arduino toolset and, before today, the setup was functional.
The problem is probably that I am writing to the serial in the setup() section like this:
void setup() {
  pinMode(a0, OUTPUT);
  pinMode(a1, OUTPUT);
  pinMode(a2, OUTPUT);
  pinMode(b1, OUTPUT);
  pinMode(m0, OUTPUT);
  pinMode(m1, OUTPUT);
  pinMode(m2, OUTPUT);
  pinMode(OK, OUTPUT);
  pinMode(KO, OUTPUT);

  pinMode(carry, INPUT);
  pinMode(result, INPUT);
  delay(1000);

  Serial.begin(9600);
  Serial.write("Arduino Tester v. 0.1\n");
}

Arduino seems to be running the code. The problem is that Windows doesn't recognize it and doesn't set up a COM port for it.
So: i'd like to nuke it and restart from scratch.
How is this done?

What kind of Arduino clone?  What USB interface does it use?

@Majenko updated the question

The word "clone" immediately rings alarm bells.
Firstly, for a "normal" Arduino (like an Uno, etc) the sketch cannot influence whether Windows detects the board or not.  All that is handled by a completely separate chip.
A lot of the cheap clones these days are coming out of China with a really really cheap USB serial adapter chip.  These barely work at the best of times.  Looking at the pictures I have found of your clone (the manufacturer's site is considerably lacking in any information whatsoever) it doesn't look like it's one of those chips, but one never can tell.
If they have followed the reference designs for the Arduino then it will be an Atmel ATMega32U4 (IIRC) chip that deals with the interface to the computer.  That has firmware of its own on it, and if that has become corrupted (very unlikely) or damaged (possible) then it could cause it to not be recognised.  If that is the case the in the former instance (corrupted) you will need to replace the firmware on it. For that you will need either a hardware ICSP programmer or another Arduino.  In the latter instance you're stuffed, since you would need to replace the chip.
As I say that is unlikely.
Instead your problem is most likely actually with either Windows or the USB cable.  You may need to remove and reinstall the Arduino drivers, or try a difference USB cable.  Also try your "Arduino" on another computer.

Interesting. The USB chip is Amtel AT MEGA16U2. I've tried on a completely different system (macbook air which also was working before today) and it didn't make a difference.

Solved: It was the cable.

The 16U2 was used on the R2 - they upgraded to the 32U4 for the R3 IIRC.

+1 for guessing it was the cable, Makenko. I just want to comment that I found some USB cables (eg. to a USB light or fan) do not have data wires. That is, to save money, they only use two wires, which carry the 5V power and ground, and omit the A/B data wires. Naturally such cables do not work as data cables, and therefore plugging into a PC using one achieves nothing.

@NickGammon It wasn't a guess - just weighing up the balance of probability - probably skewed slightly in (dis)favour of Windows failing, but that's personal bias...

before today, the setup was functional - yes, but ... How come it worked yesterday? Does the OP mean: Before today, the setup was functional, I then changed USB cables and it stopped working. However I never expected the change in cable to be the problem. ?

@NickGammon If the OP is anything like me all the USB cables are in a tangled mess on the desk, and one is just grabbed at random for use at that specific moment.  Never the same cable twice.  Of course, if I find one of my cables has stopped working, I cut the ends off it and strip the wires out of it to re-use them for something else...

@NickGammon dunno, I guess the cable simply failed today. I didn't change it and pick up the wrong one.

@Sklivvz Cables fail. Especially cheap chinese ones. My parents have gone through 6 charge cables for their iPad this year. at 3 for 99p from china it's no problem, just annoying.


text:
Operating Sharp memory LCD with Arduino
I am trying to write to Sharp memory LCD "LS027B7DH01" which isn't going well for me. I didn't find any useful information for beginners. I just want to display any character on the LCD. Here's my code:
#include<SPI.h>

int SCS=10;
int SI=11;
int SCLK=13;
int EXTCOMIN=4;

 void setup()
 {
   pinMode(SCS,OUTPUT);
   pinMode(EXTCOMIN,OUTPUT);
   pinMode(SCLK,OUTPUT);
   pinMode(SI,OUTPUT);
   digitalWrite(SCS,HIGH);
   tone(EXTCOMIN,40);
   SPI.setClockDivider(SPI_CLOCK_DIV16);
   SPI.setBitOrder(MSBFIRST);
   SPI.setDataMode(SPI_MODE0);
   SPI.begin();
   SPI.transfer(0×20);
   delay(3000);
}

void loop()
 {
   SPI.transfer(0×80);
   delay(3000);
   for (byte i=0; i<30;i++)
    {
       SPI.transfer(i+1);
       delay(3000);
      for(int j=0; j<50;j++)
       {
         SPI.transfer(0x0F);
         delay(3000);
       }
       delay(3000);
       SPI.transfer(0×00);
    }
    delay(3000);
    SPI.transfer(0×00);
  }

What adapter-board are you using?

@Gerben: I am not using any adapter board, directly connected arduino with the sharp lcd

As the page Sharp Memory LCD Breakout A2 shows, it seems that you need some additional circuitry to drive the display, such as capacitors and resistors. This is why breakout boards are usually employed. Quoting the page:

This is a simple breakout board for Sharp’s new Memory LCD displays (
  LS013B4DN02 and LS013B4DN04). It brings all pins to a 0.1″ header and
  provides necessary caps and resistors. The new revision A2 also adds
  an optional boost converter for those wanting to run 5V display from
  sub 3.3V supply.The footprints are there, but parts are not populated
  to save cost. I’ve also added silk labels to the header pins on the
  back. This is an open design under CC BY SA license.

Of course, you can always make your own breakout circuit. For example, you could reproduce the breakout board using a breadboard and some resistors and capacitors. The schematics are provided on that page for A1

and A2

So, in short, either purchase a breakout board, or make one. Once you have done that , you can use the CraftyCoders Arduino Library
Hope that helps.

I am a beginner in coding but I don't want to use libraries written by someone. I want to learn how to code the Sharp Memory LCD maybe starting with writing a character to the LCD. I am trying hard for the past two days but it isn't going well. I am able to turn on the display and the clear command is working but the write command is not working. I have added the code above, which I am working on.                                                                                As far as hardware is concerned, I have followed the above connections in my breakout  board.

@Naresh, You should use the library to validatie that your connections and the display itself are working. After that your can create your own library/driver code.

I looked at this question as I too plan to drive a Sharp Memory LCD manually with my own code at some point.  From your question and comments I think you are going about it the wrong way, even if you are already very proficient with the electronics side of the task.
As mentioned, the breakout board is the easiest way to connect the screen and the library is the easiest way to program it.  I suggest you use both initially and then replace them one by one.  I did this when driving a 32x32 LED matrix.
Once you have a little bit of code running that displays what you want on the screen, try removing the breakout board and wiring the display yourself without changing the code at all.  If the display is not what you expect, you know the problem is in the wiring so you don't waste time looking into your code.
Once the wiring is sorted, start on the driver code.  Leave the wiring and your code that makes the display show what you want untouched so that you know any problems are in your driver code.  The other advantage of this is that you have the working library as reference for how the screen works and what signals to send with what sort of timing.
As a pointer to why your code is not doing what you expect, I think you may be misunderstanding how the screen works.  Your question and code suggest you may be trying to display ASCII characters on the screen which I believe can be done easily with some LCD displays but I'm fairly sure that these LCDs are not character based - you have to manually set or clear each individual dot.  I think the minimum number of dots you can set at a time is a full single line of the display.
In your code you have a delay of 3000ms after every byte send.  At that rate it would take 2mins 30secs just to transfer the data for a single line of the screen so maybe you are sending the correct data, but are not waiting long enough to see the results.  I've also read that you have to do something (sorry, not quite sure what) at least once per second to prevent problems with the screen - this suggests that taking over 2mins to send a line of data could not work as you expect.


text:
SD Card shield and TCRT5000 sensor aren't working together on arduino uno
I need to work with SD card and TCRT5000 sensor (Reflective Optical Sensor with Transistor Output) and save data from sensor to file. So I select Arduino Uno and added to it a SD card shield(from LC STUDIO) and a TCRT5000 sensor but it isn't working.
My circuit and code is here:

#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

void setup() {
  Serial.begin(9600);
  pinMode(chipSelect, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while(true);
  }
  Serial.println("card initialized.");
  File dataFile = SD.open("test.txt", FILE_WRITE);
  dataFile.close();
  dataFile = SD.open("test.txt", FILE_WRITE);
  if(dataFile){
    dataFile.println("Start:");
  }else{
    Serial.println("Error in creating file.");
    while(true);
  }
}

void loop() {
  float value = analogRead(A3);
  File dataFile = SD.open("test.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println(value);
    Serial.println(value);
    dataFile.close();
  }else{
    Serial.println("Error in opening file.");
  }
  delay(5);
}

When TCRT5000 isn't connected SD card working without any problem.
I think it is related to current and supply current. Any idea?

I would like to believe that you made a mistake with +5 and GND from board???

60mA can not do any problem. Maybe you connected it wrong? 90% problems are in wiring :))

I checked it again. The circuit isn't wrong. I do it like this and this. If problem is not related to current,it is related to what? Why the SD card work when I remove TCRT5000 from circuit without any change in wiring?

Try disconnecting only D+. That way you know if the problem is with the IR-diode or the phototransistor.

The 5V to the breadboard power rails is 100% not in the right spot. Both the 5V and GND are in the same rail, causing a short. I assume this is just an error in the diagram, like @Martynas said?

Did you figure this out yet? If not, you have the +5 volts going to the GND on the breadboard, causing a short.


text:
DC Motor Not Braking
I have a brushed motor hooked up to a NodeMCU that moves a plate left (moveLeft) and right (moveRight). When a button (buttonOpen) is pressed, it turns to the left until the plate hits a limit switch (limit1), then the system stops and the motor driver goes to sleep. Then when a different button (buttonClose) is pressed, it moves the plate to the right, until a different limit switch (limit2) is pressed.
Now the thing is that I need the DC motor to brake once the limit switch is triggered, otherwise it will slowly roll over the switch (which is bad).
I noticed that I needed to apply the brake for at least a fraction of a second to get the motor to stop. If the brake is too short, the motor will continue to spin. That is why I created a loop that lasts 0.8 seconds (stopMotor)
The problem is that the brake is only being applied when the motor moves right. But when it moves left, it does not get applied and coasts to a stop. I can't figure this out for the life of me. I really need to to brake and stop in either direction.
Here's the code.
const int IN1 = 13;
const int IN2 = 12;
const int Enable1 = 14;
const int buttonOpen = 2; // Yellow
const int buttonClose = 0; // Black
const int limit1 = 5;
const int limit2 = 4;

void setup()
{
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(Enable1, OUTPUT);
  pinMode(buttonOpen, INPUT);
  pinMode(buttonClose, INPUT);
  pinMode(limit1, INPUT);
  pinMode(limit2, INPUT);
}

void moveLeft()
{
  digitalWrite(Enable1, HIGH); // wakes up driver
  digitalWrite(IN1, LOW); //
  digitalWrite(IN2, HIGH); // spins counter-clockwise
}

void moveRight()
{
  digitalWrite(Enable1, HIGH); // wakes up driver
  digitalWrite(IN1, HIGH); //
  digitalWrite(IN2, LOW); // spins clockwise
}

void stopMotor() //brake motor for 0.1 seconds to avoid coasting then place             driver to sleep
{
  int period = 80L;       // 0.08 seconds
  for( int tStart = millis();  (millis()-tStart) < period;  ){
    digitalWrite(IN1, HIGH); // brake
    digitalWrite(IN2, HIGH); // brake
  }
  digitalWrite(Enable1, LOW); // Sleep driver
}

void loop(){
  // Move motor right
  if (digitalRead(buttonOpen) == LOW){
    while(digitalRead(limit2) == HIGH){
      moveRight();
      yield();
    }
  }
  else
    (stopMotor());

  // Move motor left
  if (digitalRead(buttonClose) == LOW){
    while(digitalRead(limit1) == HIGH){
      moveLeft();
      yield();
    }
  }
  else
    (stopMotor());
}

I'm not sure, if this has to do with your problem, but the logic in your loop() is weird. When you hit a limit switch the code does not go directly to the stop function, because its in the else statement of the control button, which will not be evaluated, when you are inside its if statement. Insteat the stop Funktion will be executed in the next if statement ( for the other direction). Instead stop the Motor directly after it hit the limit switch

And the yield() function does WLAN stuff in the ESP, right? As I remember this has to be executed often enough or the webserver, you may want to use in future, will be unresponsive. Since it may take relatively long time for the motor to hit the limit switch, you can execute it inside the while() loop. Or rewrite your code to be completely non-blocking

Your whole methodology belies a complete misunderstanding of how the Arduino works. You do not need to constantly tell it "Go right!Go right!Go right!Go right!Go right!Go right!Go right!". You only need to do it once and it will keep going right until you tell it otherwise. What you need is a finite state machine to switch between different modes depending on the various external stimulii.

Thanks guys. Yes the     yield() function keeps the ESP from resetting since I have blocking code which times the ESP out.

And I found this code that uses a state machine in almost my exact same situation link. But I was very confused about this methodology so thanks for the link to that tutorial, I'll be sure to dive into it


text:
Arduino Zero Compiling Issues for "Test-AnalogReadFast-SAM"
#include <Streaming.h>
#include "StopWatch.h"
#include <Albert.h>
#include "avdweb_AnalogReadFast.h"

const byte adcPin = A1;

void setup(void)
{ Serial.begin(9600);
  while(!Serial);
  Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
  for(int i=0; i<10; i++) testAnalogRead();
}

void testAnalogRead()
{ static Stopwatch Stopwatch(micros);
  //delay(1000);

  stopwatch.start();
  int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
  stopwatch.stop(); int t1 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc2 = analogRead(adcPin); // 425us on SAMD21
  stopwatch.stop(); int t2 = stopwatch.interval;

  analogReadResolution(10);
  stopwatch.start();
  int adc3 = analogReadFast(adcPin); // 23us on SAMD21
  stopwatch.stop(); int t3 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc4 = analogReadFast(adcPin); // 24us on SAMD21
  stopwatch.stop(); int t4 = stopwatch.interval;

  Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
  analogReadResolution(10); // restore default
}

void loop(void)
{
}

Hi I have to run this code in the Arduino Zero. When I try to compile this code it throws the following error:
Error:
In file included from /Users/RAJU/Documents/Arduino/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino:2:0:
/Users/RAJU/Documents/Arduino/libraries/Streaming/Streaming.h:102:15: warning: unused parameter 'arg' [-Wunused-parameter]
 inline Print &operator <<(Print &obj, _EndLineCode arg)

               ^
/Users/RAJU/Documents/Arduino/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino: In function 'void testAnalogRead()':
Test_AnalogReadFast_SAM:17: error: 'Stopwatch' does not name a type
 { static Stopwatch Stopwatch(micros);
          ^
Test_AnalogReadFast_SAM:20: error: 'stopwatch' was not declared in this scope
   stopwatch.start();
   ^
exit status 1
'Stopwatch' does not name a type

Any helps are greatly appreciated

what debugging have you done? ..... did you try anything before posting the question?

it should be static StopWatch stopwatch(MICROS);

The compiler doesn't know the type Stopwatch. You have a typo there. A short look into the header file (StopWatch.h) shows you, that it is StopWatch and not Stopwatch. You need a big W there.
Next time first try to investigate yourself. Obviously you didn't do anything before asking here. Next time try it and then, if you  cannot find the problem, then write in your question what you have tried.

I was able to compile the following program in my Arduino IDE for Arduino/Genuino Zero:
#include "StopWatch.h"

void setup() {
  static StopWatch Stopwatch(StopWatch::MICROS);
}

void loop() {
}

The StopWatch library comes from this Github page. It is the same, that you linked within your other language with the same code, so I assume, that you use it.
For future questions: It is better to directly provide links to all used libraries, that are not part of the Arduino IDE.

No, I tried many times. I tried StopWatch also. It throws the same error for StopWatch and Stopwatch.

For me it compiles if I also write MICROS instead of micros. If it doesn't for you, please write a minimal working example, that shows this error, with no other library included than StopWatch

Are you also using the Arduino Zero ?

Could you please send me the link for the StopWatch library that you have used? Thank you for your comment.

@RajuKC: Added the compilable code and the library link to the answer

Hi thank you so much for your reply. Whenever I ran this piece of code in my Arduino Zero Sketch folder, It says " 'MICROS' is not a member of 'StopWatch".

Are you sure you have the same library, as I linked in the answer? For this library MICROS is defined as a part of the enum Resolution

Hi, I used this library from the link "https://github.com/RobTillaart/Arduino/tree/master/libraries/StopWatch "

Mhh, maybe try this: static StopWatch Stopwatch(StopWatch::Resolution::MICROS); . this answer states, that this can also work, and it correctly compiles in my IDE. Also: What IDE version do you use?

Thank you very much for the suggestions. could you please send me the zip file of the exact StopWatch library that you have used? That might be more helpful.

Just follow the link to the Github page, that I wrote in the answer. Also this is the same link, that you already send in the comments. I think we can be sure, that we refer to the same library. The IDE version may be important, because they may use different compiler versions inside.

@RajuKC, the library comes with example code .... did you even bother to try one of the examples?

Thank you for the suggestions. I tried to run the example code in the Stopwatch library which also does not compile.

For the more information, I use the Arduino Zero 1.8.5 version


text:
Arduino potentiometer example: what limits the current?
I have a question regarding potentiometer example:
https://www.arduino.cc/en/Tutorial/AnalogReadSerial

If I turn the potentiometer to the marginal position and have 5V at A0 (and almost zero resistance at the pot), what limits the current flowing through the circuit?

A0 input is high impedance, so very little current is flowing into A0. The value is so small that you can simplify that it flows only from +5V through the potentiometer to GND.
For some applications, when you are measuring high-impedance sources (a source that can deliver very little current) this simplification may not be correct.
You can find more detailed explaination in Atmel application note:
http://www.atmel.com/images/atmel-8456-8-and-32-bit-avr-microcontrollers-avr127-understanding-adc-parameters_application-note.pdf

Sorry for maybe a stupid question, but if the current flows through the pot with close to zero resistance from +5V to GND, isn't I short-circuting an Adruino that way?

Resistance between +5V to GND is rather high and equal to nominal potentiometer resistance. It depends what pot you've choosen. Check it with a meter or check for value printent on the case. If it haven't smoked yet, it must be high enough. :-)
Potentiometer works as a voltage divider with current flowing mainly through Z1 and Z2: https://en.wikipedia.org/wiki/Voltage_divider

Oh, got it finally! Resistance between +5V and ground is always 10 kOms, but resistance between +5V and OUT can vary from 0 Ohms to 10 kOhms.

Exactly. Now, the important thing is that the source impedance will vary. If you swipe the potentiometer to +5V, source impedance will be close to 0 (low Z1, high Z2). If you turn it to let's say, 0.1V, the source impedance will be close to 10k (high Z1, low Z2). This will start being an issue if you use high-resistance potentiometers (100s kiloohms), as the source will become to weak for the ADC, resulting in errors. We use buffers and signal conditioning circuits to mitigate those issues.

Assuming A0 is set to input then it is a high-impedance input. That is, the input has a high resistance, and only consumes enough current to "sample" the voltage.

Please, take no offence for giving an accepted answer to IOB Toolkit Team. I suppose it's in the best interest for community to distribute the rep-wealth evenly among its members.

I'm not offended. They typed their answer while I was typing mine. By the time I pressed "Submit" their answer was there. I agree about distributing rep, BTW. :)


text:
Can you drive a stepper motor without the L293D
Can you drive a stepper motor without L293D.
Don't awnser without giving explanations or saying it will be cheaper to buy the L293D.
Thanks

yes, you can ... there are other stepper drivers available

Any (dual-) H-bridge will do. You can build your own H-bridge out of transistors. You could even use two relays. Or get some proper stepper drivers, as the L293D isn't really great for that purpose.

Depending on the type of stepper motor the answer can be "Yes" or "No".
There are two types of stepper motor: Unipolar and Bipolar.  Bipolar motors typically have 4 wires and require a H-bridge to drive them.
The L239D is a popular (and cheap), though inefficient, H-bridge that is commonly used. But it is possible to build your own H-bridge from discrete components. There are a lot of caveats and pitfalls when building your own H-bridge though, so people generally don't unless they have a specific requirement that isn't addressed by an integrated one. There are plenty of schematics and descriptions of operation online if you want to learn more about H-bridges.
There are also dedicated bipolar stepper drivers which are easier to work with: you just set the direction and give it a pulse to step in that direction. Much easier to program with, but can be more expensive. However these do tend to be more modern MOSFET based components which are far more efficient and dissipate less heat (or can handle more powerful motors in a similar size package).
Unipolar stepper motors, on the other hand, have more wires (typically 6) and are much simpler to drive. All you need for these is a transistor per coil (typically 4 coils connected as pairs) and you just need to activate them in the right sequence.
The ULN2003 is a popular integrated chip for driving unipolar stepper motors. It's just a bunch of transistors in a single package that is easier to wire up than discrete transistors, though there is no reason why you couldn't do it just with 4 discrete transistors. It's just simpler and tidier to use a single chip.
There are plenty of demonstrations and tutorials online describing driving a unipolar stepper motor with the ULN2003.


text:
How to make "IF "Temperature exceeds" logic to work in same arduino code
I have the below code working from https://www.youtube.com/watch?v=Y30iEOxl1To - to receive temperature & humidity as an sms when i give a missed call to a specific number (sim on the gsm shield)
The above code is like on demand sms. I also want to alter this code so it can automatically send me another sms if the temperature exceeds a threshold.
Please help.
Below is the code...
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

void loop()
{
    float humidity, temperature;
    String smsText ="";
    if(temperature>29)
    {
        switch (call.CallStatus())
        {
            case CALL_NONE: // Nothing is happening
                break;

            case CALL_INCOM_VOICE : // Yes! Someone is calling us
                Serial.println("RECEIVING CALL");
                call.HangUp();
                delay(1000);
                humidity = dht.readHumidity();
                temperature = dht.readTemperature();
                delay(1000);
                smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
                smsText.toCharArray(sms_text,160);
                //Serial.println(smsText);
                sms.SendSMS("+91**********",sms_text);
                break;

            case CALL_COMM_LINE_BUSY:  // In this case the call would be established
                Serial.println("TALKING. Line busy.");
                break;
        }
        delay(1000);
    }
}

The code below will check if the temperature goes above 29 degrees. It also check whether the temperature was below 29 previously, to prevent it from sending an SMS every second, for as long as it's above 29 degrees C.
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

float previousTemperature = 0;
void loop()
{
    float humidity, temperature;
    humidity = dht.readHumidity();
    temperature = dht.readTemperature();
    delay(1000);

    // check if temperature has raised to above 29 degrees
    if(temperature>29 && previousTemperature<=29)
    {
        sendSMS(temperature, humidity);
    }
    previousTemperature = temperature;

    // check for incomming call
    switch (call.CallStatus())
    {
        case CALL_NONE: // Nothing is happening
            break;

        case CALL_INCOM_VOICE : // Yes! Someone is calling us
            Serial.println("RECEIVING CALL");
            call.HangUp();
            delay(1000);
            sendSMS(temperature, humidity);
            break;

        case CALL_COMM_LINE_BUSY:  // In this case the call would be established
            Serial.println("TALKING. Line busy.");
            break;
    }

    delay(1000);
}

void sendSMS(float temperature, float humidity)
{
    String smsText ="";
    smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
    smsText.toCharArray(sms_text,160);
    //Serial.println(smsText);
    sms.SendSMS("+91**********",sms_text);
}

You are awesome :-)

Thank you. Just make sure to mark this answer as accepted, in return.

I get this error now when compiling the same code in ARDUINO IDE
/Users/administrator/Documents/GSM_Call_Receive/GSM_Call_Receive.ino: In function 'void loop()':
GSM_Call_Receive:42: error: 'sendSMS' was not declared in this scope
sendSMS(temperature, humidity);
^
GSM_Call_Receive:56: error: 'sendSMS' was not declared in this scope
sendSMS(temperature, humidity);
^
exit status 1
'sendSMS' was not declared in this scope

That’s not how it works!

well i had the void sms part before the loop function and it started working

how do we keep the existing code and also include a logic which sends the temperature to a phone number that is not configured in the code.

You should create a new question.

My bad, i am not good at posting. Let me create a new question

Kindly help here
https://arduino.stackexchange.com/questions/51768/how-to-get-temperature-sms-to-any-calling-number

posted a new question

Please stop bugging me!

Sorry. Will not disturb you on this again.


text:
OLED with arduino?
I recently bought a 0.96" Serial OLED Screen. I am not very experienced with this. I'm trying to display some text with the Arduino Uno. I installed the adafruit SSD1306 and GFX libraries but no luck. I've looked for tutorials for similar screens, but my screen has extra pins that others don't.
Mine has:
CS DC RST D1 D0 VCC GND,
others only have 4.
I don't know what each pin should be connected to. Does any one know how to get this to work? Is there a different library that I could use with this screen?

Yes, certain OLED screens do have different pinouts. For yours, the following would be your OLED's pinouts.
OLED ---- Arduino

D0-----------10

D1-----------9

RST----------13

DC-----------11

VCC----------5V

GND----------GND

The CS pin does not need to be plugged in.
As for the code, you can use this include from Smart Prototyping as an extra file, then have some simple code in your loop portion:
void loop()
{

LED_P8x16Str(23,0,"here is");

LED_P8x16Str(40,2,"example");

LED_P8x16Str(20,4,"text");

}

No problem! Glad I could help!


text:
Sending uint16_t over I2C
How do you transmit and read a uint16_t over I2C?
I'm trying to read two uint16_t values from a slave device, and I'm seeing nonsensical readings.
This is the code on my slave Arduino Uno:
#include <Wire.h>

void send_wire_int(uint16_t num){

    // Send low byte
    Wire.write((uint8_t)num);

    // Send high byte
    num >>= 8;
    Wire.write((uint8_t)num);
}

// This is called from the I2C host.
void I2C_Send()
{

    //  send_wire_int(acount_abs);// Send encoder A count.
    //  send_wire_int(bcount_abs);// Send encoder B count.

    send_wire_int(0);
    send_wire_int(0);

}

void setup(){

    Wire.begin(30);                                                        // initialize I²C library and set slave address
    Wire.onRequest(I2C_Send);                                                   // define I²C slave transmit ISR

    Wire.flush();
    Wire.setTimeout(1000L);

}

void loop(){
    //stuff
}

All it does is wait for the master to request data. Originally, it was sending the values of two registers back, but these values were also garbled or non-changing, so I changed it to just send back 0s but I still get the identical garbled values.
This is the code on my master Arduino Uno:
#include <Wire.h>

uint16_t receive_wire_int(){

    while(Wire.available() < 1){}

    // Read low byte into rxnum
    uint16_t rxnum = Wire.read();

    while(Wire.available() < 1){}

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    return rxnum;
}

void setup() {
    Wire.begin();        // join i2c bus (address optional for master)
    Wire.setTimeout(1000L);
    Serial.begin(9600);  // start serial for output
}

void loop() {
    Serial.println("Requesting data..."); Serial.flush();

    Wire.requestFrom(30, 4);

    uint16_t acount = receive_wire_int();
    uint16_t bcount = receive_wire_int();

    Serial.println(String("acount:")+String(acount)+String(" bcount:")+String(bcount));

    delay(500);
}

As you can see, it simply requests the two uint16_t values in 4 bytes, and then prints them to the Serial (my laptop's terminal).
The output I'm seeing is:
acount:65280 bcount:65535

when I would expect:
acount:0 bcount:0

What I am I doing wrong?

What is the I2C clock rate on the master? You set it on the slave but not the master device.

Seems like all the calls to Wire.read(), save for the first, return -1, which becomes 0xffff when cast to uint16_t. Could you check for this condition?

Do the two Arduinos share a common ground?

@Andrew, The clock speeds are both the default/standard 100k.

@EdgarBonet, You're correct that read() returns -1 if nothing is received, but why would that only be happening for 2 of the 4 bytes?

@Matt, Yes, the I2C connection includes the SCL/SDA pins as well as Vcc/Gnd.

@Cerin - Had to check I assume you have pull up resistors too.  I think the read function will return -1 if there is no data.  Which is strange because the available function says there is 4 bytes of data.  What happens if the 1ms timeout expires?  Can you make the timeout stupidly large?  You are getting -1 for 3 bytes not 2.  The second byte (acount MSB is also -1).  Should there be a Wire.available() call in your read function to wait for the second byte to become available?

@Matt, Yeah, it looks like maybe only one byte is making it over, and the other read() calls are returning -1. I tried changing the timeout to 1000ms, but that had no effect. I also changed the reads to wait for each byte individually, but that also had no effect.

@Cerin - Have you looked at the write function in the same way?  would adding a delay statement between the writes help?  Does Write.write() return a value, is it possible that you are only writing one byte of data?

So I've just tested your code and apparently you have to send all data at once. After some research: it sends characters into the function twi_transmit and this function just fills the buffer and actual data are sent asynchronously. So, if you are fast enough, you will overwrite the buffer with another bytes and it's still like you have only 1 character to send.
For example this works (AVRs are little endian):
#include <Wire.h>

// This is called from the I2C host.
void I2C_Send()
{
    uint16_t   uints[2] = {0xDEAD,0xBEEF};

    Wire.write((uint8_t*) uints, 4);
}

void setup(){
    Wire.begin(30);  // initialize I²C library and set slave address
    Wire.onRequest(I2C_Send); // define I²C slave transmit ISR

    Wire.flush();
    Wire.setTimeout(1000L);
}

void loop(){
    //stuff
}

And receiver with HEX prints:
#include <Wire.h>

uint16_t receive_wire_int(){

    while(Wire.available() < 1){}

    // Read low byte into rxnum
    uint16_t rxnum = Wire.read();

    while(Wire.available() < 1){}

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    return rxnum;
}

void setup() {
    Wire.begin();        // join i2c bus (address optional for master)
    Wire.setTimeout(1000L);
    Serial.begin(9600);  // start serial for output
}

void loop() {
    Serial.println("Requesting data..."); Serial.flush();

    Wire.requestFrom(30, 4);

    uint16_t acount = receive_wire_int();
    uint16_t bcount = receive_wire_int();

    Serial.print("acount: 0x");
    Serial.print(acount,HEX);
    Serial.print("  bcount: 0x");
    Serial.println(bcount,HEX);

    delay(500);
}

The problem is that I'm using the wrong type of write() in my slave. As this blog explains, there are two overloaded write() methods in the Wire library. One that accepts a single byte, and another that accepts a byte array. I was sending each byte separately, which doesn't guarantee they'll be received together.
It works if I rewrite my slave's to:
void I2C_Send()
{
  byte myArray[4];

  myArray[0] = 0;
  myArray[1] = 0;
  myArray[2] = 0;
  myArray[3] = 0;

  Wire.write(myArray, 4);

}


text:
Unable to upload code to Leonardo
I was using Arduino-Makefile to upload code to a Leonardo via its standard make upload. However, it became "stuck" and unresponsive, as Leonardo's sometimes do. I tried power cycling it, and unplugging the USB cable, but nothing worked. So I tried re-burning the bootloader via an AVRISP MkII programmer and the Arduino 1.8.2 IDE, but that only made things worse.
It somehow uploaded a simple "blink" program, but now the it's completely unable to be programmed via USB. When I run make upload, or use the Arduino IDE's "upload" button, the Leonoardo's status LED begins blinking rapidly and its /dev/ttyACM0 device disappears permanently. I have to power-cycle it to make the device reappear, but the upload still fails, with the error:
/usr/share/arduino/bin/ard-reset-arduino --caterina  /dev/ttyACM0
make[1]: Leaving directory '/usr/local/myproject/main'
make do_upload
make[1]: Entering directory '/usr/local/myproject/main'
/usr/share/arduino/hardware/tools/avr/bin/avrdude -v -p atmega32u4 -C /usr/share/arduino/hardware/tools/avr/etc/avrdude.conf -D -c avr109 -b 57600 -P /dev/ttyACM0 \
        -U flash:w:build-leonardo/main.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/chris/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
    Software Version = .; Hardware Version = �.
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

If I manually run:
/usr/share/arduino/bin/ard-reset-arduino --caterina  /dev/ttyACM0

or upload via the Arduino IDE, it makes the Leonardo disappear from USB, and blink rapidly. Pressing the reset button does nothing. I have to manually unplug its USB cable to fix it.
I can program it still using the AVRISP MkII programmer...but obviously that's a huge inconvenience since it takes about 5 minutes just to upload the sample blink sketch, and even then it requires that I first power off the Leonardo, disconnect the programmer, and then power on. For development, where I might need to make dozens of revisions, this turnout is far too slow.
Why am I unable to program the Leonardo via avrdude and USB?

I need to press the Leonardo's "RESET" button to get out of this state (it will always fail after the first flash failure). It works best pressing the "RESET" button when the Arduino log window shows the lines with "PORTS ..." (for example, "PORTS {/dev/ttyACM1, } / {/dev/ttyACM1, } => {}").

Using some examples and similar questions, such as this one and this one, I fixed udev rules for the AVRISP MkII programmer, then I manually reflashed the Leonardo's bootloader with with the MkII by running:
avrdude -c avrispmkii -p m32u4 -P usb -B 8 -u -e -U lock:w:0x3F:m -v
avrdude -c avrispmkii -p m32u4 -P usb -v
avrdude -c avrispmkii -p m32u4 -P usb -u -U efuse:w:0xcb:m -v
avrdude -c avrispmkii -p m32u4 -P usb -u -U hfuse:w:0xd8:m -v
avrdude -c avrispmkii -p m32u4 -P usb -u -U lfuse:w:0xFF:m -v
avrdude -c avrispmkii -p m32u4 -P usb -U flash:w:/usr/share/arduino/hardware/arduino/avr/bootloaders/caterina/Leonardo-prod-firmware-2012-12-10.hex -v
avrdude -c avrispmkii -p m32u4 -P usb -U lock:w:0x0F:m -v

I'm not sure if the first and last command to write the lock bytes were necessary, since they returned the verification error; content mismatch error, but they didn't seem to break anything either.
Oddly, this ran in seconds, whereas the Arduino IDE took almost 5 minutes to burn the bootloader. So I suspect there's a bug in the Arduino IDE that burns an incorrect or corrupted bootloader.
After running this, ard-reset-arduino works correctly, and make upload can successfully upload a sketch again.
On a side note, I'm not 100% sure if Leonardo-prod-firmware-2012-12-10.hex was the correct bootloader to use. Again, I just made an educated guess based on naming. I'd read that the Leonardo uses the "caterina" bootloader, and the directory /usr/share/arduino/hardware/arduino/avr/bootloaders/caterina contained several .hex files, only three of which contained "Leonardo" in the name:
Caterina-Leonardo.hex
Leonardo-prod-firmware-2012-04-26.hex
Leonardo-prod-firmware-2012-12-10.hex

It seemed logical to not use Leonardo-prod-firmware-2012-04-26.hex, since that was likely an old and obsolete bootloader based on the date. That left Caterina-Leonardo.hex or Leonardo-prod-firmware-2012-12-10.hex. Unfortunately, checking the commit logs shows they're exactly the same age. In my experience, prod tends to mean the final or production product, so I decided to try that one first and it worked. If anyone knows what Caterina-Leonardo.hex is for and how it differs from the others, please tell me. I don't want to risk breaking my Leonardo again experimenting with this.
The only issue I'm having now is that after I upload my sketch, with uses ROS and about 49% of the Arduino's memory, I again can no longer upload new sketches to it. I'm assuming the sketch's use of the Serial port is somehow stopping ard-reset-arduino from properly resetting it`. However, I the Arduino IDE is still able to upload sketches, so as a clumsy workaround, I can use that to upload the "blink" sketch, afterwhich then I can upload my own revised sketch.

If you believe this has fixed your issue please accept your own answer. Thanks!


text:
DS3231 RTC not working with ESP32
I am using ESP-32-WROOM-32 with a RTC DS3231 module. I have connected SDA & SCL pins of RTC DS3231 with ESP32 D22 and D23 pins. Also, the VCC of RTC is connected to 3V3 of ESP32 and the GND of RTC is also connected to GND of ESP32  .RTC module is having attached battery also.
Following is the code:
#include <Wire.h> // for I2C with RTC module
#include "RTClib.h" //to show time

RTC_DS3231 rtc;

void Scanner ()
{
  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin(22,23);
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);          // Begin I2C transmission Address (i)
    if (Wire.endTransmission () == 0)  // Receive 0 = success (ACK response)
    {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);     // PCF8574 7 bit address
      Serial.println (")");
      count++;
    }
  }
  Serial.print ("Found ");
  Serial.print (count, DEC);        // numbers of devices
  Serial.println (" device(s).");
}
void setup()
{
    // put your setup code here, to run once:
    Wire.begin(22,23);
    //Wire.begin();
    Serial.begin(115200);
         while(!Serial);

       ////////////////////////////////////

    ////////////////////////////////////////

    while (!rtc.begin())
    {
        Serial.println("Couldn't find RTC");
        Scanner();
        //Serial.println(DS3231_REG_STATUS);
        //        while (1)
        //        {
        //                  Serial.println("Couldn't find RTC");
        //
        //        }

        ;
    }
    Serial.println("Finally");
    // In setup function, we will call a function rtc.adjust(DateTime(__DATE__, __TIME__)) which will set the time according to our PC time.
    rtc.adjust(DateTime(__DATE__, __TIME__));
}
void loop()
{

    DateTime curr_time_obj = rtc.now();
    int day = curr_time_obj.day();
    int month = curr_time_obj.month();
    int year = curr_time_obj.year();
    int week_day = curr_time_obj.dayOfTheWeek();
    int sec = curr_time_obj.second();
    int hr = curr_time_obj.hour();
    int minute = curr_time_obj.minute();

    Serial.print("hour is ");
    Serial.println(hr);
    Serial.print("min is ");
    Serial.println(minute);
    Serial.print("secs is ");
    Serial.println(sec);
    Serial.println("############################");
    delay(5000);
}

Following is the output:

Some of the images of the circuit can be found here: https://drive.google.com/drive/folders/1fhM7o_aZCGh88OBDcypVLqhKhizhXnNd?usp=sharing
I would appreciate any help to resolve this issue.
Thanks

The I²C address of the DS3231 is 0x68, not 0x57. Are you sure that's the chip you have?

Yes, the chip says DS3231M to be specific.

Please link to the exact module that you are using. It's impossible to make out what it is from those pictures.

https://robu.in/product/ds3231-rtc-module-precise-real-time-clock-i2c-at24c32/?gclid=CjwKCAjwhOyJBhA4EiwAEcJdceN-yJB_Uxzz_EervOkpZRWXgECrQZJ_zWbnB5o3OxVbhG_Ki_f69RoCQKIQAvD_BwE @Majenko

That module contains both an RTC and an EEPROM.  The device 0x57 looks to be the EEPROM. There is no schematic for the module, but there are two sets of I2C pins. It could be that the two chips are wired separately and you have to choose the right I2C pins for which chip you wish to use. Try switching to the other SCL/SDA pins.

@Majenko I have this module and I use the RTC over the 6 pin header

I use this module with the DS3231 library by  Andrew Wickert. it is in the Library Manager

Warning
These modules normally come with a 200Ω resistor soldered next to the IN4148 Zener diode, as you can see in the image below.
ds3231 module problem fix
The resistor and diode form a simple charging circuit designed for use with LIR2032 rechargeable batteries.
Be aware that some DS3231 modules come with a non-rechargeable CR2032 battery. If this is the case, you must remove the resistor because attempting to charge a non-rechargeable battery can cause serious damage.

Blockquote

I resolved the rebooting problem extract the 200 ohms resistor

That battery will not charge with a 3V3 system such as the ESP devices. The diode should isolate it so you need to do nothing. If you power it with 5V then you need to modify it for a non rechargeable battery.


text:
Arduino MPU error
This is my code -
// Basic demo for accelerometer readings from Adafruit MPU6050

#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>

Adafruit_MPU6050 mpu;

void setup(void) {
  Serial.begin(115200);
  while (!Serial)
    delay(10); // will pause Zero, Leonardo, etc until serial console opens

  Serial.println("Adafruit MPU6050 test!");

  // Try to initialize!
  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    while (1) {
      delay(10);
    }
  }
  Serial.println("MPU6050 Found!");

  mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
  Serial.print("Accelerometer range set to: ");
  switch (mpu.getAccelerometerRange()) {
  case MPU6050_RANGE_2_G:
    Serial.println("+-2G");
    break;
  case MPU6050_RANGE_4_G:
    Serial.println("+-4G");
    break;
  case MPU6050_RANGE_8_G:
    Serial.println("+-8G");
    break;
  case MPU6050_RANGE_16_G:
    Serial.println("+-16G");
    break;
  }
  mpu.setGyroRange(MPU6050_RANGE_500_DEG);
  Serial.print("Gyro range set to: ");
  switch (mpu.getGyroRange()) {
  case MPU6050_RANGE_250_DEG:
    Serial.println("+- 250 deg/s");
    break;
  case MPU6050_RANGE_500_DEG:
    Serial.println("+- 500 deg/s");
    break;
  case MPU6050_RANGE_1000_DEG:
    Serial.println("+- 1000 deg/s");
    break;
  case MPU6050_RANGE_2000_DEG:
    Serial.println("+- 2000 deg/s");
    break;
  }

  mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
  Serial.print("Filter bandwidth set to: ");
  switch (mpu.getFilterBandwidth()) {
  case MPU6050_BAND_260_HZ:
    Serial.println("260 Hz");
    break;
  case MPU6050_BAND_184_HZ:
    Serial.println("184 Hz");
    break;
  case MPU6050_BAND_94_HZ:
    Serial.println("94 Hz");
    break;
  case MPU6050_BAND_44_HZ:
    Serial.println("44 Hz");
    break;
  case MPU6050_BAND_21_HZ:
    Serial.println("21 Hz");
    break;
  case MPU6050_BAND_10_HZ:
    Serial.println("10 Hz");
    break;
  case MPU6050_BAND_5_HZ:
    Serial.println("5 Hz");
    break;
  }

  Serial.println("");
  delay(100);
}

void loop() {

  /* Get new sensor events with the readings */
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  /* Print out the values */
  Serial.print("Acceleration X: ");
  Serial.print(a.acceleration.x);
  Serial.print(", Y: ");
  Serial.print(a.acceleration.y);
  Serial.print(", Z: ");
  Serial.print(a.acceleration.z);
  Serial.println(" m/s^2");

  Serial.print("Rotation X: ");
  Serial.print(g.gyro.x);
  Serial.print(", Y: ");
  Serial.print(g.gyro.y);
  Serial.print(", Z: ");
  Serial.print(g.gyro.z);
  Serial.println(" rad/s");

  Serial.print("Temperature: ");
  Serial.print(temp.temperature);
  Serial.println(" degC");

  Serial.println("");
  delay(500);
}

and this is my error-
Adafruit MPU6050 test!
Failed to find MPU6050 chip
Adafruit MPU6050 test!
Failed to find MPU6050 chip

wires are connected properly

Please try the I2C Scanner sketch. That will show you if any device is found on the bus and which address it has. When I remember correctly the MPU6050 also has address pins to change the address. Maybe your MPU has a different address, than the library uses by default (seems to be 0x68 according to the library code on github)

If I had a nickel for every time I thought the wires were connected properly...

the address is 0x68 I checked it

Knowing the address, there's not a lot in the begin() function that can make it fail that isn't ultimately a wiring problem.  Determining (e.g. via Serial.println) which of these return statements is being executed may be of some use.

Have you checked with the I2C scanner sketch? You didn't specify that. I mentioned that sketch because it also confirms, that the I2C bus is working. And please share a schematic of your wiring

hey @timemage
https://jpst.it/2xPxh
This code is working but I want to use the other code, if it was a wiring problem then the code I mentioned now wouldn't work right? that's why I said the wiring is correct.                                                                                by the way, thank yout for helping me I really appreciate it.

hi @chrisl I checked with the i2c scanner the and it says the address is 0x68, by the way, thank you for helping me I really appreciate it.

I haven't looked at your other code and probably won't for a while.  But in short, no.  In particular the speed of the bus is under control of code and crappier wiring (the bus lines themselves and pullup resistors) support slower speeds.

Mhh, your code is just the basic_readings example from the Adafruit_MPU6050 library, so I would think that it is correct (the library is used by so many others without problems, so I don't think the library is at fault here). For me that doesn't leave much to analyze here. At that point I would normally check the wiring (and try pullup resistors like 4.7kOhm on the I2C lines, if not already done). I now that it worked with your other code, which is not using the library, but I cannot thing of anything else here.

If you have a logic analyzer (great tool, really cheap as USB device, like 10 bucks) you can monitor the I2C lines and look, what actually gets send and responded on the bus.