How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560? I have been trying to generate a PWM wave of 38 Khz (13 microsec= ON period , 13 microsec= OFF period).  Currently I am using Timer 0 to generate the PWM wave , however i am confused as to how to prescale the 16Mhz input clock frequency so that i can get 38 Khz from it .

The code is as follows -

#include<avr/io.h>
#include<util/delay.h>

uint8_t  dutycycle;
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        DDRG |= (1<<PG5);

        // Clear o/p on Match and Fast PWM Mode
        TCCR0A |=(1<<COM0A1) | (1<<WGM01) | (1<<WGM00) | (1<<COM0B1);// COM0A1/0b1 are the ouput ports , and WGM01 and WGM02 are used for fast PWM mode
        TCCR0B |=(1<<WGM02) | (1<<CS01);//WGM02 is used to set the fast pwm mode with max value stored in OCRA. CS01 is used to prescale the clock frequency to 16Mhz % 8 .
        OCR0A = 52;

}
void dutycycleA(uint8_t dutycycle)
{
    OCR0B = (dutycycle * 52)/100 ;
}
int main()
{
        pwm_init();

        while(1)
        {
            dutycycle=50;
            dutycycleA(dutycycle);
            _delay_ms(1000);
        }
}

So , the code is supposed to keep checking the value of OCR0B with the timer value and if it is less than that , then the output is logic HIGH , and if it is same as the timer value , then it'll be logic LOW . the duty cycle is given as 50 so that a pulse waveform of 50% duty cycle is reached .

However I am unable to obtain 38Khz output .

Please help me figure out where I have gone wrong and also suggest corrections to my approach , if wrong .

Thank you .

PS - I am using Eclipse Neon platform.

It appears that you didn't set any Clock Select bits.  Per datasheet,

  clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped.

That could account for getting no output at all, if that's what's happening.  [I had overlooked (1<<CS01) in your TCCR0B setup.]

You have the COM0A1 and COM0B1 bits set, and you apparently assume COM0A0 and COM0B0 are clear. (Note that in the code below, I say TCCR1A = ... and  TCCR1B = ... instead of using |=, because |= is not reasonable to use for initial setup).  In the #7 fast PWM mode that you selected via WGM bits, this would lead to OC0A and OC0B clearing on their respective Compare Matches and setting at BOTTOM, which looks more or less ok for the OC0B pin, if you have OCR0B set to about half of OCR0A.  If the OC0A pin clears, however, it probably gets set again a cycle later, if I understand correctly.  (However, I'd want to actually test the code, with oscilloscope connected, to say for sure.)

Note that the OCR0A count of 52 and prescaler of 8 will set up a counting frequency of 1600000/(52+1)/8 Hz, ie about 37735.85 Hz, while a count of 51 would give 38461.54 Hz.  If accuracy matters, you can use simpler and more accurate code like the following.  It uses a prescale of 1 and count of 209, to generate a toggle frequency of 1600000/(219+1) Hz, ie about 76190.48 Hz, and a square wave frequency of about 38095.24 Hz.   Note, this code is written for timer 1; it should be straightforward to adapt to timer 0, because 209 is less than 255, the upper limit of TCNT0.

// Generate a constant frequency on PB1, using Fast PWM - jw May 2017
enum { OC1Apin = 9 };    // Arduino digital pin #9 = OC1A = PB1

void setup() {  // Set up timer 1
  noInterrupts();               // Turn off interrupts during setting
  TIMSK1 = 0;                   // Turn off timer 1 interrupts
  // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
  TCNT1 = 0;                    // Zero the counter
  TCCR1A = 1<<WGM11 | 1<<WGM10  // for Fast Pwm with TOP from OCR1A
    | 1<<COM1A0;                // To toggle OC1A PB1 D9 on Compare Match
  TCCR1B = 1<<WGM13 | 1<<WGM12// for Fast Pwm with TOP from OCR1A
    | 1;                      // Start timer 1 with prescale 1
  // Set OCR1A *after* setting up TCCR1A & TCCR1B
  OCR1A = 209;                // Gen. about 38095.24 Hz
  pinMode(OC1Apin, OUTPUT);
  interrupts();
}
void loop() {}

Edit 1: Here are some of the differences between this code and that shown in the question, aside from using timer 1 instead of 0:

• Initialization of TCCRxA and TCCRxB registers here is done using Register = expression forms, rather than  Register |= expression forms.  Just OR-ing your bits in may be a problem if some other CS bits are set.  For example, in the Arduino environment, initialization for millis() will set a prescale factor of 64, by setting both of the CS00 and CS01 bits, so that when you say TCCR0B |=(1<<WGM02) | (1<<CS01); you end up with both of the CS00 and CS01 bits still set, and a prescale of 64 instead of 8.

• TCCR1B = ... | 1;  // Start timer 1 with prescale 1 sets the CS00 bit and leaves the CS01 and CS02 bits clear, selecting prescale 1, while TCCR0B |= ... | (1<<CS01); selects a prescale factor greater than 1.

• The code shown here generates a square wave because it toggles a pin at a constant rate.  The code in the question sets OCR0B to 26, which will give 27 clock-cycles to half of each output cycle, and 26 clock-cycles to the other half.

• The code shown here generates a frequency of about 38095 Hz, which is about 0.25% high, vs a frequency 0.7% low for the code in the question.

Edit 2: One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle if appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:

volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

To output a specified number of cycles n, set the mode of TogPin to OUTPUT and set TogCounter to 2·n.  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.

To generate a sequence like m1 cycles on, n1 off, m2 cycles on, n2 off, etc, you could set up an array containing m1, n1, m2, n2, etc; then each time TogCounter runs down, toggle TogPin from INPUT to OUTPUT or vice versa, and load the next array entry into TogCounter.


Gratuitious instantiation of `Serial`, why? Let's take a very simple sketch, any simple one-.ino sketch. Say, just a led blinker like this

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop()
{
  static bool on;
  digitalWrite(LED_BUILTIN, (on = !on) ? HIGH : LOW);
  delay(1000);
}

Once compiled in Arduino IDE, compiler reports using 10 bytes for global variables. This is perfect for our purposes.

Now let's add an extra .cpp file to it. Let's call it foo.cpp. The file looks like follows

#include <Arduino.h>

int foo()
{
  return Serial.available();
}

Compile it all together. Now the compiler reports using 185 bytes for globals. But why?!

Clearly, this extra global memory usage is Serial. It is brought in by the fact that global object Serial is referenced from foo. In the original sketch Serial is not instantiated (or discarded) by the linker as an unreferenced symbol. In this case it is referenced from foo, so the linker keeps it.

But... But GCC linker is usually smarter than this. I'd expect it to see that symbol foo is not referenced anywhere, so the reference to Serial inside foo also "doesn't count" and should not require an instance of Serial in final code.

In fact, if I tried using my own "heavy" class, my own global variable of that class and reference it in foo (instead of Serial), GCC would work as expected: regardless of how "heavy" my global variable is, GCC linker would discard my global variable from the final code and report the same 10 bytes for globals, as expected. The global memory usage would remain at 10 until I'd actually reference foo from somewhere.

But Serial is somehow special. Even an "unused" mention of Serial causes it to appear in global memory. What is so special about it? What makes it behave that way?

