text:
Delay workaround needed for RTC and LCD-shield buttons
Following configuration:

Arduino UNO R3
Real Time Clock DS1307RTC
LCD1602 Shield with buttons
Photo resistor
DHT11 (Temp & Humidity Sensor)

I need the function delay(1000) to display the seconds properly from the RTC to the LCD.
But, that way I always have to keep the buttons pressed for up to 1 second until they react.
How can I workaround or solve this problem?
Idea 1: Multitasking would come in handy here :-) pseudocode:
task 1: listen for LCD buttons
task 2: display seconds with a delay of 1000ms

But there isn’t a way Arduino could multitask, isn’t it?
Idea 2: As far as I saw in the header files for the RTC, the smallest readable unit is seconds. Otherwise I could have used something like a millisecond reader in a while condition to listen for the buttons; pseudocode:
while (RTC-millisecond < 1000ms) {
    // listen for buttons
    // so a second passes, which gives the RTC time to display the seconds values
}

-
EDIT
updated code, thanks to @NickGammon and Gerben:
#include <LiquidCrystal.h>
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <DHT.h>

// initialize the library with the numbers of the interface pins
//                RS  E  D4 D5 D6 D7 (maybe wrong order)
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// pins on which the sensor is connected
#define DHTPIN A1
#define PHOTOPIN A2

// initialize DHT sensor
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
//#define btnRIGHT  0
//#define btnUP     1
//#define btnDOWN   2
//#define btnLEFT   3
//#define btnSELECT 4
//#define btnNONE   5

// FSM
unsigned long previousMillis1 = 0;
unsigned long previousMillis2 = 0;
const long interval = 3000;

// prototypes
void print2digits(int number);
int read_LCD_buttons();

void setup() {
  // open a serial connection to display values on PC
  Serial.begin(9600);

  // set up the number of columns and rows on the LCD
  lcd.begin(16, 2);

  // start DHT sensor
  dht.begin();
}

void loop() {
  // set variable from struct tmElements_t
  tmElements_t tm;

/********* Reading from sensors *********/
  /*** DHT sensor ***/
  // Reading temp or RH takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float humid = dht.readHumidity();
  float tempC = dht.readTemperature();
  // Check if any reads failed and exit early (to try again).
  if (isnan(humid) || isnan(tempC)) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("DHT reading failed!");
    Serial.println("DHT reading failed!");
    return;
  }
  // Compute heat index in Celsius (isFahreheit = false)
  float hiC = dht.computeHeatIndex(tempC, humid, false);

  /*** Photo resistor ***/
  int lightReading = analogRead(PHOTOPIN);

/********* Print to PC over serial connection *********/
  // ...

/********* Print values to LCD *********/
  /* --- first line on LCD --- */
  /*** RTC ***/
  // set the cursor to LCD column 4, line 0 to center the clock
  lcd.setCursor(4, 0);

  // starts RTC reading and checks if it's working
  if (RTC.read(tm)) {
    static byte oldSecond = 60; // 60, because there is no 60'th second in a clock
    // display only if time changes
    if (tm.Second != oldSecond) {
      oldSecond = tm.Second;
      print2digits(tm.Hour);
      lcd.print(':');
      print2digits(tm.Minute);
      lcd.print(':');
      print2digits(tm.Second);
    }
  }
  else {
    lcd.clear();
    lcd.setCursor(0, 0);
    if (RTC.chipPresent()) {
      lcd.print("Please run SetTime function");
    } else {
      lcd.print("DS1307 read error!");
    }
    delay(9000);
  }

  /* --- second line on LCD according to button --- */
  lcd_key = ((lcd_key + read_LCD_buttons()) %3);  // call button function, modulo 3 to cycle through
    /** // Test buttons:
    lcd.setCursor(1, 1);
    lcd.print("lcd var:");
    lcd.print(lcd_key); */

  unsigned long currentMillis = millis(); // FSM used for displaying DHT and photo values without flikering

  switch (lcd_key) {
    case 0:
      /*** Weekday and Date ***/
      // display only if day changed
      static byte oldDay = 99;
      if (tm.Day != oldDay) {
        oldDay = tm.Day;
        lcd.setCursor(0, 1);
        lcd.print("                "); // 16 spaces to clear second line before printing
        lcd.setCursor(0, 1);
        //lcd.print(dayShortStr((weekday() + 1) % 7 )); // (day+1)%7 calculation for Swiss layout
        lcd.print(tm.Wday); // TEST
        lcd.print(weekday()); // TEST
        lcd.print(", ");
        print2digits(tm.Day);
        lcd.print('.');
        print2digits(tm.Month);
        lcd.print('.');
        lcd.print(tmYearToCalendar(tm.Year));
      }
      break;

    case 1:
      /*** DHT Sensor ***/
      if (currentMillis - previousMillis1 >= interval) {
        previousMillis1 = currentMillis;
        lcd.setCursor(0, 1);
        lcd.print("                "); // 16 spaces to clear second line before printing
        lcd.setCursor(1, 1);
        lcd.print(hiC);
        lcd.print("*C ");
        lcd.setCursor(10, 1);
        lcd.print(humid);
        lcd.setCursor(12, 1);
        lcd.print("%RH ");
      }
      break;

    case 2:
      /*** Photo resistor ***/
      if (currentMillis - previousMillis2 >= interval) {
        previousMillis2 = currentMillis;
        lcd.setCursor(0, 1);
        lcd.print("                "); // 16 spaces to clear second line before printing
        lcd.setCursor(0, 1);
        lcd.print("Light ");
        lcd.setCursor(6, 1);
        lcd.print(lightReading);
      }
      break;
  }
}

// used to print 2 digits in the time values
void print2digits(int number) {
  if (number >= 0 && number < 10) {
    lcd.print('0');
  }
  lcd.print(number);
}

// read the buttons
int read_LCD_buttons() {
  adc_key_in = analogRead(0);
  //if (adc_key_in > 1000) return btnNONE; // 1st option since it will be the most likely result (speed reasons)
  //if (adc_key_in < 50)   return btnRIGHT;
  //if (adc_key_in < 195)  return btnUP; // replaced by below one
  if (adc_key_in < 195)  return 1; // my button up !
  //if (adc_key_in < 380)  return btnDOWN;
  //if (adc_key_in < 555)  return btnLEFT;
  //if (adc_key_in < 790)  return btnSELECT;
  //return btnNONE;  // when all others fail, return this...
  return 0;
}

Try leaving out the delay entirely and see what happens. You'd be surprised.

I tried that. The problem is, that seconds are then updated too frequently which makes the characters spin like crazy on the LCD. Also using a delay of 500 does not work properly: seconds aren't displayed smoothly.

The lcd flickers, because you are constantly updating it, but the time itself is shown correctly. That's what I was trying to show. Using delay(1000) would also give problems as the rest of the code also takes some time. So it's a bit like delay(1008). So every now and then the seconds will skip a number. What you could do it store the previous time in a variable, and only update the display is the new time is different from the time in the previous loop. That way you don't need the delay, and also don't get the flickering.

What @Gerben suggested is by far the simplest. Since you need a delay anyway to stop the flickering, and you have a clock, use that to get yourself a nice one-second delay. Only update the display if the time differs from the previous one. Testing the seconds only would probably do it, as the minutes aren't going to change without the seconds changing.

Gerben and Nick Gammon: Thanks for the answers, I'll try them out in the next few hours and then tackle an answer as solution. I like the FSM approach; But one Q about millis(): will it count until infinity and then overflow the variable after 50 days (long = 32bit = 4Billion ms = ca 50days)?

Yes. Millis will count to 4294967295 and will be 0 the next millis, starting all over.

I don't see where you followed my suggestion of only printing the time if it changed.

@NickGammon to be honest, I am not quite sure how to do it :-/ yet, I removed the code which displays the time to test your suggestion. So, no time/date was shown, but the buttons still remain laggy...

See my extra code at the bottom of my reply.

while (currentMillis - previousMillis >= interval) - You seem to have built in a 1-second delay before reading a button. Of course it will be laggy.

  // clean up screen before printing a new reply
  lcd.clear();

  /* --- first line on LCD --- */
  /*** RTC ***/
  // set the cursor to LCD column 4, line 0 to center the clock
  lcd.setCursor(4, 0);

Straight away, that will cause flicker, right? For a few milliseconds the screen will go blank, and then get gradually redrawn. Why not omit the clear? You could put it in if you are changing display types (eg. from date to temperature) but you don't need to clear the screen every time. So:

Don't call delay()
Don't clear the screen unless changing to displaying a different type of thing
Only update the display at all if the new number (or time, or temperature, etc.) is different from what you just displayed.
Just do the setCursor() to position the cursor and overwrite the information there previously.
Preferably follow by a space or two in case a large number is replaced by a smaller one.

Side-benefit: Since you have removed the delay, your project will now be much more responsive to key presses. Win win!

References

State machines
How to do multiple things at once ... like cook bacon and eggs

I am not quite sure how to do it

 if (RTC.read(tm))
  {
  static byte oldSecond = 99;
  // display if time changes
  if (tm.Second != oldSecond)
    {
    oldSecond = tm.Second;
    print2digits(tm.Hour);
    lcd.print(':');
    print2digits(tm.Minute);
    lcd.print(':');
    print2digits(tm.Second);
    }
  }

Similarly further down where you display the date / sensor.