My guess (though I didn't check) is that it is a side effect of the fact
that the same file contains the instantiation of Serial and the
associated ISRs. The definition of the ISR macro looks roughly
like this (slightly simplified):

#define ISR(vector) extern "C" \
    void __attribute__((signal, used, externally_visible)) vector(void)

The key here is the “used” attribute. It tells the compiler that the
symbol should be considered to be used, even though no code calls the
ISR (for a good reason: it's called by the hardware).

When your program is linked, the object file foo.o pulls in
HardwareSerial0.o. The linker then sees the serial ISRs which are
labeled as “used”. These in turn make use of the Serial object which
then appears to also be used.


Multiple tones with one piezo buzzer I have figured out how to make a piezo buzzer play two tones at once with analogWrite() and tone() but how would I make an actual song by playing both bass and treble, such as this one. Here is the circuit I had to do it:

and here is the code I had to do it:

int buzzer1 = 9;
int buzzer2 = 10;

void setup() {
  pinMode(buzzer1, OUTPUT);
  pinMode(buzzer2, OUTPUT);
}

void loop() {
  analogWrite(buzzer1, 100);
  tone(buzzer2, 262);
}

First of all - You can drain max 20mA via pin, when one of the pins is HIGH and the other LOW, there is 5V between them, so there should be at least 250 Ohm resistor placed there, if you do not want damage your Arduino. I sugest add, to each of the red wires, at least a 200 Ohm resistor (to be safe).

For playing melody you have to save it somewhere, probabely easiest way is in arrays, and then play it note by note at regular intervals.

something like this (but insert your notes and set the length correctly):

int num_tones=6;
int tones1[] = {100,200,400,200,100,50};
int tones2[] = {262,131,131,262,131,524};

void loop() {
  for (int i=0;i<num_tones;i++){
    analogWrite(buzzer1, tones1[i]);
    tone(buzzer2,tones2[i]);
    delay(250);
  }
}


Can an Arduino act as a GATT Server (Bluetooth LE) I know it's pretty standard to set up an Arduino system as a BLE client, and use something like an app running on a smartphone as the GATT server, which receives the data and does something with it.

In my scenario I have a BLE sensor that is not connected directly to the Arduino system, and I want the Arduino to be able to respond to the sensor output (a wearable accelerometer) and, for example, initiate various lighting sequences depending on the data being received.

I would prefer not to introduce a third component (ie: mobile device as GATT server) into the equation. I'd like for the Arduino to listen to the remote device's services and characteristics, analyze the incoming data and then make some decisions about what LEDs to illuminate based on that analysis.

Can an Arduino run as a GATT server?

I got this link here that could be helpful - link at the bottom. It is a tutorial that shows you how to control your Arduino with a custom app on an Android. It uses the MIT app creator, an app that lets you create an app. You program it with there IDE in some Java I believe. You can add button to your app so that is sends a message to your Arduino then program the Arduino to do something when it receives that message. For the Arduino side, you could buy an HC-05 Bluetooth module. It is both an transmitter and receiver. It is quite cheap and very popular so there is many libraries out there. I think this is a good module you should get and I recommend to get them in pairs so you can connect them together with 2 Arduinos.

https://www.youtube.com/watch?v=E-1w7dL3Cps


Arduino zero programming port recognized as EDBG USB port I am using Arduino Zero with Windows 10. I tried following the procedure listed in Getting started with Arduino to set up my Arduino/environment, however, when I connect the Zero's Programming Port to my laptop's USB 3.0 port, it detects it as "Atmel Corp. EDBG USB Port" instead of "Arduino Zero Prog. Port" (or something similar) as described under the section "Installing Drivers for the Zero" in the above link. Since it is recognized as an EDBG USB Port, I am unable to burn bootloader or upload sketches using the Programming port as it cannot detect CMSIS-DAP.
when I try to upload a sketch I get the following error:
Arduino: 1.8.13 (Windows 10), Board: "Arduino Zero (Programming Port)"
Sketch uses 23496 bytes (8%) of program storage space. Maximum is 262144 bytes.
Global variables use 3536 bytes (10%) of dynamic memory, leaving 29232 bytes for local variables. Maximum is 32768 bytes.
Open On-Chip Debugger 0.10.0+dev-gf0767a31 (2018-06-11-13:36)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
none separate
adapter speed: 400 kHz
cortex_m reset_config sysresetreq
Error: unable to open CMSIS-DAP device 0x3eb:0x2111
Error: No Valid JTAG Interface Configured.
Error: No Valid JTAG Interface Configured.

When I try to burn bootloader I get the following error:
Open On-Chip Debugger 0.10.0+dev-gf0767a31 (2018-06-11-13:36)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
none separate
adapter speed: 400 kHz
cortex_m reset_config sysresetreq
Error: unable to open CMSIS-DAP device 0x3eb:0x2111

Error while burning bootloader.

How can I fix this?
So far, I tried

re-installing the IDE several times, and also tried uninstalling the device- but it auto installs the driver when I connect again.
Starting IDE as an admin did not help, although I think the issue is the EDBG CMSIS-DAP is not installed, and instead, the EDBG USB driver is installed

I don't have one of these to test with, but in looking at the driver installation instructions, I would expect it to say "EDBG Virtual COM Port" before a driver is installed and "Atmel Corp. EDBG CMSIS-DAP" after the driver is installed.
The "Arduino Zero Programming Port" is something I expect only appears in the Tools/Port menu in the IDE, despite what it says in the article.  You can see this name given in the boards.txt file.  And this makes sense to me, given that the EDBG firmware is Atmel's not Arduino's and there appears to be no indication in the driver directory, the content of the INF files, to suggest that they they're providing their own customized driver for the programming port.  So I would trust what you see in the images, suggesting it should say CMSIS-DAP without mention of "Arduino Zero" at all.  So far as I can tell, you're not doing anything incorrect driver-wise, but I'm also not seeing everything.
In any case, it appears you should have the VID (03eb) and PID (2157) in the device properties that boards.txt instructs the IDE to look for:
arduino_zero_edbg.name=Arduino/Genuino Zero (Programming Port)
  1 arduino_zero_edbg.vid.0=0x03eb
  2 arduino_zero_edbg.pid.0=0x2157

However, your error mentions PID=2111.  I looked this up in a USB VID/PID database, and it mentions the an ATMEL Xplained board, which is not a completely unrelated thing, but this VID:PID are not mentioned in the driver information or boards.txt for the Arduino Zero.
I did find this one mention that the Xplained USB PID was used on the M0 Pro which is a different beast from the Zero.
In any case, I would not worry about not seeing something like "Arduino Zero Prog. Port" in device manager itself for the programming port.
Make sure you are using Zero and not M0 Pro.  If you have the M0 pro, in which case properties in Device Manager may show PID as *2111, I'm not sure what to suggest except that maybe you should install Microchip Studio since this seems to be the only way I can find to get the Xplained EDBG drivers.  Some work may still be required after that to get it to work in the IDE.
If you have a Zero and not M0 Pro installing Microchip Studio may also install the EDBG driver for it as well, although this really shouldn't be necessary.


"Manually" generating a PWM signal I've been trying, just out of curiosity, to write my own function that generates a PWM signal, just like analogWrite(), and to make it light up an LED. Here's my attempt so far:

const int pin = 3;
int cycle = 2; // analogWrite() outputs a 498 Hz signal, so each cycle has approximately 2ms

int duty = 0.5; // for a 50% duty cycle

void setup() {
  Serial.begin(9600);
  pinMode(pin,OUTPUT);
}

void loop() {
  digitalWrite(pin,HIGH);
  delay(cycle*duty);
  digitalWrite(pin,LOW);
  delay(cycle*(1-duty));
}

The LED does light up, but very dimly, as shown below:

However, when using analogWrite() with a 50% duty cycle to achieve the same result, the LED shines much brighter:

Is there something wrong with my code, or is there a special reason why more power is dissipated with analogWrite()?

You need to review your code and also the capabilities of the Arduino UNO.

int declares an integer.  So int duty = 0.5; is going to get rounded to either 0 1.
delay(0); also will not work.  The instruction will simply get skipped. Likely the reason why you get a brighter LED. Try to use delayMicroseconds(); if you need shorter time but the minimum delay you can have is 4 us for Arduino UNO.
If you are using times as short as 2 us, then from the above comment the delayMicroseconds(); function is not going to be sufficient.  Also, you should consider the loop overhead, which will be a few microseconds.

All in all this is not a great method.  If you do want to create your own PWM signals, it is much better to use the hardware timers.  For example this tutorial on the Arduino website.  You should also be able to find posts about hardware timers on Arduino SE.


Arduino Mega: Interrupt not working? Use any pin for interrupt? I am using an arduino mega. I'm trying to use interrupts in one of my programs.
I have 8 pins that I will need to make separate interrupts for.

The pins are 40 - 47. These pins are attached to limit switches, so when the limit switch is pressed or not it'll indicate that via digitalRead().

#define switch_1 43     // Pin 43 is connected to Switch 1 (1: X+)
#define switch_2 42     // Pin 42 is connected to Switch 2 (1: X-)
#define switch_3 41     // Pin 41 is connected to Switch 3 (1: Y+)
#define switch_4 40     // Pin 40 is connected to Switch 4 (1: Y-)
#define switch_5 46     // Pin 46 is connected to Switch 5 (2: FR)
#define switch_6 47     // Pin 47 is connected to Switch 6 (2: BL)
#define switch_7 45     // Pin 45 is connected to Switch 7 (2: BR)
#define switch_8 44     // Pin 44 is connected to Switch 8 (2: FL)
int interruptVar = 5;

In my set up function I have:

attachInterrupt(digitalPinToInterrupt(switch_6), tightenStrings1, CHANGE);

Then I have:

void tightenStrings1()
{
  interruptVar = 9;

}

When I change the status of the limit switches, by pressing them or unpressing them, this function never activates. The variable interruptVar is still 5.

What am I doing wrong?

Also, Serial isn't the problem in this case. I understand now not to use it though, but still doesn't solve the problem. Additionally I tried instead of CHANGE using RISING or FALLING and still no changes.

I have a feeling it's because the pins I'm using aren't technically interrupt pins...is there a way to make them usable as interrupt pins? I'm not allowed to change the pins being used, and using an interrupt is the best solution for the coding portion I'm working on.

You are right when you say "technically they aren't interrupt pins".

The only pins you can use as interrupts are 2, 3, 18, 19, 20 and 21. There is no way of changing that. You can't magic more interrupts out of thin air.

However there is a different interrupt system that may help you out - the pin change interrupts.  These are harder to work with since they are grouped into sets of pins that share the same interrupt, but there are far more pins with this kind of interrupt available. Note that you still have to be careful which pins you choose.

There are a couple of libraries available to help you configure the PCINT registers should you need it.


Using PROGMEM in constructor Is it safe to use PROGMEM variable like dynamically allocated memory (a pointer to PROGMEM variable which is out of scope).

I need this so I can generate a variable size (before compilation), constant values, lookup array stored in flash.

Working example:

class Ex_class {
  public:
    Ex_class(int table_size, int value_range) {
      int flash_table[table_size + 1] PROGMEM;
      _ex_table = flash_table;
      for (int i = 0; i <= table_size; i++) {
        _ex_table[i] = random(value_range);
      }
    }

    int get_value(int index) const { return _ex_table[index]; }

  private:
    int* _ex_table;
};

void setup() {
  randomSeed(analogRead(0));
  Serial.begin(9600);
  Ex_class ex_object(5, 50);
  for (int i = 0; i <= 5; i++) {
    Serial.print(i); Serial.print(": "); Serial.println(ex_object.get_value(i));
  }
}

void loop() {}

The closest I could get to what you are trying to do is this:

template <size_t table_size> struct Ex_class {
  int get_value(int index) const {
    return pgm_read_word(&_ex_table[index]);
  }
  int _ex_table[table_size];
};

void setup() {
  Serial.begin(9600);
  static PROGMEM const Ex_class<5> ex_object = {1, 2, 3, 4, 5};
  for (int i = 0; i < 5; i++) {
    Serial.print(i);
    Serial.print(": ");
    Serial.println(ex_object.get_value(i));
  }
}

void loop() {}

avr-nm and avr-objdump confirmed that the object lives indeed in the
text section of the program. Please note that:

The object is PROGMEM const. It would make no sense to try to put in
PROGMEM anything that is not constant.
The object is allocated statically. It can be either a global or a
static local, but not an automatic local like in your example.
I am using aggregate initialization here. I know no other way to
statically initialize an array of variable length. If you have an
idea, I would be interested to know though.


Wiring Issues with Sparkfun Oled I'm attempting to hook up an arduino uno with a Sparkfun Oled. I downloaded the example program and made these changes:

#define PIN_RESET 3  // Connect RST to pin 3
#define PIN_DC    4  // Connect DC to pin 4
#define PIN_CS    10 // Connect CS to pin 10
#define DC_JUMPER 0

I connected everything according to Sparfun's walkthrough. I also wired accordingly. However, I cannot seem to get the Oled to do, well, much of anything. I have tried switching the MOSI and MISO to see if that makes a difference, but it doesn't seem to have any effect.

I'm using:
pin 13 - clock (in the picture I was trying pin 8 for the clock but I have tried both)

pin 12 - MISO

pin 11 - MOSI

pin 10 - CS

pin 4 - DC

pin 3 - RESET

Can anyone tell me what's going wrong? I've tried to figure it out for a good long while now and I can't make the display do anything productive.

Thanks

Have you connected the GND pin from the UNO to the breadboard?  I can't hardly tell.  But it looks like you are also using 5V to power it?

How are you powering the UNO?  Is it just 3.3V?  I'm powering mine with a 5V but have level converters connected.

Mine:


ESP8266 TCP connection WiFiClient issue I am using ESP8266 01 board to send some data via TCP to server on local network. My code is:

#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pas";

const char* host = "192.168.1.103";

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

  // Wifi connection

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  while(Serial.available() == 0)
  {
    //wait for arduino serial data
  }

   while(Serial.available())
  {
    // send data to server
    client.print(Serial.read());
  }
}

After chacking code in Arduino IDE I am getting error message:

In function 'void loop()':
espwifitcp1:57: error: 'client' was not declared in this scope
     client.print(Serial.read());
     ^
exit status 1
'client' was not declared in this scope

It appears that if I declare WiFiClient client; inside setup() function it can't be accessed outside it. Do I correctly understand the problem? I have tried to declare object outside setup() and loop() functions but it got even more errors. Any suggestions?

You have declared WiFiClient client; in the scope of setup() only. Move it's declaration to the global scope by placing it above the declaration of void setup()


Is it possible to run two for loops separated? I have three funtion which describe the brightness of three LEDs. I want the seconde loop run 1 second after the first one and the third 1 second after the second one. One loop needs approximately 5 seconds. So basically I need to run three loops separated. How is this possible?

Update:
So I have this code running which I can compile but does not work:

int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
// Update loop enablers.
switch(periodIndex)
{
case 0:
 loop1state = true;
 loop1index = 0;
 break;

case 1000:
 loop2state = true;
 loop2index = 0;
 break;

case 1500:
 loop3state = true;
 loop3index = 0;
 break;

case 4000:
 periodIndex = 0;
 break;
}

if (loop1state)
{
 for (loop1index = 0; loop1index<255; loop1index++){
  analogWrite(LED,loop1index);
 }

 loop1state = loop1index < 256;
 }

 if (loop2state)
 {
 for(loop2index = 0; loop2index<255; loop2index++)
 {
  analogWrite(LED2,loop2index);
 }

 loop2state = loop2index < 256;
}

 if (loop3state)
 {
 for(loop3index = 0; loop3index<255; loop3index++)
 {
  analogWrite(LED3,loop3index);
 }
 loop3state = loop3index < 256;
 }
 delay(10);
 }