Due to your help, nothing flickers anymore. Hope you're still patient with me :-) I updated the code above, please have a look. Strange thing happened now: Weekday only shows NULL or Error, after implementing the change-check. When removing the check, it works again. Problem 2: without delay the buttons are now too fast :-) It's a LCD Shield with buttons, which when pressed constantly send a signal. Giving a delay of between 100 or 300ms doesn't help. Tested in a separate code, shows that my switch case is spinning; though here in this code the button works intermittend. I'm on since hours :-/

For the weekday issue, I don't see where you are providing the time to the weekday function. As for the buttons, now it is fast, you are reading them too quickly. One simple thing is to look for a state change. That is, is the new button different to the old button? So for example, if it is btnRIGHT but was btnNONE then you have a state change. More information: Switches tutorial.

You need to learn a different way of programming.
Two things you need to understand:

Non-blocking code.  Read and understand the BlinkWithoutDelay example sketch (in the Arduino IDE's File -> Examples menu)
Finite State Machines.  Stop thinking purely linear, and start thinking about the different states your program can be in at any one time.

Once you have those cracked you'll be an Elite Arduino Programmer (EAP™).

EAP sounds great :-) BlinkWithoutDelay: will check it out immediately. Regarding point 2. Could you explain "different states" a bit more detailed?

http://hacking.majenko.co.uk/finite-state-machine

See How to do multiple things at once and State machines.


text:
Pi3 + ATmega644P: How do I establish a data connection with 1 analog input and 1 digital output left on the AT?
I have no UARTs left on the ATmega and need to deliver 1 Byte of information from the pi using 1 analog input. I2C is no option either.
I planned using the digital output to request an analog signal from the Pi, but it does not seem to have a DAC.
Is it possible to properly translate/read a PWM signal with the atmegas ADC?
Analyzing the PWM the 'usual' way would probably be too slow as I don't trust the pi to keep up with a high PWM frequency.
PINS left: PA0(ADC0|PCINT0), PD7(OC2A|PCINT31)
I should add that this is a rather large robotics project involving communication between 8 MCUs in it's current state and needs to be extended by a computer vision module(=pi), which is not compatible with the existing custom bus
Edit: This also is a real time system which has approximately ~1-2ms left in it's main loop(10ms period). The required data has to be present in time as it alters the robot's behaviour for this loop.

You can use SoftwareSerial to connect to a pi uart; otherwise upi can use a software serial communication using whatever protocol you want. I highly suggest you to avoid using analog signals, since these signals can't transfer reliably one byte... And PWM too is a bit too imprecise. Just remember to voltage translate the 3.3V to 5V (even if you actually could use the 3.3V output to communicate to the arduino, since it should accept voltages as low as 3V...

I'm sorry but your question isn't very clear.  Do you know about logic level shifters?  You could use that to convert 3.3. to 5v.  Also you might want to look into adding additional ports to both devices, but you are going to need to use I2C or SPI to do that.

Yes I do know about level converters, the problem is about generating an analog signal on the pi or using a different method to communicate with given pins.
I should add that this is a rather large robotics project involving communication between 8 MCUs in it's current state and needs to be extended by a computer vision module(=pi), which is not compatible with the existing custom bus

While there are various ways to do digital signalling on your remaining pin(s), depending on how locked in to your current setup you are, an approach that might make sense would be to see if you could convert an existing point-to-point serial link to a multi-party serial bus.  Basically, read up on RS485 and see if you can do something conceptually similar, without the differential transceivers, but rather using your existing low or high voltage connections simply by software-enabling the output driver of only transmitter at a time and writing some rules for deciding who gets to talk.

The exisintg i2c interface is used to debug and locked during normal operation to not interfere with already multiply used connections.
The second UART is exclusive to robot2robot bluetooth communication.
I already thought about hooking up another bt module to that, which was too slow as well

Perhaps you should move the bluetooth to the pi, use that serial channel for communciation between the pi and the atmega, and encapsulate relayed bluetooth messages on it, perhaps divided into small pieces to fit in between the realtime messages (though why the Arduino would be the appropriate consumer of the bluetooth data at all is a mystery).  This is a really a system engineering problem, not a narrow Arduino question in the scope of this site.  Your fear about interrupts is not entirely unfounded, but the concern is something that can be overcome with careful software design.

The solution was to hook up PA0 to GPIO18 of the pi with an RC-circuit inbetween.
GPIO18 features a hardware PWM output, which has to be set to mode 0 (non balanced, mark-space), because the balanced mode could not handle odd pwmRanges for some reason(it is badly documented).
This setup enables the atmega to read the pi's pulsed 0-3,3V output as analog input.
Pin initialization on Pi(using a python library):
import wiringpi2 as wiringpi

wiringpi.wiringPiSetupGpio()
wiringpi.pinMode(18, 2)
wiringpi.pwmSetMode(0)    #<- important part

Currently writing the Atmega side
    uint8_t     i = 0;
    uint32_t val  = 0;
    while(i<8)    //average 8 measures
    {
        i++;
        ADMUX   = 0 & 0x1f;    //select channel 0 (PA0)
        ADMUX |= (1<<5);       //set ADLAR bit ADCH > ADCL
        ADCSRA  = ADCSRA | (1 << ADSC) | (1 << ADIF);
        while (ADCSRA & (1<<ADSC));
        val = val + (ADCH);
    }
    return ((val)>>3);

Note that this reads a 10bit value on the channel and discards the least significant 2bit stored in ADCL as ADLAR is set to speed everything up.

You can start researching about one wire protocol here to see if can implement it given your situation.

I have read about that but a minimum of 1,5ms to transfer 1byte is far too slow (reset + presence + 2x(8bit at 60us))

You really should include your speed requirement in your problem statement.

In your edit to the question, you are mixing up transmission time with the processor's attention time required to receive the data.  They are by no means the same thing, unless you sit in a blocking loop watching the signal change, which would be a rather unwise implementation.  1.5 ms for data transmission sounds like it would actually fit your 10 ms loop time rather nicely.

It is difficult to accurately ask a question dependant on so many factors.
Timers that could be used to modulate the signal are used up.
The PD7 pin has a signal change interrupt, whose use could interrupt the main bus, crashing the system.

source: Stack Exchange

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

sort: votes


text:
Two MPU 9250 connected to one arduino (Code of the MPU6050 edited for MPU9250)
I have done a lot of tries to make my two IMU work with my arduino. I'm also done with many research about it and I found this code:
 // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
 // 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
 // Updates should (hopefully) always be available at
 //https://github.com/jrowberg/i2cdevlib
 //
// Changelog:
//     2011-10-07 - initial release