No, but there is a solution to put the action in one loop (main loop).

If I understand you well, you have the following scheme:

Time[s]
0..1     Loop 1
1..2     Nothing
2..3     Loop 2
3..4     Nothing
4..5     Loop 3

Define a variable that keeps track of the time.
Check against the current time (millis) and when within the correct 'range' perform an action.
After 5 seconds start over again.

uint32_t lastTime = -1;

void loop()
{
    if (lastTime == -1)
    {
        lastTime = currentTime; // Initialization, can be done in setup too
    }

    uint32_t diffTime = millis() - lastTime;

    if (diffTime < 1000) // 0..1 sec
    {
        DoLoop1();
    }
    else if (diffTime < 2000)
    {
         // Do nothing();
    }
    else if (diffTime < 3000)
    {
       DoLoop2();
    }
    else if (diffTime < 4000)
    {
        // Do nothing
    }
    else if (diffTime < 5000)
    {
       DoLoop3();
    }
    else // diffTime >= 5000
    {
         lastTime == currentTime; // Reset after 6 s
    }
}

Update

Since you need all three loops together (and mixed), it's easier to define some variables.

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

Too bad I don't know the conditions when a loop starts, but let's say each iteration is 10 ms, and loop 1 starts immediately, loop 2 after 1000 ms, loop 3 after 1500 ms. After 3000 ms it starts all over.

void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
     loop1state = true;
     loop1index = 0;
     break;

  case 1000:
     loop2state = true;
     loop2index = 0;
     break;

  case 1500:
     loop3state = true;
     loop3index = 0;
     break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
     DoLoop1(loop1index++);
     loop1state = loop1index < 256;
  }

  if (loop2state)
  {
     DoLoop2(loop2index++);
     loop2state = loop2index < 256;
  }

  if (loop3state)
  {
     DoLoop3(loop3index++);
     loop3state = loop3index < 256;
  }

  delay(10); // 10 ms
}

Note, not tested, but the idea shold be clear

New update

You should not do a full loop during each switch, but only one iteration of the loop.

I did not run the sketch, just out of my head.

Some tips: print out the variables during each loop, so you get a clear idea what is happening (so all loop states and indices, and the periodIndex).

int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
    loop1state = true;
    loop1index = 0;
    break;

  case 1000:
    loop2state = true;
    loop2index = 0;
    break;

  case 1500:
    loop3state = true;
    loop3index = 0;
    break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
    analogWrite(LED,loop1index++);
    loop1state = loop1index < 256;
  }

  if (loop2state)
  {
    analogWrite(LED2,loop2index++);
    loop2state = loop2index < 256;
  }

  if (loop3state)
  {
    analogWrite(LED3,loop3index++);
    loop3state = loop3index < 256;
  }

  periodIndex++;
  delay(10);
}


Building a gps system I'd like to build a simple GPS system. It should be very little. For the software side, I will build an API, so from my PC/smartphone/whatever else I could ask the GPS system where it is located (I think Google provides this kind of feature).

How can I do this? My main problem is the GPS and the its building. I'd like to build the smallest thing possible, because I have to hide it. My idea is to hide this GPS system in my bike: I'd like to locate my bike if someone stole it. As you can see, internet is a problem.

I'm not asking to design anything. I would only know what I need to build a basic GPS system that has just the feature described. What do I need? Is it possible to do it? Does GPS require Internet connection? I would know if I could make it or not without internet access.

"Is it possible to do it?"

Well... everything is possible :-)

"Does GPS require Internet connection?"

GPS doesn't require internet. A GPS receiver (e.g. http://www.modulestek.com/prodts/GPS/Mars740-mini/Mars740-mini_SPEC.pdf) is connected to the reading unit via USB or a RS232 interface. The protocol is very simple. However it only provides latitude and longitude. If you want to have an address, map data is required (for this you would need internet - or a large memory).

And of course such a system requires good signals from the GPS satellites.

"What do I need?"

First you need a GPS receiver (see above).

Second, you need a microcontroller unit which runs your application and does all the control of the external units.