/* ============================================
 I2Cdev device library code is placed under the MIT license
 Copyright (c) 2011 Jeff Rowberg

 // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE   implementation
 // is used in I2Cdev.h
 #include "Wire.h"

 // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
 #include "I2Cdev.h"
 #include "MPU6050.h"

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68; (default for InvenSense evaluation board)
//AD0 high = 0x69;
MPU6050 accelgyro;
// accelgyroIC1.initialize();
//accelgyroIC2.initialize();
MPU6050 accelgyroIC1(0x69);
MPU6050 accelgyroIC2(0x68);

int16_t ax1, ay1, az1;
int16_t gx1, gy1, gz1;

int16_t ax2, ay2, az2;
int16_t gx2, gy2, gz2;

#define LED_PIN 13
bool blinkState = false;

void setup() {
// join I2C bus (I2Cdev library doesn't do this automatically)
Wire.begin();

// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(38400);

// initialize device
Serial.println("Initializing I2C devices...");
//accelgyro.initialize();
accelgyroIC1.initialize();
accelgyroIC2.initialize();

// verify connection
Serial.println("Testing device connections...");
Serial.println(accelgyroIC1.testConnection() ? "MPU6050 #1 connection successful" : "MPU6050 connection failed");
Serial.println(accelgyroIC2.testConnection() ? "MPU6050 #2 connection successful" : "MPU6050 connection failed");

// configure Arduino LED for
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
// read raw accel/gyro measurements from device
accelgyroIC1.getMotion6(&ax1, &ay1, &az1, &gx1, &gy1, &gz1);
accelgyroIC2.getMotion6(&ax2, &ay2, &az2, &gx2, &gy2, &gz2);

// these methods (and a few others) are also available
//accelgyro.getAcceleration(&ax, &ay, &az);
//accelgyro.getRotation(&gx, &gy, &gz);

// display tab-separated accel/gyro x/y/z values
Serial.println("MPU1:");      Serial.print("\t"    );     Serial.print("\t"      );
Serial.print(ax1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.print(ay1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.print(az1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.print(gx1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.print(gy1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.println(gz1);
delay(1000);

// display tab-separated accel/gyro x/y/z values
Serial.println("MPU2:");     Serial.print("\t"    );     Serial.print("\t"    );
Serial.print(ax2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.print(ay2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.print(az2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.print(gx2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.print(gy2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.println(gz2);
delay(1000);

// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
}

After running it, I'm wondering why the two MPU connections failed. Please see the attached image for the result I got.
And I guess that should be the probable reason why everytime I try to move the MPU1, the MPU2 varies like what is happening to the MPU1, and there are times that they get the same value.
I also even tried to edit the code I posted above, and here it goes...
 #include <MPU9250.h>

 // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
 // 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
 // Updates should (hopefully) always be available at
 //https://github.com/jrowberg/i2cdevlib
 //
 // Changelog:
 //     2011-10-07 - initial release

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
 // is used in I2Cdev.h
 #include "Wire.h"

 // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
 // for both classes must be in the include path of your project
 #include "I2Cdev.h"
 #include "MPU6050.h"

 // class default I2C address is 0x68
 // specific I2C addresses may be passed as a parameter here
  int AD0LOW= 0x68; //(default for InvenSense evaluation board)
  int AD0HIGH= 0x69;
  //MPU9250 accelgyro;
  int accelgyroIC1 ();
  int accelgyroIC2 ();
  //MPU9250 accelgyroIC1(0x68);
  //MPU9250 accelgyroIC2(0x69);

  int16_t ax1, ay1, az1;
  int16_t gx1, gy1, gz1;
  int16_t mx1, my1, mz1;

  int16_t ax2, ay2, az2;
  int16_t gx2, gy2, gz2;
  int16_t mx2, my2, mz2;

  #define LED_PIN 13
  bool blinkState = false;

  void setup() {
   // join I2C bus (I2Cdev library doesn't do this automatically)
   Wire.begin();
   Serial.begin(38400);

  // initialize device
   Serial.println("Initializing I2C devices...");
  //accelgyro.initialize();
  int accelgyroIC1();
  int accelgyroIC2();

   // verify connection
   Serial.println("Testing device connections...");
   //    Serial.println(accelgyroIC1.testConnection() ? "MPU9250 #1     connection successful" : "MPU9250 connection failed");
   //    Serial.println(accelgyroIC2.testConnection() ? "MPU9250 #2 connection successful" : "MPU9250 connection failed");

    // configure Arduino LED for
    pinMode(LED_PIN, OUTPUT);
    }

    void loop() {
   // read raw accel/gyro measurements from device
   //    accelgyroIC1.getMotion9(&ax1, &ay1, &az1, &gx1, &gy1, &gz1);
   //  accelgyroIC2.getMotion9(&ax2, &ay2, &az2, &gx2, &gy2, &gz2);

    accelgyroIC1.getMotion9(&ax1, &ay1, &az1, &gx1, &gy1, &gz1, &mx1, &my1, &mz1);
    accelgyroIC2.getMotion9(&ax2, &ay2, &az2, &gx2, &gy2, &gz2, &mx2, &my2, &mz2);

    // these methods (and a few others) are also available
    //accelgyro.getAcceleration(&ax, &ay, &az);
    //accelgyro.getRotation(&gx, &gy, &gz);

    // display tab-separated accel/gyro x/y/z values
    /*Serial.println("MPU1:");      Serial.print("\t"    );              Serial.print("\t"    );
   Serial.print(ax1);        Serial.print("\t"    );  Serial.print("\t"    );
   Serial.print(ay1);        Serial.print("\t"    );  Serial.print("\t"    );
   Serial.print(az1);        Serial.print("\t"    );  Serial.print("\t"    );
   Serial.print(gx1);        Serial.print("\t"    );  Serial.print("\t"    );
    Serial.print(gy1);        Serial.print("\t"    );  Serial.print("\t"    );
    Serial.println(gz1);
    delay(1000);

    // display tab-separated accel/gyro x/y/z values
     Serial.println("MPU2:");     Serial.print("\t"    );     Serial.print("\t"    );
    Serial.print(ax2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.print(ay2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.print(az2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.print(gx2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.print(gy2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.println(gz2);
    delay(1000);*/

    Serial.print("MPU1:");
    Serial.print(ax); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(ay); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(az); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(gx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(gy); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(gz); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(mx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(my); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.println(mz);

     Serial.print("MPU2:");
    Serial.print(ax); Serial.print("\t");   Serial.print("\t");     Serial.print("\t");
     Serial.print(ay); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(az); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(gx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(gy); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(gz); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(mx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(my); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
      Serial.println(mz);

     // blink LED to indicate activity
     blinkState = !blinkState;
     digitalWrite(LED_PIN, blinkState);
      }

And please see the error that it displayed: (please see attached image)

With a result of: (please see image attched)
Please help me with these. I'm getting confused with my codes that I should be using and how to edit them. Please guide me on how to put connections in between them..
Thank you...
...Thom
This is the error message I copied:
Arduino: 1.6.7 (Windows 8.1), Board: "Arduino Mega ADK"

C:\Users\Jasmin.Morales\Desktop\_2MPU_Practice\_2MPU_Practice.ino: In function 'void loop()':

_2MPU_Practice:70: error: request for member 'getMotion9' in 'accelgyroIC1', which is of non-class type 'int()'

   accelgyroIC1.getMotion9(&ax1, &ay1, &az1, &gx1, &gy1, &gz1, &mx1, &my1, &mz1);

                ^

_2MPU_Practice:71: error: request for member 'getMotion9' in 'accelgyroIC2', which is of non-class type 'int()'

   accelgyroIC2.getMotion9(&ax2, &ay2, &az2, &gx2, &gy2, &gz2, &mx2, &my2, &mz2);

                ^

_2MPU_Practice:100: error: 'ax' was not declared in this scope

     Serial.print(ax); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:101: error: 'ay' was not declared in this scope

     Serial.print(ay); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:102: error: 'az' was not declared in this scope

     Serial.print(az); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:103: error: 'gx' was not declared in this scope

     Serial.print(gx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:104: error: 'gy' was not declared in this scope

     Serial.print(gy); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:105: error: 'gz' was not declared in this scope

     Serial.print(gz); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:106: error: 'mx' was not declared in this scope

     Serial.print(mx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:107: error: 'my' was not declared in this scope

     Serial.print(my); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:108: error: 'mz' was not declared in this scope

     Serial.println(mz);

                    ^

exit status 1
request for member 'getMotion9' in 'accelgyroIC1', which is of non-class type 'int()'

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

Please copy and paste errors into the post, not a screenshot of the errors. At least for the last screenshot. There is even a button: "Copy error messages".

Please see the edited version. Thanks. :)

Please edit your post and format the messages using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

Serial.print("\t");   Serial.print("\t");   Serial.print("\t"); - how about: Serial.print("\t\t\t");

What was wrong with the initial code (before the edit)? Please describe the circuit, wiring, of the two MPUs. If you set the addresses correctly?

can u please post hardware connection? did you gnd INT pin.
did u enable AD0 pin in second IMU?

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

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


text:
Wrong data from DS18B20 temperature sensor after long power off
I have my Arduino Uno connected to the PC via USB when prototyping.  I am developing a thermometer with memory, using DS18B20 sensors.
When PC is shut down, there is no power on the USB and the Arduino is off. Sometimes, when my PC is turned off for several hours and then, when I turn it on, the Arduino is started, but it behaves "strange" - the program is showing buggy values on the display, looking like if there is some bug in the sketch. However, when I upload the sketch again, it works fine.
The buggy values are the averages for the run, computed simply by summing a float and dividing by int. What I see is e.g. instead of seeing something around 23.5 I see 85.1. The current values read from the sensor look OK (show 23.5 as expected), but I cannot tell for sure if perhaps some value read early might be wrong.
It is not easy to reproduce, I see it only sometimes, always when powering Arduino on after several hours without power.
My first idea is either the sketch got corrupted during the long power down, or variables are initialized wrong, and the sample sum / sample count is not zero.
However I though the sketches are uploaded into the Flash RAM, which should be non-volatile according to the docs. Is there something obvious I am missing, some explanation why is the sketch working differently after long power down?

Are you storing any values to EEPROM? The problem sounds odd. The brown out detector on the AVR is supposed to ensure a clean power off, meaning no unpredictable behaviour.

@user2973 No EEPROM. Moreover, I did not see the problem recently. I will watch the behaviour and will post if I learn anything new.

It sounds like the problematic variables should be properly cleared during the setup(). And or the sensor is not correctly working for an initial power up period.

@mpflaga Do you mean static variables are not reset when Arduino is reboot? Well, that would explain a lot ... I was probably programming PCs for too long.

@mpflaga "Global and static variables are guaranteed to be initialized to 0 by the C standard. avr-gcc does this by placing the appropriate code into section .init4"

They should be, cleared. I would print them and then clear them after a number of delays. To determine where the corruption is coming from.

It is not entirely out of the question that during boot, the PC could write garbage data to the Arduino - for example, as the Arduino uses what is really supposed to be a modem interface, the operating system might be trying to initialize it as such.

Can you clarify your question - "Sometimes, when my PC is turned off for several hours and then I turn it off" - do you mean turned off and then the pc is turned on, or turned on and then the pc is turned off?

Maxim DS18b20 data sheet, rev 042208, page 4, in a footnote to Table 1, says: *The power-on reset value of the temperature register is +85°C. Maybe a premature attempt to read?

There should be no difference between turning on your computer and plugging in a USB cable. The embedded devices typically plugged into a USB ports such as mice, keyboards, wireless adapters, hard drives, etc don't have their FLASH memory corrupted when the computer is turned on so it is unlikely that your Arduino would.
To confirm there isn't something dodgy going on with the USB power supplied to the board, use a multimeter to monitor the 5V pin of the Arduino. If the voltage isn't going too high or too low then everything should be fine. Even if it goes too low, the microcontroller will have brown-out-detect enabled to shut it down in this event.
You mentioned a display. Perhaps, and this is pure speculation, some how the display is being initialised wrongly due to the Arduino being reset by USB connection. If the display has a general reset command, or a reset pin, enable it at the start of your sketch to ensure the display is in its default state.

The display is fine, it is displaying values with good format, only the values are wrong (min/max temperatures out of possible range). Those min/max are stored in SRAM only, therefore they were freshly calculated since the Arduino was powered. Multimeter shows clean 5.00 V, but I cannot rule out some short spike, I am not sure the multimeter would show that (the response of the one I have is not immediate).

Would you be able to post the code? Just in case there is something obvious. :P

The code seems too long to post here. If I will see it again, I will try to create an isolated example, if possible.

What is the temperature sensor in use? Is it a thermistor, or some chip with i2c/2wire or a dallas 1 wire? Maybe it requires some initialisation step and not being reset properly?

@danny It is "dallas 1 wire" (DS18B20 - packed as https://www.sparkfun.com/products/11050). I am using http://www.milesburton.com/Dallas_Temperature_Control_Library to control it.

I researched this once when I was getting consistent, exactly 85 degC readings from my sensors. The Maxim DS18b20 data sheet (rev 042208, page 4, in a footnote to Table 1) says:

"The power-on reset value of the temperature register is +85°C.

Double check that the Arduino code is follows the sensor communication protocol correctly.

You are correct. I am using DS library in async mode  - setWaitForConversion(false) - therefore the library is not handling the wait for conversion for me and I have to wait on my own.

Thanks for the the feedback, Suma. That's useful to know.

The number you are seeing instead - 85.1, is suspiciously close to a Farenheit reading instead of Celcius - my guess is that there maybe a setup step for the Dallas DB18B20 that you are issuing too early for it, before it has initialised, and so it is ignoring it.
My guess would be steps being a unit setting, and a calibration setting.
can you attempt to wait a little time (perhaps 100 millis) before initialising the temperature control library.

Interesting theory, however DB18B20 is not providing F or C reading, it provides a raw value which needs to be recalculated in the program. However I agree it might be somthing with the setup wrong.


text:
How to upload Arduino C code to mBot?
I am trying to program mBot using Arduino IDE. I am connected to the mBot using USB on COM7, I am able to upload a code created in mBlock 3.4.11 fine, using "Arduino Mode" as the editing mode. I would like to proceed to more complex coding now and for this I want to be able to edit the source code directly. The source code seen in the MBlock application seems to be read only, there is a button which should allow editing the code, called "Edit with Arduino". When I press this button, the Arduino IDE opens and I am able to edit the code. The trouble is I seem to be unable to send the code edited this way into the mBot.
When I use the Arduino IDE Sketch/Upload menu item, the code is compiled, but when sending it, I always get following error:

avrdude: stk500v2_ReceiveMessage(): timeout

Note: I was editing and uploading Arduino code before with both Ardino IDE and VisualStudio visualMicro (now Arduino IDE for Visual Studio) without any issues.
I do not know exactly how is the mBlock application handling the upload, but while doing so a folder with the project is created, which contains the following buildprefs.txt - perhaps this could help to understand what it is doing:
build.arch = AVR
build.board = AVR_UNO
build.core = arduino
build.core.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\cores\arduino
build.extra_flags =
build.f_cpu = 16000000L
build.mcu = atmega328p
build.path = X:\Users\UserName\AppData\Local\Temp\build3998294614124133332.tmp
build.project_name = project_followLineAuto0_0.cpp
build.source.path = X:\Users\UserName\AppData\Roaming\com.makeblock.Scratch3.4.11\Local Store\scratchTemp\project_followLineAuto0_0
build.system.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\system
build.usb_flags = -DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'
build.usb_manufacturer = "Unknown"
build.variant = standard
build.variant.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\variants\standard
build.verbose = true
build.warn_data_percentage = 75
compiler.S.extra_flags =
compiler.S.flags = -c -g -x assembler-with-cpp
compiler.ar.cmd = avr-ar
compiler.ar.extra_flags =
compiler.ar.flags = rcs
compiler.c.cmd = avr-gcc
compiler.c.elf.cmd = avr-gcc
compiler.c.elf.extra_flags =
compiler.c.elf.flags = {compiler.warning_flags} -Os -Wl,--gc-sections
compiler.c.extra_flags =
compiler.c.flags = -c -g -Os {compiler.warning_flags} -ffunction-sections -fdata-sections -MMD
compiler.cpp.cmd = avr-g++
compiler.cpp.extra_flags =
compiler.cpp.flags = -c -g -Os {compiler.warning_flags} -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD
compiler.elf2hex.cmd = avr-objcopy
compiler.elf2hex.extra_flags =
compiler.elf2hex.flags = -O ihex -R .eeprom
compiler.ldflags =
compiler.objcopy.cmd = avr-objcopy
compiler.objcopy.eep.extra_flags =
compiler.objcopy.eep.flags = -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0
compiler.path = {runtime.tools.avr-gcc.path}/bin/
compiler.size.cmd = avr-size
compiler.warning_flags = -w
compiler.warning_flags.all = -Wall -Wextra
compiler.warning_flags.default =
compiler.warning_flags.more = -Wall
compiler.warning_flags.none = -w

Which Arduino IDE do you use? How did you get it? Which operating system? May we see the code (just curious)?

@Jot The Arduino IDE is installed by the mBlock application. The version I have is 1.6.5. I am running Windows 10 x64 Pro.

That is an old version. The newest version is 1.8.8. Here is more information about mBot: https://github.com/Makeblock-official/mBot The schematic is in the "pcb" folder. As far as I can tell the hardware and software of the mBot is okay, they know what they are doing. You could buy a cheap uno clone for 3 dollars to learn more about c++ arduino programming.

"That is an old version. The newest version is 1.8.8". Well, that is a version which is bundled with mBlocks. As it is working fine, I am not sure if it is worth messing with the installation. Regarding the C++ arduino programming, I already have experience with that (I own one Uno and one Mega board). I only had trouble making the C code working with the mBot.

Be sure to select correct board (Arduino UNO) and port.
See this guide for details:
https://www.arduino.cc/en/Guide/ArduinoUno#toc5

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


text:
How can Arduino know that the number in a variable is a pin number and not something else?
I have a question with the topic variables.
So, a variable is a place where you can store data.
And when you make a variable with datatype int (int ledpin=13;) then you store a value 10 in a variable named ledpin.
BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

Was the answer helpful? If so, please accept it by clicking on the "tick" icon next to the answer, and also possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!

You need to put the correct number into the pinMode() function.
You could put the number into a variable like:
int ledPin = 13;
pinMode(ledPin, OUTPUT);

or you can put a number straight into pinMode() like this:
pinMode(13, OUTPUT);

Whatever number you put in will be the pin that you start using.
Here's an example to blink the onboard LED:
int ledPin = 13;                 // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // Whatever number is in ledPin is made an output.
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
  delay(1000);                  // waits for a second
  digitalWrite(ledPin, LOW);    // sets the LED off
  delay(1000);                  // waits for a second
}

Yes, a variable is just somewhere to store some data.
It's what you do with the variable that is important.
For instance:
int ledpin = 13;
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);

That will set the variable ledpin to 13, then the next line will query the ledpin variable to find out what number it is, then pass that number to the pinMode function to set the mode of the pin to OUTPUT. The line after then does the same thing but passes the number 13 that it read from ledpin to the digitalWrite function to turn the LED on.
However, if you do this:
int ledpin = 13;
pinMode(ledpin, OUTPUT);
ledpin = 10
digitalWrite(ledpin, HIGH);

then it will act just the same at first, but the digitalWrite function will get the number 10 not the number 13 since the value in ledpin has been changed to 10 in the third line.
Remember: an integer is just a number - it's only when you do something with that number that it has any meaning.

thank you so much. Finally i got it. It was an great explanation. :)

BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

The Arduino does not "know" the intention of a variable. The variable "becomes" a pin number when passed as an argument to pinMode() or digitalRead().
The use of a variable to "name" a pin is part of a programming style. There are a lot of examples sketches that try to convey programming style. One of these is to reduce the amount of ripple effects of change; reduce the number of line to change for a logical change.
Continuing the LED pin number example above. The "baseline" code is:
void setup()
{
  pinMode(13, OUTPUT);
  ...
}
void loop()
{
   digitalWrite(13, HIGH);
   ...
   digitalWrite(13, LOW);
   ...
 }

This works just fine BUT what is the ripple effect if we change the pin "13". The example uses symbols OUTPUT, HIGH and LOW which are also just numbers.
Typically in C the tradition is to use the preprocessor and define a macro.
 #define LED 13

The preprocessor will replace LED in the source code with 13 and the compiler sees the same code as above.
An alternative is using a variable.
 int LED = 13;

The drawback is that memory is allocated and it is possible to change the value at run-time which is often a very bad idea especially for a pin. The definition should actually be:
 const int LED = 13;

The drawback with the macro is that it is just a value. In C++ it is best to use a constant variable. This tells the compiler both what data type and value it is. A constant variable cannot be assigned (again).
The next level to strength code quality and reduce ripple effects is to use lexical scope. A lexical scope such as a function body, class or namespace defines "when" a symbol is available.
An example; first global scope where definitions are available across the source code (just as for a macro):
const size_t BUF_MAX = 32;
static char buf[BUF_MAX];

const char* read()
{
   ...
   for (int i = 0; i < BUF_MAX; i++) buf[i] = ...
   ...
}

Local lexical scope; definitions within a function:
const char* read()
{
   const size_t BUF_MAX = 32;
   static char buf[BUF_MAX];
   ...
   for (int i = 0; i < BUF_MAX; i++) m_buf[i] = ...
}

The symbols buffer buf and the buffer size BUF_MAX are only available in the function.
class Reader {
public:
  void read()
  {
    ...
    for (int i = 0; i < BUF_MAX; i++) m_buf[i] = ...
  }
protected:
  const size_t BUF_MAX = 32;
  char m_buf[BUF_MAX];
  ...
};

Again the symbols are only available within the class and member function. Here is also another example of programming style. The prefix m_ is used to show that it is member data.
Last, the same example using a namespace:
namespace Reader {
  const size_t BUF_MAX = 32;
  char buf[BUF_MAX];
  ...
  void read()
  {
    ...
    for (int i = 0; i < BUF_MAX; i++) buf[i] = ...
  }
};
...
for (int i = 0; i < Reader::BUF_MAX; i++) Reader::buf[i] = ...;

All symbols must have the prefix Reader when used outside the namespace.
These techniques have been developed to allow writing larger programs with reuse. It is important to use them when writing a library for Arduino and especially when sharing. Ripple effects and symbol redefinition/collisions are reduced.


text:
I feel like an idiot, why can't I make a servo move with the boilerplate code?
So I was working on a far more grand project, until I discovered that I couldn't get any of my servos to move.
I've gone back to basics, and am trying to just get the boilerplate code found here, working.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

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

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

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

Here are pictures of my setup.

You can embed pictures into your question (I'm not sure of the limit if you don't have much rep - at least one or two). For short code it helps to embed the code as well - I did that for you. You can provide a link so people know where it came from.

The only thing I see that could be the problem is with your servo wiring. It seems that most servos use this kind of wiring  Which is the way that you seem to wire it, but depending on how Radioshack servos are made the signal wire could correspond with a different wire. I imagine this could possibly be on the packaging so I would start by looking there to confirm your wiring.


text:
Arduino metronome - Change time signature on button press
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);

  }
  pinMode(keyPin, INPUT);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == HIGH && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == HIGH && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == HIGH && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);

    pinMode(13, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }

    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(13, 1500, 100);
    else
      tone(13, 1000, 100);

    delay(bpm - 52);
    pinMode(13, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  }

}