Third, you need a GSM module (e.g. http://www.exp-tech.de/Shields/Wireless/GSM-GPRS/adafruit-fona-mini-cellular-gsm-breakout-sma.html) to send a message.
Don't forget the antenna for connection to the mobile communication network.

Fourth, you need a power supply. Ideally it has a battery which can be reloaded when driving.

As you may see, if you put all this together you are far from the "smallest thing possible".

Actually any modern smartphone could be enough. Mount it "invisible" under your saddle, connect it to a bike charger, find the proper App and that's it - although it might not be the smallest solution.

I don't know any, but I'm sure there are products off the shelf that fulfil your requirements, designed and developed by experienced engineers, and thus smaller and maybe cheaper than what you ever could achieve on your own.


Arduino - My problem is when the condition is greater than 900.00 it will continue the loop and do the code below once I want is to stop the loop and when it read  Greater than 900.00 again it will do task again.

I need condition. When it back to greater than 900.00 the code below will do task and then it will stop. And when it will reach the condition again it will do the code again and it will stop .. Please help me

void loop(){
  float reading = analogRead(LIGHTSENSORPIN); //Read light level
  float square_ratio = reading / 1023.0;      //Get percent of maximum value (1023)
  square_ratio = pow(square_ratio, 2.0);      //Square to make response more obvious

  analogWrite(LEDPIN, 255.0 * square_ratio);  //Adjust LED brightness relatively
  analogWrite(LED_BUILTIN, 255.0 * square_ratio);  //Adjust LED brightness relatively
  Serial.println(reading);                    //Display reading in serial monitor

if(reading >= 900.00){

  digitalWrite(smDirectionPin, LOW); //Writes the direction to the EasyDriver DIR pin. (LOW is counter clockwise).
    /*Turns the motor fast 1600 steps*/
      for (int i = 0; i < 400; i++){
    digitalWrite(smStepPin, HIGH);
    delayMicroseconds(700);
    digitalWrite(smStepPin, LOW);
    delayMicroseconds(700);
}
}

  delay(1000);

}

setup(){ ....
......
}
float old_reading=0;
loop() {
float reading = analogRead(LIGHTSENSORPIN); //Read light level
// ... do this always (maybe empty)
// in your code it is LED shining and printing
if ((old_reading<=900) && (reading>900)) {
   // ... do this just just once when reading goes over 900 up
   // in your code it is manipulating motor
   }
old_reading=reading;
// ... do this always , but after special part (maybe empty)
// in your code it is just delay
}

So on begining old_reading is just zero, but being declared outside loop, it keeps its value between different runs of loop.
the if (condition) does not hit, as reading is less than 900 (if it starts with more then 900, see next part)
the end with old_reading=reading; makes old_reading to be the last known value of reading
when reading goes Greater than 900 for first time, the old_reading is Less or Equal 900 (as it was the last value of reading before it crossed 900 up.

so the if (condiotion) is true and you start moving motor

then (on the end) you set old_reading=reading; and old_reading is also larger then 900

while reading stays over 900 in next loops, the old_reading does so, and therefore the if (condition) does not hit - (old_reading<=900) is not true

when reading falls down 900 or lower, the if(condition) also does not hit, but after that the old_reading=reading; makes old_reading less or equal 900

and so we are at the start again, skipping the part after if(condition) until reading gets Greater than 900 (then we run motor, set old_reading to something greater than 900 and we already was here and know, how it works :)


Encoders for precise robot turns So I recently purchased:

DFRobot Wheel Encoders

DFRobot 3PA and 4WD Rovers (2pk)

Romeo V2 Arduino Controller

I was doing a bit of research online and I'm trying to figure out how to use the encoders to control the PWM applied to the motors which will make precise turns. This seems like a popular method to use. Here is some of my code. I have nothing for the encoders yet. I only have the sensors working the PWM control for the motors. All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn. Does anyone have some sample code or tips on how to do this? Thanks in advanced!

  void stop(void)
    {
      digitalWrite(5,LOW);
      digitalWrite(6,LOW);

    }
    void forward(char a,char b)
    {
      analogWrite(5,a);
      digitalWrite(4,HIGH);
      analogWrite(6,b);
      digitalWrite(7,HIGH);

    }
    void back(char a,char b)
    {
      analogWrite(5,a);
      digitalWrite(4,LOW);
      analogWrite(6,b);
      digitalWrite(7,LOW);

    }
    void Left(char a,char b)
    {
      analogWrite (5,a);
      digitalWrite(4,LOW);
      analogWrite (6,b);
      digitalWrite(7,HIGH);

    }
    void Right(char a,char b)
    {
      analogWrite (5,a);
      digitalWrite(4,HIGH);
      analogWrite (6,b);
      digitalWrite(7,LOW);

    }
    void setup(void)
    {

      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);
      for(int i =4;i<=7;i++)
        pinMode(i, OUTPUT);
      pinMode(LED_BUILTIN, OUTPUT);
     forward(100,100);

      Serial.begin(9600);

    }
void GetSensor()
{

  Sen_Val_B = SenAvg(Sensor_Back);
  Sen_Val_F = SenAvg(Sensor_Front);
  Sen_Val_R = SenAvg(Sensor_Right);
  Sen_Val_L = SenAvg(Sensor_Left);

}

int SenAvg(int SensorNumber)
{

  Arr[100]= 0;
  avg = 0;

  for(int i = 0; i<100; i++)
  {
    Arr[i] = analogRead(SensorNumber);
    avg = avg + Arr[i];
  }
    avg = avg/100;
    return avg;
}
void loop(void)
{

   GetSensor();
  if(Sen_Val_F > 200)
  {
   stop();
  }

}

All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn.

would this work?

  if (wall_sensed()) turn_90right(); //if wall is sensed, turn 90 degrees to the right

You may also consider change

  digitalWrite(5,LOW);
  digitalWrite(6,LOW);

to:

  digitalWrite(MOTOR_LF,STOP);   //stop left front motor
  digitalWrite(MOTOR_LR,STOP);   //stop left right motor

so that

it is a lot more readable; and
if you were to change pin assignment, it is done consistently throughout your code.


Android Studio project for Redbearlab BLE Shield apps To interact with its BLE shield, Redbearlab published sample Android apps in the Play Store. The sources for the apps are available on GitHub. How can I build them in Android Studio?

It was much simpler than expected to put together the Android Studio projects. They are on GitHub now.

Note that the apps built from source are actually different from the ones published by Redbearlabs on the Play Store. On top of that, the chat app is not working.


The Time are functions do not work correctly when the processor clock speed is set at 128K How can I change The timers to work correctly when The processor clock is set to 128K instead of 16 M?
At present, using the delay function does not work correctly, The delay is far too long.

Add a new entry in boards.txt with the new value for f_cpu. Note that the timing functions will become far less precise at so low a speed.


Why map Arduino pins 2 and 3 to Rx and Tx instead of using the build in Rx and Tx pins? In many examples I see the following:

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// set up a new serial object
SoftwareSerial mySerial (rxPin, txPin);

what is the benefit of mapping pins 2 and 3 like this? Why not just use the built in RX (pin 0) and TX (pin 1) pins? I'm using a standard Arduino Uno.

SoftwareSerial lets you add an additional serial port using "bit banging" to read/write to the port. This lets you connect up another serial device (eg. GPS, RFID reader, MIDI device, LCD) to this extra port, and still use the hardware serial interface (pins 0 and 1) via the USB port to send messages and/or debugging to the connected PC.

  Is there any special wiring needed to send messages to the connected PC? Or is it enough that they just not be in use?

Pins 0 and 1 are connected to the Atmega16U2 USB interface chip. If it gets what looks like serial data it will forward it to the PC.


Can someone help me figure out why only one wheel is spinning? I am attempting to use a code which I have posted below for two wheels. However, when connected to power, only one wheel spins. I am using a 9V battery which is what was suggested so I am not sure why only one wheel spins. When both wheels are connected, the wheel that was originally working stopped spinning.
#include <SPI.h>      //SPI library for communication with the nRF24L01+
#include "RF24.h"  //The main library of the nRF24L01+
#include "Wire.h"

RF24 radio (8, 9); // CE,CSN

//Create a pipe addresses for  communication
const uint64_t pipe = 0xE8E8F0F0E1LL;

struct package
{
  int X = 1;
  int Y = 1;
};

typedef struct package Package;
Package pos;

int buttonState;
int spinnerState = false ;
int motora_1 = 3;
int motora_2 = 4;
int motorb_1 = 5;
int motorb_2 = 6;
int spinner = 2;

void setup()
{
  Serial.begin(9600);
  radio.begin();                    //Start the nRF24 communicate
  radio.openReadingPipe(1, pipe);   //Sets the address of the transmitter to which the program will receive data.
  radio.startListening();
  pinMode(motora_1, OUTPUT);
  pinMode(motora_2, OUTPUT);
  pinMode(motorb_1, OUTPUT);
  pinMode(motorb_2, OUTPUT);
  pinMode(spinner, OUTPUT);
  digitalWrite(spinner, LOW);
  delay(100);
}

void loop()
{

  if (radio.available()) {
    radio.read(&pos, sizeof(pos));
    radio.read(&buttonState, sizeof(buttonState));
    Serial.print("X:");
    Serial.print(pos.X);
    Serial.print("      Y");
    Serial.print(pos.Y);
    Serial.print("      buttonState");
    Serial.println(buttonState);
  }

  int xAxis = pos.X;
  int yAxis = pos.Y;
  int forward = map(yAxis, 570, 1024, 0, 255);
  int backward = map(yAxis, 480, 0, 0, 255);
  int right = map(xAxis, 570, 1024, 0, 255);
  int left = map(xAxis, 480, 0, 0, 255);

  if (yAxis > 570) {          // Move Forward
    // Set Motor A forward
    analogWrite(motora_1, forward);
    analogWrite(motora_2, 0);
    // Set Motor B forward
    analogWrite(motorb_1, forward);
    analogWrite(motorb_2, 0);
  } else if (yAxis < 480) {                     //Move Backward
    // Set Motor A backward
    analogWrite(motora_1, 0);
    analogWrite(motora_2, backward);
    // Set Motor B backward
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, backward);
  } else if (xAxis > 570) {                     // Move Right
    // Set Motor A forward
    analogWrite(motora_1, right);
    analogWrite(motora_2, 0);
    // Set Motor B stop
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, 0);
  } else if (xAxis < 480) {                     // Move Left
    // Set Motor A stop
    analogWrite(motora_1, 0);
    analogWrite(motora_2, 0);
    // Set Motor B foward
    analogWrite(motorb_1, left);
    analogWrite(motorb_2, 0);
  } else  {     //stop
    // Set Motor A stop
    analogWrite(motora_1, 0);
    analogWrite(motora_2, 0);
    // Set Motor B stop
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, 0);
  }

  if (buttonState == 0 ) {
    spinnerState = ! spinnerState;
    delay(50);
  }

  if (spinnerState == true) {
    digitalWrite(spinner, HIGH);    //turn On spinner
    delay(100);
  } else {
    digitalWrite(spinner, LOW);      //turn Off spinner
    delay(100);
  }

}

Firstly, the 9V batery is going to struggle with driving two motors. Change this 9V battery out with another power source.
As @timemage points out in his comment, you are using a PWM command on a non-PWM pin. For the Arduino Uno, the PWM pins are: 3, 5, 6, 9, 10, 11. Move the wiring and change the code so that it is using pin 9, 10 or 11 instead of pin 4.
It sounds like you are trying to test your hardware setup and your firmware at the same time. It is much easier to test your hardware first and make sure that works as expected before testing your firmware. I suggest writing a simpler program (the simpler the better) that just drives the motors full forward - one at a time and then together. Verify that it works and then change your test program so the motors spin in (full) reverse. Then change your test program so it changes the speed of the motors. Then with known working hardware test your firmware.


ATTiny 85 analog input pin number problem I am using AT Tiny 85 to read voltage from lead acid battery charger while charging.  Basically the setup has two 7-segment displays driven by two SIPO shift registers(74ls164n). And used tiny 85's pin 4 (physical pin3) to read voltage.

I tested the code using arduino and finally burned it to AT Tiny 85,   it didn't worked, i debugged it for hours, and pulled hair out of my head, tested it on bread board, eventually i changed the port to "A2" from "4" and surprisingly, everything runs as expected.

My question is why this happens? why analogRead(A2) works while analogRead(4) don't. ?

I am using Arduino IDE 1.6.5 with https://github.com/damellis/attiny  (1.0.1 installed from the board manager) .

Full Code:

//// Arduino Uno Pins
//const int data = 8 ; //Tiny pin 3 (Physical 2)
//const int clock = 9 ;//Tiny pin 2 (physical 7)
//const int battery_Sensor = A0; //Tiny pin 4 (physical 3)
//const int charger_ctrl = 5;   //Tinypin 1 (physical 6)

// ATTiny 85 Pins
const int data = 3 ;
const int clock = 2 ;
const int battery_Sensor = 4;
const int charger_ctrl = 1;

int outputValue = 0;
int sensorValue = 0;
int voltage_reading = 0;
int msb = 0;
int lsb = 0 ;

// Qo -> 1
// Q1 -> 2
// Q2 -> 4
// Q3 -> 5
// Q4 -> 6
// Q5 -> 7
// Q6 -> 9
// Q7 -> 10

char c_array[10] = { '0', '1', '2',  '3',  '4',  '5', '6',  '7', '8', '9'} ;

int measure_voltage(){
 sensorValue = analogRead(battery_Sensor);
 return map(sensorValue, 0, 1023, 0, 50);
}

byte seven_segment(char input, bool period){
  byte output_byte;
  switch (input) {
      case '0':
        output_byte = B11101110;
        break;
      case '1':
        output_byte = B10000010;
        break;
      case '2':
        output_byte = B11001101;
        break;
      case '3':
        output_byte = B01101101;
        break;
      case '4':
        output_byte = B00101011;
        break;
      case '5':
        output_byte = B01100111;
        break;
      case '6':
        output_byte = B11100111;
        break;
      case '7':
        output_byte = B00101100;
        break;
      case '8':
        output_byte = B11101111;
        break;
      case '9':
        output_byte = B00101111;
        break;
      default:
        output_byte = B00000001;
      break;
    }
  if(period == 1){
    output_byte = output_byte ^ B00010000;
  }
  return output_byte;
}

void setup()
{
  pinMode(clock, OUTPUT); // make the clock pin an output
  pinMode(data , OUTPUT); // make the data pin an output
  pinMode(charger_ctrl, OUTPUT);
  pinMode(battery_Sensor, INPUT);

}

void loop() {
    voltage_reading = measure_voltage() ; // voltage x 10
    msb = voltage_reading/10;
    lsb = voltage_reading%10;

    shiftOut(data, clock, LSBFIRST, seven_segment(c_array[lsb], 0));// send this binary value to the shift register
    shiftOut(data, clock, LSBFIRST, seven_segment(c_array[msb], 1));
    delay(1000);
}

See the analogPinToChannel function.

static const uint8_t A0 = 6;
static const uint8_t A1 = 7;
static const uint8_t A2 = 8;
static const uint8_t A3 = 9;

...

#define analogPinToChannel(p)   ( (p) < 6 ? (p) : (p) - 6 )

Using A2, which is 8, will return 2 (8-6) from the analogPinToChannel function.

Using 4 will give 4. There is no (useful) analog channel 4.


"variable must be const" fix for Arduino progrem I am trying to upload to my nano the code attached. It is giving me an error saying variable must be const about something I am trying to put in progrem. I learned that installing a older version of the compiler worked. However I was wondering is there a way to just edit the code to make it work. I tried putting const before it but it didn't work. It is on line 78 and 79 of the first file.

const extern PGM_P *NApowerCodes[] PROGMEM;

const extern PGM_P *EUpowerCodes[] PROGMEM;

Using the source from this link I got it to compile following these steps.

Before opening the sketch in the Arduino:

Rename TVB.pde to TVB.ino
Rename WORLDcodes.cpp to WORLDcodes.h

Open the sketch (TVB.ino) in the Arduino IDE

Edit main.h and change:

// The structure of compressed code entries
struct IrCode {
  uint8_t timer_val;
  uint8_t numpairs;
  uint8_t bitcompression;
  uint16_t const *times;
  uint8_t const*codes;
};

to:

// The structure of compressed code entries
struct IrCode {
  uint8_t timer_val;
  uint8_t numpairs;
  uint8_t bitcompression;
  uint16_t const *times;
  uint8_t const*codes PROGMEM;
};

That is, add PROGMEM to the codes line.

Edit TVB.ino and change:

extern PGM_P *NApowerCodes[] PROGMEM;
extern PGM_P *EUpowerCodes[] PROGMEM;
extern uint8_t num_NAcodes, num_EUcodes;

to:

#include "WORLDcodes.h"

This avoids some linker problems in the original code.

Edit WORLDcodes.h and delete the line:

 #include "main.h"

Continue editing WORLDcodes.h and change:

const struct IrCode *NApowerCodes[] PROGMEM = {

to:

const struct IrCode * const NApowerCodes[] PROGMEM = {

And also change:

const struct IrCode *EUpowerCodes[] PROGMEM = {

to:

const struct IrCode * const EUpowerCodes[] PROGMEM = {

It should now compile OK.


Problem with uploading my sketch to my Arduino I chose the correct COM port but it won't upload.

Arduino: 1.8.3 (Windows 10), Board: "Arduino Leonardo"

Sketch uses 5252 bytes (18%) of program storage space. Maximum is 28672 bytes.
Global variables use 228 bytes (8%) of dynamic memory, leaving 2332 bytes for local variables. Maximum is 2560 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:713)
    at processing.app.SketchController.exportApplet(SketchController.java:686)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2149)
    at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port 'COM4'.
    at processing.app.Serial.touchForCDCReset(Serial.java:99)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:93)
    ... 6 more
An error occurred while uploading the sketch
Exception in thread "Thread-124" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:123)
    at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:106)
    at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:682)
    at processing.app.Base.onBoardOrPortChange(Base.java:1297)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2179)
    at java.lang.Thread.run(Thread.java:745)

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

This is the relevant bit in your error output:

Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.

Is your Leonardo on COM4, or some other port? Does some other program have that port open?


How to fix serial communication? I am trying to use serial communication to open and close a Blue Robotics Newton gripper. The gripper works with normal commands, but when I try to use serial communication to control it, it is extremely slow and my commands do not correspond to the action I would like. For example, I'll write a "o" in the serial monitor and the gripper will not open.
Does anyone know what is wrong?
#include "Servo.h"

#define GRIPPER_PWM_PIN   10    // Gripper PWM output pin
#define OPEN_TIME         5.0   // Gripper open time (seconds)
#define CLOSE_TIME        5.0   // Gripper close time (seconds)

#define OPEN_PWM_US       1100  // Gripper open PWM output (us)
#define CLOSE_PWM_US      1900  // Gripper close PWM output (us)
int incomingByte =0; // for incoming serial data
Servo gripper;

void setup() {
 // Attach gripper to proper pin
 gripper.attach(GRIPPER_PWM_PIN);
 Serial.begin(9600); // opens serial port, sets data rate to 9600 bps

}

void loop() {
 if (Serial.available() > 0){
   incomingByte = Serial.read();
   if (incomingByte == 'o')
   {
     // Open the gripper
     gripper.writeMicroseconds(1100);
     // Let the gripper open up (microseconds)
     delay(OPEN_TIME*1000);
   }

   if (incomingByte == 'c')
   {
     // Close the gripper
     gripper.writeMicroseconds(1900);
     // Let the gripper close for a while (microseconds)
     delay(CLOSE_TIME*1000);
   }
 }
}

You have a big 5s delay in your code, right after both serial commands. You don't need a delay there; it does not do anything. But it makes your code unresponsive. So you can simply remove it.
I guess you wanted to do some timed thing there and accidentally left it there.  But in general you should not use any big delay() in any code. As you have seen, it makes your code unresponsive, as the Arduino doesn't do anything during this time. Instead look at the BlinkWithoutDelay example, that comes with the Arduino IDE (Its a really important principle to learn). It uses the millis() function (or alternatively the micros() function) to check, if it is time to do something. If yes, it will execute this, if not, it will exit fast and give the rest of the code an opportunity to execute. Much like you would bake a pizza: You start the baking and then regularly  check the clock, if it is time to take the pizza out. In between you can do other things, like reacting go messages on your phone. Its the same principle, just in code.


FreeRTOS: Object not created properly from within task I am encountering a very strange error using freeRTOS on an Arduino Mega2560:

In the setup block I can create an instance of my class:

MyClass* myClass = new MyClass(/*char*/ a, /*char*/ b, new Vector(42));
// new Vector(42) creates a new vector and pushes 42 in as first item

Using a print() method in this class, I get a legitimate output on the console, showing me all the chars and values in the vector.

Using the exact same line inside a task, causes the object not to be created properly. It seems like the fields are empty or there is something entirely wrong (like strange memory errors) with the instance. Printing it again results in an empty line (program doesn't crash) while printing a globally created instance gives the correct result.

Is there any trap in freeRTOS concerning the creation of new instances of an object inside a task? Below is the code for the task creation, increasing the task stack size doesn't help. For debug reasons this the only task running at the moment.

xTaskCreate(displayTask,
    "DisplayTask",
    configMINIMAL_STACK_SIZE + 300,
    NULL,
    tskIDLE_PRIORITY + 1,
    NULL);

'Strange memory errors' you seem to be describing values that have gone out of scope.

This is all based on your code, so I may have misunderstood.

The third parameter is causing a memory leak, unless you happen to be deleting it within MyClass (which is normally, not always, bad practice).

It sounds to me that you are trying to access values that have gone out of scope.

Its also possible that this OS requires you to do something to allow the memory to be shared between the tasks.


Cannot spin motor 28BYJ-48 with controller board ULN2003APG I'm a beginner with Arduino. I managed to grasp the basic understanding and try to use each component/shield that came with my Arduino kit.

I'm unable to use the following component:

Step Motor 28BYJ-48
Step Motor controller board ULN2003APG

I connected the Arduino to the ULN2003APG and put some coding such that I can see that the ULN2003APG's LED turned on from 1, 2, 3, 4, 1, 2, 3, 4, and so on. So this is as expected as per programming below.

My issue:

I noticed the LED in the ULN2003APG is not as bright as a regular
LED.
Once I plugged in the 28BYJ-48 to the ULN2003APG, the ULN2003APG's LED all off.
The motor (28BYJ-48) doesn't spin - at all.
I tried to spin the motor with my 2 fingers, it seems pretty heavy - is this normal?

Is this a faulty ULN2003APG or is it a faulty 28BYJ-48 or is it a faulty programming? please help.

Program:

#include <Stepper.h>

int pin1=8;
int pin2=9;
int pin3=10;
int pin4=11;
int _step=0;
void setup() {
    Serial.begin(9600);
    pinMode(pin1, INPUT);
    pinMode(pin2, INPUT);
    pinMode(pin3, INPUT);
    pinMode(pin4, INPUT);
}

void loop() {
  switch (_step){
    case 0:
      digitalWrite (pin1, HIGH);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, LOW);
      break;
    case 1:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, HIGH);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, LOW);
      break;
    case 2:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, HIGH);
      digitalWrite (pin4, LOW);
      break;
    case 3:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, HIGH);
      break;
  }
  _step ++;
  if (_step == 4){
    _step = 0;
  }
  Serial.println(_step);
  delay(250);

}

What happens if you change

pinMode(pin1, INPUT);
pinMode(pin1, INPUT); // Pin 2 ?
pinMode(pin3, INPUT);
pinMode(pin4, INPUT);

to

pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);

Answer for Q1 - Q3. You are using pinMode as an input. Using digitalWrite() on an INPUT will enable (HIGH) or disable (LOW) the internal pullup resistor on the input pin. The pin will not be able to "source" enough current to operate the stepper motor.

A4. The stepper motor has a "mechanical" 1/64 gear ratio. This is why it is hard to turn by hand.

Here are 2 pages that will help you to understand the issue: https://www.arduino.cc/en/Reference/PinMode and https://www.arduino.cc/en/Reference/DigitalWrite.


Which Arduino is the most suitable for my project? I've started to prototype something using an Arduino Mega and Yún Shield.

It's simple. It reads an ADC at 50Hz and sends data to a server through a socket. But because of that combination, I need to use Bridge to send data through the socket. It's very slow.

Should I change the Arduino Mega for a Leonardo or a Due to get better performance?

Here is my code, maybe I did something wrong.

Arduino code:

#include <Bridge.h>
#include <Process.h>
#include <Time.h>
#include <TimeLib.h>
#include <stdlib.h>

boolean interruptFlag = 0;
int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;
String analogSignals = "";
static char outstr[15];
int count = 0;
float x = 0.0;