I am trying to make a metronome using Arduino Uno, with 4 LEDs, each LED is a beat. I want to change the time signature every time I press the pushbutton, so that there are different number of beats per measure, but when I do press the button, it runs the code for 2 and 3 beats per measure once, and then goes back to its default, 4 beats per measure.
Sometimes, it even changes without pressing the button, randomly. I am using a 220 ohm resister instead of 10, as 10 starts much more randomly than the 220.

Do you have resistors in series with those LEDs?

No resistors are with those LEDs

You must have resistors in series with the LEDs. See The care and feeding of LEDs. 330 ohms in series with each LED would be about right in your situation.
With no resistors you are drawing far too much current from the output pins. That would drop the voltage and the processor would reset. Thus it goes back to the default of 4 beats per measure.
It also damages both the processor and the LEDs.
You can tell if the processor resets by putting extra code into setup. For example, after setting the pins to outputs:
 for (int i = 0; i < 10; i++)
    {
    digitalWrite (3, HIGH);
    delay (200);
    digitalWrite (3, LOW);
    delay (200);
    }

If you see pin 3 flashing 10 times, you know the processor has reset.

I think your problem now is that you have a floating input for the switch. When I tried your sketch, with a couple of modifications, it worked fine.
My code:
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);
  }
  pinMode(keyPin, INPUT_PULLUP);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == LOW && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);
    //bpm = 1000;

    pinMode(speaker, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }
    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(speaker, 1500, 100);
    else
      tone(speaker, 1000, 100);

    unsigned long now = millis ();
    while (millis () - now < (bpm - 52))
      {
      // quit delay if switch pressed
      if (digitalRead(keyPin) == LOW)
        break;
      }

    pinMode(speaker, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  } // end of for each pin

} // end of loop