void setup() {
  // Bridge startup.
  Bridge.begin();
  // Initialize Bridge values.
  Bridge.put("data", "");
  noInterrupts(); // Stop interrupts.
  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.
  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
  // Turn on CTC mode.
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 << OCIE1A);
  interrupts(); // Allow interrupts.
  // Launch Python script.
  /*Process p;
  p.begin("python");
  p.addParameter("/root/test/send.py");
  p.run();*/
}

ISR(TIMER1_COMPA_vect) {
  if (!interruptFlag) {
    interruptFlag = 1;
  }
}

void loop() {
  if (interruptFlag) {
    writeAnalogSignals();
    interruptFlag = 0;
  }
}

void writeAnalogSignals() {
  String HDReading = convertToVoltage(analogRead(HD));
  String HGReading = convertToVoltage(analogRead(HG));
  String CDReading = convertToVoltage(analogRead(CD));
  String CGReading = convertToVoltage(analogRead(CG));
  String ECGReading = convertToVoltage(analogRead(ECG));
  if (analogSignals.length() == 0) {
    analogSignals =  String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
  } else {
    analogSignals += "|" + String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
  }
  x += 0.02;
  count += 1;
  if (count >= 50) {
    Bridge.put("data", analogSignals);
    analogSignals = "";
    count = 0;
  }
}
// Convert the analog reading to voltage.
String convertToVoltage(int analogSignal) {
  dtostrf(analogSignal * (5.0 / 1023),8, 6, outstr);
  return outstr;
}

Python code:

import socket
import sys
import getopt
import time

def main(argv):
    try:
        sys.path.insert(0, '/usr/lib/python2.7/bridge/')
        from bridgeclient import BridgeClient as bridgeclient
        # Create a UDP socket.
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        server_address = ('192.168.1.100', 9050)
        bridge = bridgeclient()
        previous = ""

        # Send data
        while 1:
            data = bridge.get("data")
            if data != previous:
                sent = sock.sendto(data, server_address)
                previous = data
            time.sleep(0.5)

    finally:
        sock.close()

Both Mega 2560 and Due can handle 4 channels of 1,440 samples per second A-to-D and the least significant byte of the system time stamp sent as a continuous stream of vectors through the USB port to Linux.

In the lab I train at, we see almost no variance in time increment between samples or between receiver read operations, indicating that the bottleneck is our deliberate delays between samples.

The Due is running at full resolution too and communicates via the native port. The receiver process is running in normal user process priority, not boosted for real time.

We use C++ for both endpoints, the embedded Arduino code and the receiver, but the C++ on the Arduino side runs just as fast as the same loop in Arduino sketch language. Python low-level reads are generally able to handle this same level of throughput with ease too, so it is not likely that your hardware or speed goals that are the problem.

I can see a few design issues right away.

Don't use libraries for what one can do in just a few low level lines of code.
Don't place numbers in strings. Keep them as numbers.
Send the numbers as messages placed carefully into byte arrays using bitwise operations.
Don't convert raw samples to voltages on the Arduino. That can be done in the receiver or elsewhere on the Linux side.
Most importantly, find the various code examples that people posted on the Arduino blogs when testing USB baud rates (speed).

The lab engineers started with that speed testing code, replicated the throughput published with it, and then added A-to-D conversion and other features one step at a time.

It is recommended that you place the code under version control and then, with each change, test the speed again. That way you'll notice any bottleneck you introduce immediately and can see the exact changes that must have caused it.


Can I short this code? int r = 12;
int g = 11;
int b = 10;
int sw = 4;
int x;
int c = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

void loop() {
    x = digitalRead(sw);
  if(x==HIGH) {
    delay(250);
    c++;
    if(c==1) {
        digitalWrite(r, HIGH);
        digitalWrite(g, LOW);
        digitalWrite(b, LOW);
       {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }

    }
    else if(c==2) {
        digitalWrite(r, LOW);
        digitalWrite(g, HIGH);
        digitalWrite(b, LOW);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
        else if(c==3) {
        digitalWrite(r, LOW);
        digitalWrite(g, LOW);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
        else if(c==4) {
        digitalWrite(r, HIGH);
        digitalWrite(g, HIGH);
        digitalWrite(b, LOW);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
            else if(c==5) {
        digitalWrite(r, LOW);
        digitalWrite(g, HIGH);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }

    }
            else if(c==6) {
        digitalWrite(r, HIGH);
        digitalWrite(g, LOW);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        c=0;
      }

    }

  }
}

int r = 12, g = 11,b = 10, sw = 4, x, c = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

void loop() {
  x = digitalRead(sw);
  if(x==HIGH) {
    delay(250);
    c++;
    if(c==1)      setRGBandBlink13(HIGH,LOW,LOW,1);
    else if(c==2) setRGBandBlink13(LOW,HIGH,LOW,2);
    else if(c==3) setRGBandBlink13(LOW,LOW,HIGH,3);
    else if(c==4) setRGBandBlink13(HIGH,HIGH,LOW,4);
    else if(c==5) setRGBandBlink13(LOW,HIGH,HIGH,5);
    else if(c==6){
      setRGBandBlink13(HIGH,LOW,HIGH,6);
      c=0;
    }

  }
}

void setRGBandBlink13(bool newR,bool newG,bool newB,int times){
  setRGB( newR, newG, newB);
  blinkPin13(times);
}

void setRGB(bool newR,bool newG,bool newB){
  digitalWrite(r, newR);
  digitalWrite(g, newG);
  digitalWrite(b, newB);
}

void blinkPin13(int times){
  for(int i=0;i<times;i++){
    digitalWrite(13,HIGH);
    delay (250);
    digitalWrite(13, LOW);
    delay (250);
  }
}


Minimum value I2C-pull up resistor for arduino I'm trying to determine the minimum value of pull resistor for Arduino Uno

The datasheets says for arduino; VOL = 0,4 for IOL = 20 mA. (VDD = 5V)

For formula for calculation of minimal pull-up is: Rmin=Vcc−0.4V/20mA = 4,6V / 20mA = 230 ohms.

But I saw that people use 0,4V for 3mA. Than the minimal value is 1,6K ohms.

So whats the minimum value of pull-up for arduino?

(also my slave has 0,4 Vol for 20 mA IOL)

The full datasheet of the atmega328p can be found here: https://www.microchip.com/wwwproducts/en/ATmega328P.
It is called "ATmega328/P AVR MCU with picoPower Technology Data Sheet".

In section "32.7 Two-Wire Serial Interface Characteristics" in table 32-10 on page 372 it shows different voltage levels for the input.

On page 110 it says: "When the TWEN bit in TWCR is set (one) to enable the 2-wire Serial Interface, pin PC4 is disconnected from the port and becomes the Serial Data I/O pin for the 2-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation".

I wrote here before that the i2c (the twi hardware inside the microcontroller) did not use the digital pin hardware. However, the i2c pins can still sink a lot of current. Thanks to @Berkay for noticing the same behaviour of the sink current as a normal digital pin.

According to the datasheet the atmega328p of the Arduino uno might not use the digital pin hardware for i2c. It is not known if the same mosfet circuit is used with the same (large) sink current. Perhaps the chip uses a similar mosfet circuit with added slew rate for the output and added spike filter for the input. Perhaps the same mosfet of the digital pin is used after all.

In the Arduino sketch, calling Wire.begin turns on the dedicated i2c hardware in the atmega328p chip. The sink current and voltage levels are according to the i2c specifications.
As you can see in the i2c tutorial by Nick Gammon, the Arduino can sink more than 3 mA.

When the pullup resistors are too low, for example for a sink current of 4 mA, the Arduino uno can handle that, but the slave might not.

When all the pullup resistors are combined, the required sink current can be calculated. The maximum is 3 mA to meet the i2c specifications. To compensate for wire capacitance the i2c bus speed can be lowered.

The i2c bus is not ment to go into a cable, it is not ment for long wires. A cat6 cable is 46 pF/m. That means your 800 pF is for 17 meters cable? That is not what the i2c bus is for. It is for 17 centimeters. The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz i2c bus.


Pushing sketches to pro mini with Uno 101 So I just bought a Pro Mini the other day, however, I didn't get an FTDI cable or a USB/Serial converter board.
From what I understand from this article I can use my Arduino Uno 101 to push sketches onto the Pro Mini.
The wires are all hooked up (grounded reset on the Uno) and I have uploaded the sketch to disable the serial communication port on the Uno, however, when I try to push a sketch to the Mini it errors out with the following message
Arduino: 1.8.3 (Windows Store 1.8.6.0) (Windows 10), Board: "Arduino Pro or Pro Mini,
ATmega328 (5V, 16 MHz)"

Sketch uses 928 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM3": The system cannot find the
file specified.

Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

The only part of the suggested troubleshooting guide that maybe applicable is the drivers section.

Drivers
The Arduino Uno and Mega 2560 use standard drivers (USB CDC) provided by the operating system to communicate with the ATmega8U2 on the board. Other Arduino boards use FTDI drivers to communicate with the FTDI chip on the board (or in the USB-serial convertor).

I could be wrong but to me it doesn't seem like the second sentence applies to this situation since the the Uno sits between the pc and the mini. However, when I check the windows device manager I can see that the Uno is connected on a COM port, but nothing about the Mini. Though I am not sure that it should show up.
I am using the IDE(1.8.3) to program and "Arduino Pro or Pro Mini" as the board. Though Tools>Port is greyed out when I have this board selected.

There is no "Arduino Uno 101" there are only "Arduino Uno" and "Arduino 101".

101 uses completely different hardware, and tricks to use an Uno as an USB to UART adapter won't work on an 101.

101 has also separate serial interfaces for USB serial (Serial) and hardware serial (Serial1).

If you have have an Arduino 101 you can solve this by software means.
The board needs to be able to change the baud rate and use DTR for reset.

There is a sketch from PaulStoffregen on GitHub that does that.

/* USB to Serial - Teensy becomes a USB to Serial converter
   http://dorkbotpdx.org/blog/paul/teensy_as_benito_at_57600_baud

   You must select Serial from the "Tools > USB Type" menu

   This example code is in the public domain.
*/

// set this to the hardware serial port you wish to use
#define HWSERIAL Serial1

unsigned long baud = 19200;
const int reset_pin = 4;
const int led_pin = 13;  // 13 = Teensy 3.X & LC
                         // 11 = Teensy 2.0
                         //  6 = Teensy++ 2.0
void setup()
{
  pinMode(led_pin, OUTPUT);
  digitalWrite(led_pin, LOW);
  digitalWrite(reset_pin, HIGH);
  pinMode(reset_pin, OUTPUT);
  Serial.begin(baud);       // USB, communication to PC or Mac
  HWSERIAL.begin(baud);     // communication to hardware serial
}

long led_on_time=0;
byte buffer[80];
unsigned char prev_dtr = 0;

void loop()
{
  unsigned char dtr;
  int rd, wr, n;

  // check if any data has arrived on the USB virtual serial port
  rd = Serial.available();
  if (rd > 0) {
    // check if the hardware serial port is ready to transmit
    wr = HWSERIAL.availableForWrite();
    if (wr > 0) {
      // compute how much data to move, the smallest
      // of rd, wr and the buffer size
      if (rd > wr) rd = wr;
      if (rd > 80) rd = 80;
      // read data from the USB port
      n = Serial.readBytes((char *)buffer, rd);
      // write it to the hardware serial port
      HWSERIAL.write(buffer, n);
      // turn on the LED to indicate activity
      digitalWrite(led_pin, HIGH);
      led_on_time = millis();
    }
  }

  // check if any data has arrived on the hardware serial port
  rd = HWSERIAL.available();
  if (rd > 0) {
    // check if the USB virtual serial port is ready to transmit
    wr = Serial.availableForWrite();
    if (wr > 0) {
      // compute how much data to move, the smallest
      // of rd, wr and the buffer size
      if (rd > wr) rd = wr;
      if (rd > 80) rd = 80;
      // read data from the hardware serial port
      n = HWSERIAL.readBytes((char *)buffer, rd);
      // write it to the USB port
      Serial.write(buffer, n);
      // turn on the LED to indicate activity
      digitalWrite(led_pin, HIGH);
      led_on_time = millis();
    }
  }

  // check if the USB virtual serial port has raised DTR
  dtr = Serial.dtr();
  if (dtr && !prev_dtr) {
    digitalWrite(reset_pin, LOW);
    delayMicroseconds(250);
    digitalWrite(reset_pin, HIGH);
  }
  prev_dtr = dtr;

  // if the LED has been left on without more activity, turn it off
  if (millis() - led_on_time > 3) {
    digitalWrite(led_pin, LOW);
  }

  // check if the USB virtual serial wants a new baud rate
  if (Serial.baud() != baud) {
    baud = Serial.baud();
    if (baud == 57600) {
      // This ugly hack is necessary for talking
      // to the arduino bootloader, which actually
      // communicates at 58824 baud (+2.1% error).
      // Teensyduino will configure the UART for
      // the closest baud rate, which is 57143
      // baud (-0.8% error).  Serial communication
      // can tolerate about 2.5% error, so the
      // combined error is too large.  Simply
      // setting the baud rate to the same as
      // arduino's actual baud rate works.
      HWSERIAL.begin(58824);
    } else {
      HWSERIAL.begin(baud);
    }
  }
}

Then you need to connect:

Arduino 101  |  Arduino Pro Mini
-------------+------------------
VCC          |  VCC
GND          |  GND
TX           |  RX
RX           |  TX
PIN 4        |  DTR

After that you can use the port as a Arduino Pro Mini programmer.


Arduino Nano not responding with yellow led blinking fast Update: I started playing with a genuine Deumilanove and exactly same problem happened to it - d13 led blinking, but avrdude says stk500_recv(): programmer is not responding

I uploaded a largish sketch ~15kb to Arduino Nano v3.0 (clone) and that left the board in an unusable state. When connected to USB, a power LED goes on immediately and 1-2 seconds later the yellow "L" starts blinking really fast.
Here's the board I use, it's a cheap clone, but it worked really well before today.

Now, when I try to upload a new sketch I get an error:

avrdude: stk500_recv(): programmer is not responding

I tried making and ISP programmer out of genuine Duemilanove, using nano's ISP pins and tried following official instructions (didn't use any capacitors/resistors).
Either way when I click "Burn Bootloader" result is the same error:

avrdude: stk500_getsync(): not in sync: resp=0x15

I have connected "debug" leds to D7,8,9 and heartbeat fades in and out in idle, others stay dark.
When I click "Burn Bootloader" all leds go dark then it does few quick blinks on 7, then similar pattern for 8, and then heartbeat resumes. Sometimes this sequence is repeated twice.

I also tried editing preferences.txt to bypass bootloader, but that didn't help.

How do I restore this board or do a low level reset?
It seems to be in some failure mode, with pin 13 oscillating, but I don't know what that means.

I successfully restored both boards using the reset button:

Power off the board (I disconnected the USB cable from computer)
Press and hold the reset button
Connect USB cable (keep holding the reset button)
Click "Upload Sketch"
Wait a second or two until Arduino software says "Uploading..." in the status bar
Release the reset button

Use these steps to upload any small sketch, Blink example is a good choice.


Reading I2C registers as slave device I need to read the registers of a message gotten from onReceive(). I read here that

There's nothing "magic" about the register pointer:  it's simply the first data byte in the packet.  So just write your I2C slave code so it examines the first received byte and treats it as an "opcode" for deciding how to interpret the rest of the packet.

So I thought that since hosts set registers by calling write() twice, I could just make my onReceive() handler function twice, like this
byte CURRENT_REGISTER = 0x00;

void onMessage(int numBytes){
  if(CURRENT_REGISTER == 0x00 && numBytes == 1){
    CURRENT_REGISTER = Wire.read();
    return;
  }

  char msg[numBytes];
  for(int i = 0; i < numBytes; i++){
    msg[i] = Wire.read();
  }

  //logic function goes here

  CURRENT_REGISTER = 0x00;
}

But then i noticed here that

This first byte written here 'r' moves the register pointer to the register with address 'r'. You can think of the pointer as a read/write head.
Now that the pointer is 'pointing' at the specific register you wanted, this command will replace the byte stored in that register with the value 'v'.

which made me think after endTransmission(), it only sent one message, which would ruin this idea.
Is this the case, and if so how can I obtain the registers as a slave?

I just realized, what your actual question might be, so I'm prepending this to my answer:
With I2C and the typical register communication protocol, you have 3 communication patters:

Master wants to write:

Master does transmission with first byte being the address of the register and following bytes being the data, that should be written to the addressed register (and following registers)

Master wants to read:

Master does a 1 byte transmission with the address of the register, that is wants to read
Master starts a request for 1 or more bytes and the slave will send the previously requested register (and following registers, until no more bytes are available or requested)

Some devices have sequential reads. For these devices the register address is not reset, when an operation is done. Thus the master could do more requests and read more data from the registers. Here the current register address is incremented on each read.

This means, that a master write cycle has only 1 transmission (only 1 endTransmission() in the master code), since every first byte in a master send transmission is handled as a register address. Your code snippet does not allow that. To solve that, just remove the check of numBytes and the return statement.

As mentioned in the comments, your question is really unclear. It seems you are asking things, that doesn't really make sense in the context of general I2C communication. So I will go over the basics and then point you in a good direction to solve your problem interfacing the Wiimote as peripheral.
The I2C protocol: This is the general communication protocol, that the Wiimote uses for its peripherals. It uses 2 lines and a master-slave structure. That means, that any communication is controlled by the master (the Wiimote in this case) and the slave (the peripheral, like a Motion+, a Nunchuk or your Arduino) cannot do anything by itself. The I2C protocol has markers for the start and end of a message and can address each slave on the bus with its specific address (which is send before the data). The protocol does NOT include any rules about the content of each message. So when writing code with the Wire library (the Arduinos library for interfacing the I2C hardware), you only get a buffer full of data bytes. It is up to you to interpret these bytes as needed for your application.
Data structure protocol: This protocol is imposed onto the data, that is end via I2C, so this is a higher level of abstraction and does not really have much to do with the I2C interface (you could use this data structure protocol with any binary communication interface, that has the concept of separated data packages). The data structure protocol defines the logic of the communication.
Here the registers come in. I2C is often used to interface simple sensor chips. These chips work by reading and writing to their internal memory. So the I2C interface exposes this internal memory to the master, who can now configure the sensor by writing data to the internal memory of the sensor, or read data from it.
An example: Lets imagine a simple distance sensor. It has 2 bytes/registers of internal memory. The first byte/register is for configuration of the sensor; the second byte/register represents the measured distance. The common communication protocol for such a chip can be:
Master sends the address of the register, that it wants to access
if Master wants to write to the register
    Master sends bytes to the slave
    Slave saves bytes into previously chosen register (and following registers)
if masters wants to read form the register
    Master requests X bytes from the slave
    Slave sends X bytes with the content of the previously chosen register (and following registers)

The I2C master now wants to configure the sensor (for example setting the measurement frequency), thus writing a corresponding byte to the first byte/register. It will first send the address of the configuration register to the slave, which is 0 (first byte/register). Then it will send another byte, which is the new value of the configuration register.
Then our I2C master wants to read the distance measurement the sensor. For this it first sends the address of the register, that holds the distance measurement (1 aka second byte/register). Then it will request 1 byte from the slave. The slave will then send the content of the previously chosen register (register 1 aka distance measurement register).
So for the slave, the first byte of a Master send transmission is to be handled as a register address. More complex slave classes might have a 16bit (2byte) register address or even more.

Now to your problem mimicking a Wii Motion+. The description on the site, that you linked to is rather difficult. Unfortunately I cannot help much with that. But you can try to use an already existing library, that mimics a Wiimote peripheral: Arduino-Wiimote
I cannot guarantee, that is will work, but it is definitely a good start. If you don't want to use a library, but implement this yourself, you can still learn from how the library does it.
With more searching (for term combinations like "github wiimote arduino") you might find more libraries for this. I have only invested a limited amount of time.


Using a lot of interrupts on a single Arduino I'm doing a little project that requires a lot of sensors. Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16 (for me that's a lot).
So, I have an Arduino MEGA 2560, and I'm new to Arduino (Had a little experience with PIC before).

I've started my project with buttons and leds to simulate the sensor, but my sensors work normally HIGH, and when something pass in front of it, it goes quickly to LOW and back. English is not my first language so I don't recall the name of this sensor, kind of like movement sensor(?).

A lot of stuff pass normally, up to 50/s, in front of it, so it should keep "bouncing" between HIGH and LOW. But when I changed the buttons for the sensors, sometimes my processor won't react, and I think it's because the signal goes back to HIGH before the code reads it. Maybe it's not a problem when it's sensing lot of things, but I can't test it right now with a lot of sensors, and it's not something that can keep getting errors.

So I got to interrupts, reading the awesome gammon review. I understood a lot of new things that i didn't know and I searched for a interrupt Library, but the one I found can't use too many sensors.