Note that the input from the switch is now INPUT_PULLUP which means it is pulled HIGH by an internal resistor. Thus, the tests are now for == LOW rather than == HIGH.
Also, instead of a delay for the timing of the metronome, I changed it to testing millis() and seeing if time is up. Otherwise you have to hold the switch down for the entire time that a cycle repeats.

Now that I have resistors, the button still does not change the time signature (ts). How can I wire this differently or change the code?

See amended reply.


text:
Cannot connect to mBot after using Arduino IDE
Today I bought an mBot (from Makeblock) the one that uses 2.4G serial connection. After assembling it, I connected to it using mBlock (software based of Scratch) and I could control it using keyboard triggers. Then I went in Arduino IDE and used it to run some scripts on the mBot.
Next I tried to switch back to mBlock software, but now it cannot connect to the mBot anymore. Whatever Scratch-like scrips I build, they don't run anymore in mBlock.
Did I miss anything? Is there anything I can do so I can start using mBlock again?

There's probably some default firmware on the "mBot" (whatever that is) that is controlled by these scripts. Since you replaced that with Arduino code you're pretty much stuffed unless you can replace that original firmware.

I received some really good piece of advice on the official forum and it solved my problem, it now works:

When you go back to using the mBlock (Scratch) environment you will
  need to reload the firmware (Upgrade firmware from the Connect menu
  item). At least that’s what I’ve had to do. Oh, and make sure that you
  have shut down the Arduino environment to release the serial port.


text:
On my lcd my characters collide, how can i remove one(because of the programming)
My code means that when i press a button it displays a word, but by default words are already there and i need to get rid of those default words.
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7,8,9,10,11,12);

int buttonApin = 4;

void setup() {
 pinMode(buttonApin, INPUT_PULLUP);
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Mission Control ");
}

void loop()
{
  if (digitalRead(buttonApin) == LOW)
  {
    lcd.setCursor(0, 1);
    lcd.print("Test");
  }

  lcd.setCursor(0, 1);

lcd.print("launch in ");
lcd.print(millis()/1000);

The HD44780 controller has a 80 bytes (characters) memory, in order to support up to 2x40 character displays. Since you use a 2x16 display, there is an empty space in the memory you can use on your benefit. It's like having two desktops, you are able to show one or the other.
Refer to LCD Addressing for a visualization of the the memory locations and detailed explanation.

Anything you write in locations setCursor(16, 0) to setCursor(39, 0) and setCursor(16, 1) to setCursor(39, 1) will not be visible until you scroll to the left. Consequently you can have some text already written in the hidden area and then alternate the shown text just by scrolling left and right.
Here is an example
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7,8,9,10,11,12);

int buttonApin = 4;

void setup() {
   // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW)
  {
    // write text to the visible area
    lcd.setCursor(0, 0);
    lcd.print("showing 0,0-15,0");
    lcd.setCursor(0, 1);
    lcd.print("showing 1,0-15,1");

    // write text to the hidden area
    lcd.setCursor(16, 0);
    lcd.print("now  16,0-31,0");
    lcd.setCursor(16, 1);
    lcd.print("now  16,1-31,1");

    while (1) {  // scroll to the left and back to show different text without writing a single character
    delay(2000);
    for(uint8_t i=0;i<16;i++) lcd.scrollDisplayLeft();
    delay(2000);
    for(uint8_t i=0;i<16;i++) lcd.scrollDisplayRight();
    }

  }

}

The code changes the visible text just by scrolling

Either clear the display first, or print enough spaces after to overwrite the existing text.

Yes that would work, but i would like the original (defualt) text to reappear after the button has been pressed.

@Stratmoss if it works, then why not do that? You're going to have to re-print the text to the LCD as it doesn't have any memory...

@AnnonomusPenguin Are you sure about the memory?

It has a tiny bit of memory, but unless you can handle page switching (one of many optimization techniques mostly lost to history) it won't help.

@Stratmoss I'd estimate another write would take less than a 100 bytes (you have 32,000 bytes). If you want to make sure, when you click "verify," it tells you how big it is at the bottom.

@AnnonomusPenguin that worked, thanks, and the memory wasnt a problem.


text:
Attiny13 + Arduino
I started my first try in programming an ATTINY13 with my Arduino 2560.
Everything seemed fine, however when I wanted to run the blink example, my LED did not blink, it keeps lighting.
I am using 5V as input voltage.
I did not change the blink example except for the correct pin number.
All the wiring seems correct, when I change the pin number the LED stays dark, so my program is arriving propperly on the ATTINY.
If I start playing with the delays (delaymicroseconds) I get the LED to become darker.
The documentation of the ATTINY13 (www.atmel.com/images/doc2535.pdf) mentions a maximum clock frequency of 20MHz. When I choose the ATTINY13 from the Arduino IDE board menu it is listed with a 9.6MHz clock.
Could this be a reason?
How can I adjust or take care of that?
----------- Edit:
I was starting with the default blink example (delay(1000)).
I played with both, the normal delay and the delayMicroseconds.
The following codes dimmed the LED:
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  digitalWrite(3, HIGH);
  delayMicroseconds(10);
  digitalWrite(3, LOW);
  delayMicroseconds(1000);
}

Which makes me believe the LED is blinking very fast.
A similar sketch with normal delay does not make the LED dim:
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  digitalWrite(3, HIGH);
  delay(1);
  digitalWrite(3, LOW);
  delay(100);
}

And as mentioned with the default blink sketch the LED nothing happens as well.
I also made the delay a ever increasing variable to see if something is happening, no luck.
And I have 2 ATTINYs to test, same result for both...
--- Edit2:
Another try:
int led = 3;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
  delayMicroseconds(100);
  digitalWrite(led, LOW);
}