I forgot to tell, but I'm using a touch 2,4" shield too, so a lot of interrupts pins can't be used.

Will I be able to use all the sensors I want? If not, could I do it with 2 Arduinos and 1 screen? Am i missing something about the interrupts? Where can I find something to help me?

Edit 1: All the sensor are the same

On a Uno, all of the digital and analog pins can trigger a pin-change interrupt. That gives you 20 inputs straight away. The Mega also has pin change interrupts but not on all its pins. The pins that the Mega supports for pin-change interrupts are documented on the Software Serial page.

  Not all pins on the Arduino Mega and Arduino Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

(Note that the Atmega2560 chip itself supports more pin change interrupts, however those extra ones are not brought out to header pins on the Arduino board).

That's still quite a few (18 if I counted correctly). Plus the hardware interrupt pins: 2, 3, 18, 19, 20, 21.

  Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16

To reach 60 you probably want an input shift register such as the 74HC165 - you can daisy-chain them together to get lots of inputs. However you would have to poll to see if pins changed.

Otherwise you could use something like the MCP23017 chip, which has 16 input/output pins, and supports interrupts. You can use 4 of them (interfacing with I2C) and thus get 64 inputs. There is a shield that has 4 of those chips on it:

With suitable software (see my page about I2C) you could configure for interrupts and read any of those 64 inputs when they change.

  Do I have to keep checking all the time for every sensor one by one?

No, because you can configure the interrupts as open-drain, which means you can connect them all together (if you want to). Or, you could bring out the interrupts for the 4 x MCP23017 chips to four interrupt inputs on the Mega (that narrows down for you which chip caused the interrupt). Then you can read the chip's register(s) to find the state of the pins - either at the time of the interrupt, or right now.

However you might find that it is actually faster to just poll the chips (say) 100 times a second. There is some overhead to using I2C, you can also get SPI versions of that chip (MCP23S17) which would operate a bit faster.

Alternatively, the 74HC165, whilst simpler, could also turn out to be overall faster if you just poll rapidly.

  And the sensor sense a lot of movement per second, won't that cause trouble for the Arduino?

You need to define "a lot" and "trouble". You won't do billions of read a second. You can probably do thousands. What would you do with thousands of readings anyway? The time taken to process them would probably be the limiting factor.

  At the same time I'm using a GPS, no problem for the usage of Serial and I2C together right?

No problem, because serial input is interrupt-driven. Within reason, you can do both at once.


Serial.read() always returns 255 So I'm trying to learn basic Android app dev. My master plan was to make an app using MIT App Inventor that would turn on an LED over Bluetooth using an Arduino. Once I verified that everything worked, I would write the entire app from scratch using Android Studio. This way, when I inevitably run into bugs with my written-from-scratch app, I could say with 100% certainty that the issue is in my Android code and not hardware/Arduino related.

So I'm having trouble right now. I have two separate LED circuits, a blue LED from port 13 and a green LED from pin 8. I verified that both circuits are working properly by using the Blink code, so I know the issue is definitely not with the LED circuits.

I'm using an HC 06 Bluetooth module. The pins are connected as follows:

HC 06 -> Arduino

RX -> TX

TX -> RX

5V -> 5V

GND -> GND

Here is the Arduino code:

#include <SoftwareSerial.h>

SoftwareSerial bluetooth(0,1);
int ledblue = 13;
int ledgreen = 8;
int tx = 1;
int rx = 0;
int type;

void setup() {
  Serial.begin(9600);
  //bluetooth.begin(9600);
  pinMode(ledblue, OUTPUT);
  pinMode(ledgreen, OUTPUT);
  pinMode(tx, OUTPUT);
  pinMode(rx, INPUT);
  allpinslow();
}

void loop() {
  int i = 0;
  int m = 0;
  delay(500);
  if (Serial.available() > 0) {
    while(Serial.available() > 0){
      type = Serial.read();
      Serial.println(type);
    }
    Check_Protocol(type);
  }
}

void allpinslow()
{
  digitalWrite(ledgreen, LOW);
  digitalWrite(ledblue, LOW);
}

void Check_Protocol(int inStr) {
  int i = 0;
  int m = 0;
  if (inStr == '0') { //Led Off equals("2off")
    allpinslow();
  }
  if (inStr == '1') { //Led on
    digitalWrite(ledblue, HIGH);
  }
  if (inStr == '2'){
    digitalWrite(ledgreen,HIGH);
  }
}

Here is the MIT App Inventor block code

If I press the Green or Off button, the Serial Monitor spits out 255. If I press Red, nothing shows up on the serial monitor. I'm a bit dumbfounded on what is broken so I would greatly appreciate any help I can get.

Edit: @Delta_G here is the modified code

#include <SoftwareSerial.h>
int ledblue = 13;
int ledgreen = 8;
SoftwareSerial mySerial(2,4); //RX, TX
int type;

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(ledblue, OUTPUT);
  pinMode(ledgreen, OUTPUT);
  allpinslow();
}

void loop() {
  int i = 0;
  int m = 0;
  delay(500);
  if (mySerial.available()) {
    while(mySerial.available()){
      type = mySerial.read();
      Serial.println(type);
    }
    Check_Protocol(type);
    //Serial.println(inSerial);
  }
}

void allpinslow()
{
  digitalWrite(ledblue, HIGH);
  digitalWrite(ledblue, LOW);
}

void Check_Protocol(int inStr) {
  int i = 0;
  int m = 0;
  if (inStr == '0') { //Led Off equals("2off")
    digitalWrite(ledblue, LOW);
    digitalWrite(ledgreen, LOW);
  }
  if (inStr == '1') { //Led on
    digitalWrite(ledblue, HIGH);
  }
  if (inStr == '2'){
    digitalWrite(ledgreen,HIGH);
  }
}

If you are using Serial then you can't use pins 0 and 1 for something else as those are the hardware serialpins. Pick different pins for the Bluetooth.


How can I have 2 differents frequency on the 2 DAC outputs on an Arduino Due? I would like to blink, using specific waveforms, 2 LED controlled by the 2 DAC output of the Arduino Due.

I wrote this :

    #include "Waveforms.h"

    int i = 0;
    int sample;

    void setup()
{
      analogWriteResolution(12);
}

    void test(float fq, int wave1, int wave2)
{

      sample = ((1/fq)*1000000)/120;

      analogWrite(DAC0, waveformsTable[wave1][i]);
      analogWrite(DAC1, waveformsTable[wave2][i]);

      i++;

      if(i == maxSamplesNum)
          {
            i = 0;
          }

      delayMicroseconds(sample);

}

    void loop() {
    // 10 Hz, 0 is a sine wave on DAC0, 3 is a square wave on DAC1

      test(10, 0, 3);

I would like to be able to change the frequency of each output (1Hz - 100 Hz) using differents waveforms. Changing waveforms is ok and it works, but is it possible to also change the frequency so to have two differents output frequency on each DAC output ?

The goal is to have, for example, simultaneously :

1 Hz, sine wave on DAC0.
10Hz, square wave on DAC1.

Thanks a lot.

I don't have experience with this, but what you can do is:

If the frequency of DAC1 is x times faster than DAC2 to calculate the delay time based on the fastest and for DAC1 changing in every loop, while changing DAC2 only every DAC1/DAC2 times.
Vice versa if DAC2 is x times faster than DAC1
However, if there is not a simple ratio between DAC1 and DAC2 than you have to use the fastest speed of the two and use for the slowest an approximation...
Or use a higher significant fixed speed for i use a simple linear approximation between two points of the wavetable.

E.g. assume the speed is 10 times too fast for DAC1.
Suppose i = 100.. you should use the following points in the waveform: wave[100/10] and wave[100/10 + 1], so two consecutive points.
Assume the first is 10.0 and the second is 20.0... for the 10 increases of i (because i is running 10 times too fast) you can calculate for values of

 i     : 10.0 +   0% of (20.0 - 10.0)
 i + 1 : 10.0 +  10% of (20.0 - 10.0)
 ...
 i + 10: 10.0 + 100% of (20.0 - 10.0)

etc.

Note this is called linear interpolation.

You would have to check how many numbers per wave form table you need to get good values for different frequencies/speeds and what 'fixed' frequency you need to use for the delay.


Calculate Timezone from GPS Coordinates I have a uBlox NEO-6M GPS module and it is outputting longitude and latitude. It is also outputting time which is UTC. I want to use the GPS coordinates to calculate the timezone and then subtract and add hours based on that. Is it possible in any way? I know I can do this using WiFi but I want to use GPS to do it.

Timezones are political constructs, same as summer/winter time switch rules.
You'd need a map to look up the country/region and its current local time zone.
Your commercial car satnav is probably/perhaps equipped with such map information.


How do I repurpose Arduino's reset button Is there a way to repurpose the reset button for the code, like an on-board button? I don't need it to reset, but it would be useful to make it run through a list of RGB LED cycles.

If you just want the reset button to change the program mode, the
simplest thing would be to let the button reset the Arduino and switch
modes each time your program restarts. Then you do not need to change
the fuses or get a high voltage programmer. The code would look like
this:

void setup()
{
    // At startup, switch to the next mode.
    if (++mode >= NUMBER_OF_MODES) mode = 0;

    // etc...
}

There is just a small issue here: when the program starts, all the
global variables (like mode above) are supposed to be initialized by
the C runtime. This can be avoided by using a non-standard feature of
gcc: if you request the variable to be stored in the special .noinit
section, then it will not be initialized. Here is the program I used to
test this idea:

const unsigned int NUMBER_OF_MODES = 5;

__attribute__((section(".noinit"))) unsigned int mode;

void setup()
{
    // At startup, switch to the next mode.
    if (++mode >= NUMBER_OF_MODES) mode = 0;

    Serial.begin(9600);
    Serial.print("Current mode: ");
    Serial.println(mode);
}

void loop() {}

Now, each time I press the reset button, it goes to the next mode among
(0, 1, 2, 3, 4). The main drawback compared to using a regular input is
the delay added by the bootloader, which is slightly more than one
second.

A word about the cold boot initialization: the RAM is not initialized
by the hardware and contains essentially random bits. This means you
cannot count on mode having initially a valid value. This is why:

I am testing for ++mode >= NUMBER_OF_MODES rather than
++mode == NUMBER_OF_MODES, as the initial mode could be way larger
than NUMBER_OF_MODES
mode is an unsigned integer, otherwise I would need to also test for
it being negative.