void loop() {
}

Now I moved switching the LED on and off into the setup function. Strangely enough, by changing the delay between 1000 and 100 micro seconds, the LED gets lighter and darker...
---- Edit 3:
Here is my circuit:

And this is the ATTINY specific code I added to the Arduino IDE:
attiny13.name=ATtiny13 (internal 9.6 MHz clock)
attiny13.bootloader.low_fuses=0x7a
attiny13.bootloader.high_fuses=0xff
attiny13.upload.maximum_size=1024
attiny13.build.mcu=attiny13
attiny13.build.f_cpu=9600000L
attiny13.build.core=arduino:arduino
attiny13.build.variant=tiny8

Sounds like the LED is flashing very quickly. Try delaying for a longer time.

Delay microseconds? That's a very short amount of time... try using delay() in general because that is milliseconds

Possibly the fuse is not set correctly to match the desired oscillator.

If it is getting lighter and darker in set up then the ATTiny is resetting. What clock source are you using?

Post your circuit. How have you connected the reset pin?

Try adding a capacitor near the attiny's VCC. You are using a resistor with that led, right? What core are you using, as the Arduino IDE doesn't support the attiny13 by default?

To echo what @mpflaga says, a microsecond is a millionth of a second. So 100 microseconds is 1/10,000 of a second. You should be using delay(200). "delay" is in milliseconds (thousandths of a second) and 200 milliseconds is 2/10 of a second, a flash rate you could actually see.

I switched to a different ATTINY 13 driver and core definition in the Arduino IDE and this made it work.
Unfortunately by playing around I lost track of the old driver.
I am now using smeezkekitty's core13 which I found here: http://elabz.com/arduino-shrunk-how-to-use-attiny13-with-arduino-ide/

The documentation of the ATTINY13 (www.atmel.com/images/doc2535.pdf) mentions a maximum clock frequency of 20MHz. When I choose the ATTINY13 from the Arduino IDE board menu it is listed with a 9.6MHz clock.
Could this be a reason? How can I adjust or take care of that?

I don't think it is the reason, as it is totally fine to underclock your chip. In fact, most Arduino boards are underclocked. In fact, the Arduino Uno's chip can do 20MHz, but it is only ran at 16MHz.
As mentioned in the comments, your oscillator might be off. However, it should still blink. If you're saying changing the pin makes it go dark, then some code is running.
My guess is your delay is way to short. You said you were using delayMicroseconds(). Emphasis on microseconds, not milliseconds. (1 second = 1,000 milliseconds; 1 millisecond = 1,000 microseconds) If you meant to be using milliseconds, it is very possible that you are changing the power to the LED at 1,000 times a second, instead of 1. This would make the LED dimmer than directly to power, but it would still appear lit.
Try this code:
void setup() {
  pinmode(LEDPIN, OUTPUT);
}

void loop() {
  digitalWrite(LEDPIN, HIGH);
  delay(1000);
  digitalWrite(LEDPIN, LOW);
  delay(1000);
}

Of course, replace the LEDPIN with the right value.

I added some code an clarification: I used both, delay and delayMicorseconds.

@pat the first one you delay it for 1.0e-6 seconds, and then 1/1000th of a second. On the second example, you blink it for 1/1000th of a second, and then for 1/10th of a second. Those are way too short.

I know, it is to quick to see a blink. But with the first example I see the LED becaome darker (the result of the very fast blink), but not with the second example.

@pat that is because the LED is only on for 1/1000th of a second. That's not much time! I'd try at least 50 for that delay, although the LED brightness and a few other factors will determine if you can see the LED lighting up.

See my new edit, I moved switching the LED into the setup function and the behaviour became even weirder... (thanks for your help btw.)

@pat I'm not sure why it gets lighter/darker since you always have it either HIGH or LOW and that isn't in a loop. However, that code 1.) never repeats and 2.) if it did repeat, you'd need a delay after turning it off. Try my code first to see if the issue is with the code or with your hardware...

Pin 1 is active low reset. Try connecting it to 5V to run the program.


text:
radio wave generation using arduino

const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

It is just toggling the mode of the pin, so how it is related to radio wave generation?

This looks incredibly like the post on my page: Turn your Arduino into an AM radio transmitter!
As the page mentions:

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.

These are the important lines:
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)

Timer 1 is set up to run at 800 kHz. That is a radio frequency. The toggling code just turns the output on or off as a simple form of "keying".


text:
How can I convert PID correction values to an PWM brushless command?
Please I'm working on a quadcopter, and I have to made my own flight controller based on arduino uno.
First of all please how can I get a filtred angular velocity and linear acceleration from the MPU6050, is the following code give us the angular velocity in deg/sec and the linear velocity in m/s² ?
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
and is this pid value in this following code is right ?
  accel_reading = ax;
  accel_corrected = accel_reading - accel_offset;
  accel_corrected = map(accel_corrected, -16800, 16800, -90, 90);
  accel_corrected = constrain(accel_corrected, -90, 90);
  accel_angle = (float)(accel_corrected * accel_scale);

  err = angle_setpoint - accel_angle  ;

  P = Kp * err ;
  I += (Ki * err) ;
  D = Kd * (err - errp);

  pid = P + I + D;

Thank you.

How can I convert PID correction values to an PWM brushless command?

you have to do that yourself. you have to figure out first how to correct a pid value directionally. for example, should you increase the duty cycle if pid is positive or negative?
after that, you will need to map the pid value to a range for your pwm dc.
basically, it is application / task specific, and you are in complete charge.

You convert PID outputs to process outputs by selecting appropriate Kp, Ki, and Kd constants -- they translate the error components into a process output.   For example, if you want 10 degrees of error to give you a full-scale analogWrite() adjustment, set Kp=255.0/10.   Ki and Kd will depend on the (unspecified) sampling interval.  If the measurements are noisy, you can use the Ki term to do some filtering work, but if you filter it prior to the PID, it will reduce the performance of the PID.
Code-wise, you are missing some sort oferrp=err; code, you need more than acceleration in the x direction to calculate an angle, (atan2(az,ax) or some such, depending on orientation), and your PID scheme doesn't protect against common problems like out-of-range, integral windup, or inconsistent sampling interval.   You should investigate the http://playground.arduino.cc/Code/PIDLibrary for a more robust implementation than you've half-coded above.


text:
How to write IF/Else using a threshold range of values
basically I am trying to write an IF/ELSE statement that triggers a light when a pressure sensor is between two values.
In other words, I want the light to respond ONLY if the analog read is between 400 and 600, as opposed to, say, only being above 400.
Here is the code, any suggestions?
int sensor=0;
int threshold=200;

void setup (){
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
  Serial.begin(9600);
}

void loop() {
  sensor=analogRead(0);
  Serial.println(sensor);
  if (sensor > threshold) {
    digitalWrite(2, HIGH);
  }
  else {
    digitalWrite(2, LOW);
  }
}

To get the light to turn on only when the sensor reading is between two numbers, you should test if the reading is between the two numbers, and if it is, turn on the light.
To test if a value is between two numbers, you could use the && AND operator to see if both conditions are met.  For example:
if (sensor > loLimit && sensor < hiLimit) {
    digitalWrite(2, HIGH);
} else {
    digitalWrite(2, LOW);
}

Here's a shorter way to write that:
digitalWrite(2, (sensor > loLimit && sensor < hiLimit));

In this form, the expression evaluates to 1, or HIGH, if it is true, and to 0, or LOW, if it is false.
Another approach is to test if abs(sensor-midLimit) < halfGap, where midLimit is (loLimit+hiLimit)/2 and halfGap is (hiLimit-loLimit)/2.  Turn on the light if abs(sensor-midLimit) < halfGap, else turn it off.


text:
Arduino ESC controlled motor has issues
I have a brushless motor what is hooked up to a external power supply and I'm using an arduino with a potentiometer to control it. I know that the motor has power but whenever I turn the potentiometer nothing happens. I'm wondering if my wiring is wrong. Here's the wires is connected:
First pin of the potentometer to arduino GND
Second pin of the potentometer to arduino A0
Third pin of the potentiometer to arduino 5V
Black wire of the ESC to arduino GND
Red wire of the ESC to VIN
White wire of the ESC to D8
I'm also using a switch to give both the arduino and motor power and they both seem to turn on fine.
Motor has external power and does twitch very slightly when powered on with this circuit but I can't get is to actually move substantially using the potentiometer.
Here's my code:
#include <Servo.h>//Using servo library to control ESC
Servo esc; //Creating a servo class with name as esc
void setup()
{
esc.attach(8); //Specify the esc signal pin,Here as D8
esc.writeMicroseconds(1000); //initialize the signal to 1000
Serial.begin(9600);
}
void loop()
{
int val; //Creating a variable val
val= analogRead(A0); //Read input from analog pin a0 and store in val
val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(Change if needed)
esc.writeMicroseconds(val); //using val as the signal to esc
}

In addition to supply issues, ESC's usually require an arming sequence to demonstrate that there is a prepared pilot at the controls.  Sensor-less motor startup algorithms may also be designed with the dynamics of a propeller in mind, not a bare shaft - though do be very careful of clearance and motor mounting if you fit one.  Do not, for example, try to clamp the motor in a vise for a test run, as it's likely to work itself loose.

It would seem you are attempting to power the motor's coils from VIN of the Arduino. If you are powering the whole system from USB or from the barrel connector on the Arduino, then it's likely that the small voltage regulator on the Arduino cannot supply sufficient current to the motor.
You should connect the black and red wires of the ESC directly to a high-current power supply, and ensure the black (GND) wires of the ESC, power supply, and Arduino are tied together.

So the big red and black wires on the ESC should be to the power supply, but where should the small three ones go? This is the one I'm using: https://www.amazon.com/Hobbypower-Brushless-Controller-Multicopter-Helicopter/dp/B00XKX5TBE

Sorry, I did not see earlier you noted the motor has external power. The ESC you linked to provides power out via the small black and red wires, so it would seem you have the connections correct. However the amazon reviews for that product often note the same issue you did (twitching) and say it's a poor quality unit. Is there another you can try?

One more thought: The small red wire supplies 5V, but VIN expects something a bit higher because of the voltage drop. What happens if you power the Arduino via the 5V pin, rather than Vin?

I actually read some information on the motor and noted that I'm using a phone charger to run the circuit. Is it possible that it's not running because the amperage is too low?

What is your motor info, and what are the specs of your phone charger circuit. Without details, we are just guessing mainly.

Charger is 5v 2.0a, motor: https://www.amazon.com/Hobbypower-1000kv-Brushless-Multicopter-Quadcopter/dp/B00E7LG85O/ref=sr_1_8?ie=UTF8&qid=1502322435&sr=8-8&keywords=brushless+motor+and+esc

The specs on the motor say "No Load Current @ 10V: 0.5A" So 5V is going to be on the very low end of getting it to move. Try a higher input voltage.

It's not so much that 5v is insufficient for the motor, as that it's insufficient for the regulator in the ESC, which list a 5.5v minimum right on it.


text:
Reading HC05 Output
I am using an Arduino Mega connected with a motion sensor and HC05 bluetooth chip to transmit distance data to a larger computer, process it, and send a data back. Currently, I am having trouble receiving/reading bluetooth output received from the program running on my PC which is successfully receiving data from the HC05 chip. I am using the Serial Software library to process serial input/output to the Arduino Mega. Having probed the output of the HC05 chip that serves as return stream of decision data to the Mega, I see that the magnitude of the waveform is around 3V. My guess is that for the Arduino and Software Serial library to process this input, it must be at 5 volts, just like the output, for which I had to build a voltage divider so that I could provided the specified 3.3 V to the HC05 input. Clearly if the output at TXD from the HC05 is 3.3V then the Mega will receive 3.3 volts at PIN4, the receiving pin.
Here is a basic diagram without the sensors or motors. Exact resistances are not provided but should not affect the issue.

I have provided the code below for Arduino-side operation.
/*
    This module uses the L293D chip to modulate and power
    two DC motors controlling the wheels of the FryeBot
*/

#include <SoftwareSerial\SoftwareSerial.h>

SoftwareSerial mySerial(4, 2); // RX, TX

/*L293D INPUT 7*/
const int YELLOW_GEAR_MOTOR_BACK = 8;

/*L293D INPUT 2*/
const int YELLOW_GEAR_MOTOR_FORWARD = 9;

/*L293D INPUT 10*/
const int RED_GEAR_MOTOR_BACK = 10;

/*L293D INPUT 15*/
const int RED_GEAR_MOTOR_FORWARD = 11;

/*
    Establish ratio os the rate of the faster slower gear
    to the faster gear to scale the duty cycle of the
    faster gear
*/
const float RED_GEAR_SPEED_TO_YELLOW = 0.97;

/*Constant for full duty cycle for analogWrite*/
const int FULL_ANALOG_MOTOR_SPEED = 255;

const int pingPin = 7;

long duration, cm;

char buf[10];

char current;
String messageHolder;
String message;

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

    /* add setup code here */
    pinMode(YELLOW_GEAR_MOTOR_FORWARD, OUTPUT);
    pinMode(YELLOW_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_FORWARD, OUTPUT);

}

void loop() {

    pinMode(pingPin, OUTPUT);
    digitalWrite(pingPin, LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin, LOW);

    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);

    cm = microsecondsToCentimeters(duration);

    Serial.print(cm);
    Serial.print("cm");
    Serial.println();

    /* Load the distance value into a buffer */
    String sendValue = String(cm);
    sendValue.toCharArray(buf, sizeof(buf));

    /* Write the buffer with a space after for parsing*/
    mySerial.write(buf);
    mySerial.write(' ');

    /* Stop if too close to an object */
    //Serial.print("current: ");
    //Serial.print((int)current);
    Serial.println();

    if (message != "STOP_MOTORS") {

        analogWrite(YELLOW_GEAR_MOTOR_FORWARD, (int)(RED_GEAR_SPEED_TO_YELLOW * (float)FULL_ANALOG_MOTOR_SPEED));
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, HIGH);
    }
    else {
        digitalWrite(YELLOW_GEAR_MOTOR_FORWARD, 0);
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, LOW);
    }

    current = mySerial.read();
    Serial.print((int)current);
    Serial.println();

    if (current == ' ') {
        message = messageHolder;
        messageHolder = "";
    }
    else {
        messageHolder += current;
    }

    delay(100);

}

long microsecondsToCentimeters(long microseconds) {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    // The ping travels out and back, so to find the distance of the
    // object we take half of the distance travelled.
    return microseconds / 29 / 2;
}

I am using the Serial Software library to process serial input/output to the Arduino Mega. ... Why on earth would you do that when you have three hardware UARTs...?!?!?!?!

I mean is the hardware implementation significantly better than the software one

Well.... yes? Massively better. You should only use SoftwareSerial when you absolutely must.

Ill give the UART a try and get back to you with the results. I'm assuming I should keep the voltage divider leading to the RX of the HC05?

Yes. It's still 5v logic.

So I implemented the UART approach with the same results, I can transmit data through the HC05 but the HC05 is either not receiving the data that is being sent via bluetooth from the PC or the Arduino is failing to read the data that the HC05 is successfully receiving. My guess is I need to step up the voltage from the 3.3 V output of the TX of the HC05 to 5 V for the UART RX to be able to read this. Perhaps I can use a basic bjt transistor network with 1 arduino output at high at the collector, the tx from HC05 at the base and the input to the UART RX at the emitter?

You may want a logic level translator, yes. 3.3v is at the bottom end of VIH.

The thing is I already have the transistor (bought them a year ago) and the source (any 5V arduino output pin). My only worry is that the output from the bjt transistor at the emitter might lag the input to the base (from the HC05) which is probably on the order of MHz. Would prefer not buying additional hardware is possible.

Why do you think MHz for 9600 baud...?

You're right. Didnt think of that. Still, even at 10kHz, the bjt wont lag?

Why would it? And what would it matter if it did? It would lag BOTH sides of the signal and the signal would be the same with a slight offset. Mind, what do you think it is that is used in high frequency oscillators and things? BJTs. They can go to many hundreds of MHz no problem.


text:
Protothread Library Stalling on One Thread
I am trying to use a protothreading library found here
http://harteware.blogspot.com/2010/11/protothread-powerfull-library.html
to perform protothreading with my Arduino so I can "simultaneously" read from the HC-05 Bluetooth chip input to receive information from the master computer which I am connected to over Bluetooth while also processing and transmitting data from the sensors over Bluetooth.
My code looks like this
/*
    This module uses the L293D chip to modulate and power
    two DC motors controlling the wheels of the FryeBot
*/

#include <Time-1.5.0\Time.h>
#include <WiShield\pt.h>

/*L293D INPUT 7*/
const int YELLOW_GEAR_MOTOR_BACK = 8;

/*L293D INPUT 2*/
const int YELLOW_GEAR_MOTOR_FORWARD = 9;

/*L293D INPUT 10*/
const int RED_GEAR_MOTOR_BACK = 10;

/*L293D INPUT 15*/
const int RED_GEAR_MOTOR_FORWARD = 11;

/*
    Establish ratio os the rate of the faster slower gear
    to the faster gear to scale the duty cycle of the
    faster gear
*/
const float RED_GEAR_SPEED_TO_YELLOW = 0.97;

/*Constant for full duty cycle for analogWrite*/
const int FULL_ANALOG_MOTOR_SPEED = 255;

/* HC05 Setup Data */
const int pingPin = 7;
const int HC05PowerPin = 2;

/* Distance data */
long duration, cm;

/* Values for Bluetooth RX/TX */
char buf[25];

char current;
String messageHolder;
String message;

/* Protothreads */
static struct pt pt1, pt2;

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

    /* add setup code here */
    pinMode(YELLOW_GEAR_MOTOR_FORWARD, OUTPUT);
    pinMode(YELLOW_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_FORWARD, OUTPUT);
    pinMode(HC05PowerPin, OUTPUT);

    PT_INIT(&pt1);
    PT_INIT(&pt2);

}

static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        collectAndTransmitData();
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
    }

    PT_END(pt);
}

void collectAndTransmitData() {
    digitalWrite(HC05PowerPin, HIGH);

    pinMode(pingPin, OUTPUT);
    digitalWrite(pingPin, LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin, LOW);

    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);

    cm = microsecondsToCentimeters(duration);

    Serial.print("TX: ");
    Serial.print(cm);
    Serial.println();

    if (message.indexOf("G") > 0) {

        analogWrite(YELLOW_GEAR_MOTOR_FORWARD, (int)(RED_GEAR_SPEED_TO_YELLOW * (float)FULL_ANALOG_MOTOR_SPEED));
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, HIGH);
    }
    else if (message.indexOf("S") > 0) {
        digitalWrite(YELLOW_GEAR_MOTOR_FORWARD, 0);
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, LOW);
    }

    /* Load the distance value into a buffer */
    String sendValue = String(cm);
    sendValue.toCharArray(buf, sizeof(buf));

    /* Write the buffer with a space after for parsing*/
    Serial1.write(buf);
    Serial1.write(' ');
}

long microsecondsToCentimeters(long microseconds) {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    // The ping travels out and back, so to find the distance of the
    // object we take half of the distance travelled.
    return microseconds / 29 / 2;
}

static int protothreadReadAndParseData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        readAndParseData();
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
    }

    PT_END(pt);
}

void readAndParseData() {
    Serial.println("HERE");
    current = Serial1.read();
    Serial.print("RX: ");
    Serial.print(current);
    Serial.println();

    if (current == ' ') {
        message = messageHolder;
        messageHolder = "";
        Serial.print("message: ");
        Serial.print(message);
        Serial.println();
    }
    else {
        messageHolder += current;
    }
}

void loop() {
    Serial.println("A");
    protothreadReadAndParseData(&pt2, 20); // by calling them infinitely
    Serial.println("B");
    protothreadCollectAndTransmitData(&pt1, 20); // schedule the two protothreads
}

The code prints the following in the console when executed.
A
HERE
RX: �
B
TX: 522
TX: 524
TX: 524
TX: 524
TX: 524
TX: 524

Then continues with TX: ### forever.
I am not sure why the code is not looping back to the first function or at least running it a second time. I am not very clear on exactly how to use this library or who maintains it. The docs on their Github page for their WiShield library which this pt.h is part of are not overly helpful. If you have any experience with other Arduino protothreading libraries let me know so I might try them out. I am not sure where I went wrong with this library in my implementation.
Here is the repo containing the package I am using
https://github.com/nicolaskruchten/arduino/tree/master/libraries/WiShield

In protothreadCollectAndTransmitData you have a timestamp variable that never gets updated:
static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;   // <- This never changes
    ....

When the condition is true you will need to update timestamp = millis();.
static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
        // Updated. Move this here, else it ALWAYS gets called!
        collectAndTransmitData();
        timestamp = millis();   // <- Update timestamp for next time
    }

    PT_END(pt);
}

But to make sure that is correct, you should look at the macro:
#define PT_WAIT_UNTIL(pt, condition) \
do {                                 \
    LC_SET((pt)->lc);                \
    if(!(condition)) {               \
        return PT_WAITING;           \
    }                                \
} while(0)

(You can ignore the do/while - that's just there so you can use a semi-colon.) As you can see, when the condition is false a return is issued. So it looks like it is safe to do it this way.
Disclaimer: I've never used this threading library. I'm working off of the source code I found here: https://github.com/fernandomalmeida/protothreads-arduino/blob/master/pt.h

if you had to guess, what would you put on the millisecond argument in loop() to optimize performance for each of the threads? my baud for the serial is 9600, so i think it would make sense to try a 1 on that. Having done so, it looks like it only wants to run that thread. Barely ever touches the other one running at 20 ms

does that lib work with arduino?

Looks like I had the wrong link. Updated with what appears to be the Arduino port.

The timeout for collectAndTransmitData should be whatever your sample rate is. How often do you need to check the sensor? For readAndParseData() I would add if (!Serial.available()) return; as the first line so the function never gets entered unless a message is waiting.

it seems it will only run one thread continuously for a while then switch. I will try your library

looking at it, i think it is a different source but the same file

it is still just transmitting

Oh, I just noticed that collectAndTransmitData(); should come after PT_WAIT_UNTIL(....).

Let us continue this discussion in chat.


text:
SIM800L and Arduino Sleep - getting whimsy Serial output after 5 calls
i'm working on project where i'm trying to achieve that arduino parse caller ID so i can use it later to send SMS with sensor reading data.
Somehow i made that code (with much googling) and it works great... But when i include arduino sleep part, it does work at beginning, but after i call SIM800 4-5 times with distinct of 30 seconds, i get unusable data on Serial, so i can't no longer parse correct number.
I tried many things, dropping baud rate to 1200, changing delay, but still i get strange characters after few calls.
Can anyone help me?
P.S. ATMEGA328P ic MCU
Thank you,
Matija
#include <SoftwareSerial.h>
#include <avr/sleep.h>

SoftwareSerial SIM800(8, 7);

String buffer1;
unsigned int current_millis = 0;
String phone;

void setup() {
     buffer1.reserve(200);
     phone.reserve(20);

     Serial.begin(19200); //
     SIM800.begin(9600);
     delay(1000);
     SIM800.write("AT\r");  // because of SIM800L autobounding mode
     delay(1000);
     SIM800.write("AT+IPR=9600\r");  // set baud at 9600, i tried with 1200
     and  other, and with autobauding but still got same problem
     delay(1000);
     SIM800.write("AT+CMGF=1\r");  // set SMS mode to text
     delay(1000);
     SIM800.write("AT+CNMI=2,2,0,0,0\r");
     delay(1000);
     Serial.print(SIM800.readString());
     SIM800.write("AT+CLIP=1\r\n");
     delay(1000);
     SIM800.write("AT+SGPIO=0,7,1,0\r");
     delay(1000);
     SIM800.write("AT+CSCLK=2\r"); //power saving mode of SIM800L
     delay(1000);
     current_millis = millis();
}

void loop() {
   // put your main code here, to run repeatedly:
   if (SIM800.available() > 0) {
      buffer1 = SIM800.readStringUntil('\n'); //Saving string then parsing
           caller number from it
      Serial.println(buffer1);
      parse();
      current_millis = millis();
      }

    if ((millis() - current_millis) > 10000) { //Putting atmega tu sleep
       sleepNow();
       delay(1000);// tried many delays
       current_millis = millis();
     }

 }

void parse() {
    if (buffer1.indexOf("CLIP:") > 0) {
        phone = buffer1.substring(buffer1.indexOf("+CLIP: ") + 8,
        buffer1.indexOf("+CLIP: ") + 21); //parsing caller number
        Serial.println(phone);
        SIM800.write("ATH\r"); //hang out phone call
        delay(500);
        SIM800.write("ATH\r");
        delay(500);
  }

}

void sleepNow() { //PIN CHANGE INTERRUPT ON PIN 7,8 BECAUSE SOFTWARE SERIAL
                   LIBRARY USE IT AND IT WILL WAKE UP ATMEGA
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set herethe
                                          sleep bit in the mcucr register
    sleep_mode();            // here the device is actually put to sleep!!
                         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable
                                sleep...
    }

With SoftwareSerial it's anyone's guess what may be going on. Add some extra Serial.println() calls with static text in them to work out if the fault is PC => Arduino or Arduino => SIM800.

Hi Majenko, error is between Arduino and SIM800 (i know because phone call isn't ATH when it should be). I tried your solution but it didn't work...
I tried also SIM800.end() and SIM800.begin(9600) before putting arduino to sleep...It doesn't work...
Only thing that work for me is reseting arduino after doing the job. Adding void(* resetFunc) (void) = 0;  after setup function, and call it resetFunc(); after i send message to caller.
Thank you,
if you have any idea which solves thing problem better post it here, maybe it will help someone.

When you use sleep mode SLEEP_MODE_PWR_DOWN you're turning off all of the microcontroller's timers, Including the timer SoftSerial is using.  I expect that turning off and then when wake from sleep turning back on the timers is affecting the timing of your serial communications.
Try using SLEEP_MODE_IDLE instead of SLEEP_MODE_PWR_DOWN and see if it corrects the problem.

Give AltSoftSerial a try, it's hands down superior.
Reset might work but it does not actually solve your problem, it just swipes it under the mattress. Also, have you considered ditching that String? It is the source of many problems regarding memory. You could relatively easily substitute it for an array of chars instead. Something like this, taken from example#2:
void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}


text:
Digital Music Player (SD to USB)
I own a couple of digital in-ear headphones that connect to my phone using USB (some micro, some type C), i.e. they have a built-in DAC and amp. Now instead of having to carry my phone along to listen to music, I'd like to build a portable music player - think of it as an iPod Shuffle minus the DAC+AMP - and I think the Arduino platform should be well-suited for a first prototype(?).
So if I understand correctly, then all I need is the following:

an Arduino board
some storage (i.e. a micro-SD card module)
a serial to USB-C module
some code that streams the files to serial

then "optionally":

a battery
some controls

Am I on the right track?
The headphones connect as USB OTG slave devices, so the Arduino will need to be the master - is that an issue? Also, is it possible to output serial data through the Arduino's own USB port? I've looked around, but my findings are somewhat inconclusive. On the other hand, this might not matter since I will need to power it somehow anyway...
As you may have guessed, this is my first Arduino project, so please be kind ^.^
Thanks!

I think you need to research more about how USB Type-C Audio works, because it most certainly isn't the most standard serial connection people use with Arduinos. One is for sure, you'd have to use either an expensive shield or an 32bit (fast) Arduino to even have USB.

Errrr... no.  Just no.  For a first Arduino project do something else. This will not be possible for you. It won't even be possible for me using an Arduino and I am (as some people say) a demigod.

Haha, alright, only a fool wouldn't trust the word of a demigod. I guess sometimes things aren't quite as simple as they may appear - it's simple to drive an actual speaker, andI assumed taking away the dac shouldn't make things harder. But I guess USB comes with its own set of challenges...thanks for the feedback!