Grab keys from an ordinary USB keyboard Arduino USB
I want to write an Arduino Sketch (if there is no other possibility it can also be plain c) , to grab keyboard inputs from my ordinary USB keyboard. Preferably without expensive hardware, but as mentioned, if there is no other possibility, this will do it too.
Is this possible with V-USB? I looked a their website, but it seems like this only supports being slave and to imitate a keyboard.

As suggested in the comments, you have two options:

As suggested by Majenko, you can use the Arduino USB Host Shield:

Alternatively you could use a PS2 keyboard instead (as suggested by Gerben). Arduino already has a library to handle PS2 keyboards, so the implementation of it would be easy. For reference (and example program)
playground.arduino.cc/Main/PS2Keyboard

If you do not have access to a PS2 keyboard or just want to use a USB keyboard, Gerben further suggests that most USB keyboards can be converted to PS2 keyboards with an adapter:

The keyboard must be able to support both formats (USB & PS2).

The following webpage shows the connections needed to go from USB to PS2:  USB to PS/2 adapter pinout


Converting UNIX Time There is a ANSWER to this question on this site: "Convert to and from Unix Timestamp"  The ANSWER includes a code example.  In the code example
there is an array named "days[][]".  What is this or where is this declared and populated?

Mike, After looking at the question you are referring to (Convert to and from Unix Timestamp) your question makes a lot more sense.

That code is incomplete and its difficult to be certain what anything is for.  My best guess is days[][] would look like this:

byte days [4][13] =
{
    {366, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {365, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {365, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {365, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
}

I derived this from:

  for (year=3; year>0; year--)     // 3 to 0 is a 4 year cycle, which looks like leap year checking.
  {
      if (epoch >= days[year][0])  // Checking the epoch against the first element in the array, which implies that's number of days per year.
          break;
  }

And the other elements in the array I guess from this

  for (month=11; month>0; month--)
  {
      if (epoch >= days[year][month])
          break;
  }

However The above way trades storage for performance, it uses 52 bytes to hold the days[][] rather than use extra CPU cycles.  A less storage intensive version would be:

byte daysInMonth = 31;
if (month == 2)
{
  if (year%4 == 0)
    daysInMonth = 29;
  else
    daysInMonth = 28;
}
else if (month == 4 || month == 6 || month == 9 || month == 11)
{
  daysInMonth = 30;
}


AT command is not responding on serial monitor I am trying to send AT commands to ESP8266. I re-flashed ESP8266 http://imgur.com/a/J8Ueh I followed this tutorial http://remotexy.com/en/help/esp8266-firmware-update/ and I hope it re-flashed successfully as there was no error.

When I uploaded this program http://www.pastebin.com/frhZY7tD I am trying to run AT command at 9600 baud rate on serial monitor then no response..

Below is how my circuit looks like

#include "SoftwareSerial.h"

SoftwareSerial esp8266(2, 3); // RX, TX

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(9600);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer
    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}

Trying to execute AT command -

On clicking on send button then it shows empty response like below -

When I unplug power wire and plug it back then it prints some garbled message on serial monitor. I checked voltage on RX also, it was around 3.5V that seems also OK.

I am facing this issue after I flashed WiFi firmware to ESP8266 then back AT firmware. It seems that AT firmware was not flashed successfully so I tried to erase everything using below command.

  esptool.py --port /dev/ttyUSB0 erase_flash

C:\Users\williams>esptool.py --port COM4 -b 9600 erase_flash
esptool.py v1.3
Connecting...................

A fatal error occurred: Failed to connect to ESP8266: Timed out waiting for pack
et header

Before execute above command, I made changes in my circuit like below :-

Update

I have re-flashed ESP8266 on 115200 baud rate, and uploaded empty program then it started to respond AT commands. I connected as like above only change is TX to TX and RX to RX respectively. Alright!

AT

OK
AT

OK
AT+GMR

AT version:0.50.0.0(Sep 18 2015 20:55:38)
SDK version:1.4.0
compile time:Sep 18 2015 21:46:52
OK

Well, I want to send AT commands from the Arduino serial monitor window to ESP8266 and print ESP8266 response to the command. When I upload above program then it stops to respond, same result as like empty screen this is weird. Isn't ?

The ESP's AT firmware is probably configured for a higher baud rate, 115200 is typical. SoftwareSerial only works reliably up to 9600 baud. It can transmit "reliably enough" at 115200 for you to blindly send change-baud commands, though the ESP's response will probably be garbled. So you need to either: Reduce the ESP's baud rate or use the Uno's hardware serial port for the ESP, which means giving up the Uno's terminal output and makes it a pain to reconnect your PC each time you need to update the Uno's code. I've described the process of changing the ESP's baud-rate in more detail in
this answer.

Update: I'm not familiar with various AT comand-interpreter revs; my ESPs are all running with the firmware rev came on them; "AT+GMR" (show version info) replies:

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

There is no AT+CIOBAUD command listed in my ESP8266 AT Instruction Set document rev 1.5.3). The only one listed that affects baud rate - and the one I  use - is:

AT+UART_DEF=<baud>,<databits>,<stopbits>,<parity>,<flowcontrol>

, or:

AT+UART_DEF=9600,8,1,0,0

for 9600 baud, 8 bits, 1 stop-bit, no parity, no flow control. You probably know, but just in case, note that you will lose communication immediately after you change the ESP's baud rate, until you then change the local baud rate to match.

Update2:

  This is program pastebin.com/dquCNYJj I am not sure what wrong I am
  doing

That code sets SoftwareSerial to 115200 baud; it can not run fast enough to receive data at that speed.

Update 3:

Since you've updated the ESP's firmware unsuccessfully, it's hard or impossible to know what's going on. The output in your screenshot looks rather like the result of a baud mismatch between the ESP and your terminal. You need to get a clean firmware update to the ESP before you can expect it to respond correctly and rely on its output to diagnose any other problems.

Update 4:

I'm not sure if we're talking about the same thing so please forgive me if you already know this; we might be talking about (at least) three different baud-rates:

The rate in use during flashing of new firmware to the ESP;
The default rate that new firmware will start listening at, whenever it is booted;
The actual rate used at any given time between the ESP with its new firmware and the Arduino or some other device external to the ESP.

My own experience is with using the factory-installed AT Interpreter firmware. I have never needed to update it so I don't have personal experience with (1).

(2) and (3) are programmable by the Arduino. When I first use a new ESP (or after you've just re-flashed its AT Interpreter), it will listen at a factory-default baud rate (mine have all defaulted to 115200). There are commands to change the current rate (not saved across a reboot) and/or the default baud (saved for all future sessions).

I almost always change its default rate to 9600 to use it with an Arduino software serial port. This is my initialization for a new device, using an Arduino to talk to the ESP. (Don't transmit my '#...' comments):

# Start talking at the ESP's default rate (115200 on my factory-fresh ones).
AT+RST                         # Reset
AT+UART_DEF=9600,8,1,0,0       # Default baud to 9600,N,8,1,no flow ctl
# Here, change the Arduino's port to match: 9600 in this case.
AT+CWMODE=1                    # Station mode (client)
ATE0                           # Command echo off

From now on, the ESP will wake up listening at 9600 baud, in Station Mode as a client, with no command echo.


How can I make FastLED set every 2 LEDs to the same color? I'm controlling an WS2812 LED strip in which every 2 leds is controlled together - they are setup as "eyes" in a prop.  I'm looking to control hundreds of these, so in an effort to save RAM I'd like to have each byte in the LED color array represent 2 LEDs.  That is to say that when the FastLED library writes to the data lin I want it to duplicate every byte going out.

I've dug into FastLED code but get lost around the timings deep down in the code.

Any ideas?

The FastLED community appears to live at this reddit.com site. Consider asking your question there.
It is unknown if the following will exceed the current limitations of the Arduino platform you are using.  But, consider sending the same data to two different strings of LEDs simultaneously.  Briefly, each LED strips off the 1st packet of data and sends the balance of data through to the next LED.  Two different strips should behave the same if given the same data.  Thereby creating the effect you described (pairs of LEDs behaving the same).


NOT realtime MP3 decoder I know that MP3 is the most popular audio format out there, but I need to be able to convert them to wav files for bother project I'm working on. It can be done with a PC but I would like to know if there is a way of decoding a MP3 file and turning it into a pcm wav file on an Arduino. I don't want to use an extra chip, as I do not plan on playing the MP3s, just converting them.

The mp3 audio coding is not just one mathematical calculation. To decode every mp3 file you need a complete package and enough memory. That is not something for a simple arduino board.

There are libraries to decode for example a jpg file or a mp3 file. They have restrictions and you need a faster processor.
Adafruit has made a start: https://learn.adafruit.com/native-mp3-decoding-on-arduino/, but you need a powerful non-standaard arduino-compatible board. That library does not use I2S yet.

I suggest to use a Raspberry Pi.


Program Arduino Mega Adk on linux for a project my supervisor gave me a Arduino Mega ADK board (https://store.arduino.cc/arduino-mega-adk-rev3) and the usb-cable.

I only programmed a Atmega32 8 bit controller on linux ubuntu. I have no possibility to use windows (i heard it's easy to program the arduino using atmel studio). I can only use ubuntu 16.04. Is there a convient way to program the Arduino like a microcontroller?

I'm not aloud to use the highlevel Arduino libraries. I have to do a cascaded control for a dc-motor and sensor-fusion.

Thanks in advance.

If it's offtopic, could you transfer me to a suitable board?

You can use Eclipse, along with AVR-GCC and AVRDude and an AVR plug-in for Eclipse. Debugging may be a little painful since you don't have all the tools that Atmel Studio gives you. I'd question your employer if you aren't allowed to use the best (free) tools even if they do run on Windows.

Really all you need is the avr-gcc and avrdude to write software for it, you can use any text editor (although it isn't really convienent).  Seems like they are pigeon-holing you into a difficult job. Good luck.


Connecting Arduino Uno WiFi Developer Edition to the Internet I recently bought an Arduino Uno WiFi Developer Edition from here. Although all the other functionality appears to work (I’m able to upload/run programs, read sensors I plug in, etc.), I am not able to connect the Arduino to the internet. The Arduino has a built in ESP8266 chip which is compatible with the WiFi Link library, however, running ScanNetworks in the Arduino mac IDE (File > Examples > WiFi Link > ScanNetworks) doesn't work, nor does it print any errors. Other example files in that library don't work either. The CheckWiFiLinkFirmwareVersion program in the same library will print the welcome message "WiFi Link firmware check." but nothing after that.
I have tried every other WiFi library I could find in the library manager window (Sketch > Include Library > Manage Libraries), namely

Arduino Uno WiFi Dev Ed Library
WiFiEsp
WiFi101
WiFi

However, none of them work. Is the Arduino's WiFi chip defective, or am I doing something wrong? One reviews on the website that I bought the Arduino from said this (see lenny):

Arduino.org (which is different from arduino.cc) has not made software available to access the WiFi capabilities of this board. As far as I can tell, the wifi cannot be used. They keep saying that the software is coming soon.
See this thread on their forum: http://www.arduino.org/forums/uno/arduino-uno-wifi-arduinowifi-library-incomplete-solution-for-mqtt-tcp-udp-socket-communication-540

In summary, is the Arduino Uno WiFi Developer Edition known to be defective? If not, what am I doing wrong? If it is, could I potentially get a WiFi shield and use that instead of the built in chip? I have other shields for the Arduino (e.g. an SD card shield) that are working fine.

Do you have access to the Webgui?

with the Webgui you can configure the wifi settings.
you do not need to upload sketches for this.
It is a good test if there is no defect.

Connect your PC Wi-Fi or with your smartphone directly to the Aduino uno wifi.
Start your browser and type in the following IP: 192.168.240.1
and now you should see the WebGUI.


How to replace the delay() function in my code? I'm new to Arduino and I currently have a project that involves the control of an LED via ultrasonic sensor. Basically, if an object passes through the ultrasonic sensor, the LED will be ON for 5 seconds but adding another set of LED and ultrasonic sensor with the same function gives a problem because the other LED won't light up if the other one is ON and vice versa because of the delay whereas what I want is to be able to make them both light up and stay lit for 5 seconds after their respective ultrasonic sensors detect an object. I've tried using the "Blink without delay" example but I can't understand it nor make it work. Please help me guys and thanks for reading. Here is my current code:

int trigPin1=2;
int echoPin1=3;

int trigPin2=4;
int echoPin2=5;

int led1=10;
int led2=11;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   if (distance1 >= 500 || distance1 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print ( "Sensor1  ");
    Serial.print ( distance1);
    Serial.println("cm");
       }

  long duration2, distance2;
  digitalWrite(trigPin2, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2= (duration2/2) / 29.1;

  if (distance2 >= 500 || distance2 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor2  ");
    Serial.print(distance2);
    Serial.println("cm");
       }

  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }
}

The first set of delaymicroseconds for measuring is fine.

you'll want to replace the delay(5000) when switching the leds.

  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }

you can do that by using a timestamp of when the distance was last high:

  if(distance1<20){
    digitalWrite(led1,HIGH);
    timestamp1 = millis();
  }

  if(distance2<20){
    digitalWrite(led2,HIGH);
    timestamp2 = millis();
  }

if(millis() - timestamp1 > 5000){
  digitalWrite(led1,LOW);
}

if(millis() - timestamp2 > 5000){
  digitalWrite(led2,LOW);
}

timestamp1 and timestamp2 should be globals (or static locals). This code will delay turning off the led to 5 seconds after the sensor last detected something close.


Generating a short pulse after a delay I am trying to use one of the hardware timers on the arduino uno to generate a short pulse some number of microseconds after receiving a pulse on an input.

Currently my code looks like this:

uint16_t pulse_delay = 12000; //half-microseconds
uint16_t pulse_length = 20;

void setup(){
  pinMode(8, INPUT);
  pinMode(9, OUTPUT);
  TCCR1A = 0;
  TCCR1B = _BV(ICNC1)  //input capture noise cancel
      | _BV(ICES1) //positive edge
      | _BV(CS11); // /8 prescaler
  TIMSK1 = _BV(ICIE1); //enable input capture interrupt
}
void loop(){}
ISR(TIMER1_CAPT_vect){
  TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
  TIMSK1 |= _BV(OCIE1A); //enable match interrupt
  OCR1A = pulse_delay; //pulse begin time

  TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                        //the interrupt isn't run immediately
}
ISR(TIMER1_COMPA_vect){
  TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
  TCCR1A = _BV(COM1A1); //clear OC1A on match

  OCR1A = pulse_delay + pulse_length;
}

This code should theoretically do the task, but it doesn't produce any output at all - to my oscilloscope it looks like the output pin just stays low.

However, if I replace the last line (OCR1A = pulse_delay + pulse_length;) of the compare match interrupt with the following two lines, it outputs a pulse just fine. The issue with this is that it uses significantly more CPU time, and it can only count time from when the interrupt starts so if the interrupt is executed late the pulse will be longer.

  delayMicroseconds(pulse_length);
  TCCR1C = _BV(FOC1A); //manually trigger match event

All that the first version is doing differently is triggering the match event via an 'alarm' set on the timer, rather than waiting to trigger the match manually.

Why does the first version not work, and how can I make it work??

Expanding on my comment, after checking experimentally that this was
indeed the issue.

Short answer

You should do

TIFR1 = _BV(OCF1A);  // clear interrutp flag

right before

TIMSK1 |= _BV(OCIE1A);  // enable match interrupt

Explanation

Whenever the timer reaches the value stored in one of its “compare
match” registers, this triggers a “compare match” event, which has the
effect of raising the corresponding interrupt flag (OCF1A in your
case). If the associated interrupt is enabled, that fires an interrupt
request, and the flag is automatically cleared when the CPU starts
executing the interrupt vector.

However, if the interrupt is not enabled, the flag just stays set. If
you later enable the interrupt when the flag is already set, the
interrupt request is sent immediately. This is not what you want, you
want the interrupt to fire only on the next match. For this to happen,
you have to clear the interrupt flag prior to enabling the interrupt.

The interrupt flags have a very non-intuitive behavior: you clear the
flag by writing a logic one to it. Thus the line:

TIFR1 = _BV(OCF1A);  // clear interrutp flag

For completeness, I would also clear ICF1 before enabling ICIE1,
although this seems to not be critical for the working of your program.

Also, as a side note, be aware that the timer can increment while the
CPU is in the middle of executing TCNT1 = TCNT1 - ICR1;. If you want
the cleanest possible timings, leave the timer free-running and just set
OCR1A to the appropriate values: ICR1+pulse_delay, then
ICR1+(pulse_delay+pulse_length).


A knob that can be turned by hand, have the position read, and turned by software to another position? I'd like to be able to change variables on the Arduino by adjusting a set of knobs.  When I get to a desirable setting I'd like to be able to save those settings on the Arduino... and then I'd like to be able to load those settings back, and have the knobs turn themselves back to the correct positions.  Specifically I'm thinking of using this with a synthesizer.

I understand how to do all of this, except, I don't know if there are knobs that allow this type of behavior.

If you attach a knob to the Analog Feedback Micro Servo, either directly or via gears, then you can use the pot output to measure the current position and use the normal servo control protocol to turn it under software control.


How to write array of functions in arduino library? I've nine functions each of type void as follow:

void zero();
void one();
void two();
void three();
void four();
void five();
void six();
void seven();
void eight();
void nine();

I've put all these functions into an array pointer as follow (without any error):

typedef void (*num_func) ();
num_func functions[] = { zero, one, two, three, four, five, six, seven, eight, nine};

Now I'm writing an arduino library and wanting to achieve the same, but after hours of thinking I'm not able to achieve. Please help me how can I accomplish this in a library?

Thanks in advance.

This was a bit fiddly to get right. I got inspiration from How do I create and use an array of pointer-to-member-function?

Based on my post about Function pointers / function callbacks / function variables I modified it to work with class functions:

class foo {

  public:

   void doAction0 ()
    {
      Serial.println (0);
    }

    void doAction1 ()
    {
      Serial.println (1);
    }

    void doAction2 ()
    {
      Serial.println (2);
    }

    void doAction3 ()
    {
      Serial.println (3);
    }

    void doAction4 ()
    {
      Serial.println (4);
    }

   // typedef for class function
   typedef void (foo::*GeneralFunction) ();

   // array of function pointers
    GeneralFunction doActionsArray [5] =
    {
      &foo::doAction0,
      &foo::doAction1,
      &foo::doAction2,
      &foo::doAction3,
      &foo::doAction4,
    };

};  // end of class foo

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting"));

  // test instance of foo
  foo bar;

  for (int i = 0; i < 5; i++)
    {
    // get member function pointer from array
    foo::GeneralFunction f = bar.foo::doActionsArray [i];
    // call the function
    (bar.*f) ();
    }  // end of for loop

}  // end of setup

void loop () { }

This compiles OK and prints:

Starting
0
1
2
3
4

Amended answer

I was wondering why you needed to specify bar in this line above:

    foo::GeneralFunction f = bar.foo::doActionsArray [i];

The reason is that the code above had the array as non-static, and thus a copy belonged to each instance of the class. This doesn't make a huge amount of sense, so the modified code below makes the array static and const. That is, the array should be the same for every instance of foo and also never change.

Modified code below:

class foo {

  public:

   void doAction0 ()
    {
      Serial.println (0);
    }

    void doAction1 ()
    {
      Serial.println (1);
    }

    void doAction2 ()
    {
      Serial.println (2);
    }

    void doAction3 ()
    {
      Serial.println (3);
    }

    void doAction4 ()
    {
      Serial.println (4);
    }

   // typedef for class function
   typedef void (foo::*GeneralFunction) ();

   static const GeneralFunction doActionsArray [5];

};  // end of class foo

 // array of function pointers
const foo::GeneralFunction foo::doActionsArray [5] =
  {
    &foo::doAction0,
    &foo::doAction1,
    &foo::doAction2,
    &foo::doAction3,
    &foo::doAction4,
  };

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting"));

  // test instance of foo
  foo bar;

  for (int i = 0; i < 5; i++)
    {
    // get member function pointer from array
    foo::GeneralFunction f = foo::doActionsArray [i];
    // call the function
    (bar.*f) ();
    }

}  // end of setup

void loop () { }

This will also save RAM, as the array of function pointers only exists once, not once per instance of the class.


Arduino LCD Display 2x16 custom char byte limit Some years ago I stumble with a problem while using the 2x16 LCD. What happened was that there was a limit to how may byte arrays I could declare. So my project came to a halt because I needed to create more custom characters to advance any further...

The lcd accept custom characters to store them but I suppose there is a limit to this, am I wrong?

I'm trying to create a set of custom characters that move on screen. Since there are a lot of animations I need several of them to have a smooth animation. The problem resides in the limit of characters I can pre-establish after executing lcd.begin()

I don't post code because to my understanding that is not relevant and because sincerely is a crap since I wrote it down when I was learning programming some years ago. I want to resolve this so I can rewrite the code.

LCD version: QAPASS 1602A

Here is an example:

byte Ghost[8] = {
  0b00000,
  0b01110,
  0b01110,
  0b10101,
  0b11111,
  0b11111,
  0b11111,
  0b10101
};

lcd.createChar(0, Ghost);

So the right question is: Do I need to reset the LCD chip then declare the new characters to the lcd to make it available? How?

there was a limit to how may byte arrays I could declare.

If the problem was that you ran out of free RAM, then the fix is to move those byte arrays into program space.

Atmega 328 processors (Uno) are very RAM-limited. Fortunately you can assign constant data - fixed character strings, lookup tables for math, fonts, CRC calculation, etc - to be stored in program space which is much more generous. The upside is you can free lots of RAM in an application like yours that needs lots of constant data. The downside is that access to the data is a little bit slower:

// Definitions for data in program space
#include <avr/pgmspace.h>

// Place the character table in Flash
byte const Ghost[8] PROGMEM = {
   0b00000,
   0b01110,
   0b01110,
   0b10101,
   0b11111,
   0b11111,
   0b11111,
   0b10101
};

// Read a byte of character data
OneByte = pgm_read_byte(&Seg7_segtbl[index]);

Update:

  LCD version: QAPASS 1602

If that has an Hitachi HD44780 controller on it, its datasheetsays it has a 64-byte character RAM - more than enough for a full display of 2 x 16 unique characters, but if you need a wider choice of characters than a set of 64, you may need to re-load the RAM with a custom sub-set for any given screen-full. For animating, though, you'll probably need all of the individual parts of each animation in the LCD RAM at once; reloading during animation will most likely disturb the smoothness. One possibility is to load part of a subset between animation frames - if that's even possible. (I haven't studied this controller to that level of detail).


How do I find my 1N 4007 diodes? I am a beginner to Arduino, and a relative beginner to electronics in general. I have the official Arduino Starter Kit. I've looked through my bag of components looking for a black diode but was unable to find it among all of the LEDS & the other black components.

While the ArduinoStarterKit page at arduino.cc lists “5 Diodes [1N4007]” as part of it, and has a picture where 5 diodes apparently appear slightly left of center in the top row, several other pictures that come up in a google images search for official Arduino Starter Kit apparently don't show the diodes.  Eg, as at arduino starter kit.  But 4 Best Starter Kits for Arduino Beginners does show them.

Note, unless you are working with medium to high AC voltages (eg above 50 V) you can substitute 1N4001 - 1N4004 which have lower PIV ratings but also slightly lower forward voltage drop.  For many beginning projects, 1N4148 signal diodes will be adequate and perhaps less expensive.


Buffering data from EthernetServer clients I was trying to write a Telnet server that would be able to accept commands of sorts using the Arduino Ethernet library, and in order to access what the client was saying (to compare it to strings to check what command the client entered), I made a buffer string that would read until \n, which is part of the standard Telnet library. However, the string would never get printed to the serial connection (just for debugging purposes). Here's my code:

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xFE, 0xED };  // this client's MAC address

EthernetServer server(23);  // telnet is 23
boolean alreadyConnected = false;

void setup() {

  Ethernet.begin(mac);

  server.begin();  // open the socket

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial to start, Leonardo only
  }

  Serial.print("Connect to ");
  Serial.print(Ethernet.localIP());
  Serial.println(":23.");

}

void loop() {

  EthernetClient c = server.available();

  if (c) {
    String messageBuffer = "";

    if (!alreadyConnected) {
      c.flush();
      Serial.println("New client");
      c.println("test post, please ignore");
      alreadyConnected = true;
    }
    if (c.available() > 0) {

      char thisChar = c.read();

      //server.write(thisChar);

      //buffer until the client sends a new line
      if (thisChar == '\n') {
        Serial.println(messageBuffer);
        messageBuffer = "";
      } else {
        messageBuffer += thisChar;
      }
    }
  }
}

Most of this code was copied from the Telnet chat server example, but I changed the Serial.write(thisChar) line, because I wanted to put it into a string first. When this is run, and a user telnets to the IP, the Arduino prints New client, but when the user sends data, it doesn't print anything.

Any suggestions for what I'm doing wrong?

Well, I asked on the #arduino IRC channel, and realized my stupid mistake. I was setting the buffer to "" inside the loop.


Display values from a function on GLCD I am new to Arduino and I'm trying my first Pro Mini. I was able to find DS1302 code from github that runs perfectly. My problem is trying to add some LM35 code to also display temperature data as well as the time data.

The code doesn't seem to run the Celsius and Fahrenheit functions. I have attached my code. Any help will be appreciated.

//Required library - http://www.rinkydinkelectronics.com/library.php?id=5
//Blog Post - http://overskill.alexshu.com/ds1302-real-time-clock-w-arduino/

#include "U8glib.h"
#include <DS1302.h>
#include <PreciseLM35.h>
//int float pinLM35 = A0;
const int pinLM35 = A0;
PreciseLM35 lm35(pinLM35, DEFAULT);

DS1302 rtc(2, 3, 4);
U8GLIB_ST7920_128X64 u8g(13, 11, 12, U8G_PIN_NONE);

void setup(void) {
  rtc.halt(false);
  rtc.writeProtect(false);

  // The following lines can be commented out to use the values already stored in the DS1302
  // Once you flash the Arduino with the correct time.

  //rtc.setDOW(FRIDAY); // Set Day-of-Week to FRIDAY
  //rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(6, 8, 2010); // Set the date to August 6th, 2010

  // assign default color value
  if (u8g.getMode() == U8G_MODE_R3G3B2)
    u8g.setColorIndex(255); // white
  else if (u8g.getMode() == U8G_MODE_GRAY2BIT)
    u8g.setColorIndex(3); // max intensity
  else if (u8g.getMode() == U8G_MODE_BW)
    u8g.setColorIndex(1); // pixel on
}

void draw(void) {
  u8g.setFont(u8g_font_04b_03);
  u8g.drawStr( 2,5, "******************************");
  u8g.drawStr( 13,10, "Arduino Pro Mini Control ");
  u8g.drawStr( 24,20, (rtc.getTimeStr()));
  u8g.drawStr( 1,20, "TIME: ");
  u8g.drawStr(70,20,  "Temp (C): ");
  u8g.drawStr (80,20, (lm35.readCelsius()));
  u8g.drawStr( 25,30, rtc.getDOWStr());
  u8g.drawStr(70,30, "Temp (F): ");
  u8g.drawStr(3,30, "DAY: ");
  u8g.drawStr(80,30, (lm35.readFahrenheit()));
  u8g.drawStr( 24,40, rtc.getDateStr());
  u8g.drawStr(1,40, "DATE: ");
  u8g.drawStr(70,40, "AREF : ");
  u8g.drawStr(80,40, (lm35.readPreciseAref()));
  u8g.drawStr( 15,55, "DS1302 Real Time Clock");
  u8g.drawStr( 2,65, "********************************");
}

void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while(u8g.nextPage()); //u8g.nextPage()
  // rebuild the picture after some delay
  delay(500);
}

Use an DS3231 RTC instead. It include a temperature sensor with digital output. No need to read an analog value and it means less component in your PCB.


Wake up ESP8266 from deepSleep with a button I have a button with two isolated tracks. I want to be able to wake up esp from deepSleep with this button, and also detect that it was clicked. So i can't connect it to reset, because esp won't work if i don't release a button. And if it's not at deepSleep, it will reset, and i don't want it. How to do this?

Use some other pin to hold RESET HIGH or to disconnect the button from RESET while the esp8266 is not running.

simulate this circuit – Schematic created using CircuitLab

I asked on EE SE for the missing part of the circuit.


My Arduino got stuck and continuous looping in if condition I'm using RTC and when the if condition is true the Time gots stuck and the condition keeps looping. Please help

Here is my code:

// CONNECTIONS:
// DS1302 CLK/SCLK --> 5
// DS1302 DAT/IO --> 4
// DS1302 RST/CE --> 2
// DS1302 VCC --> 3.3v - 5v
// DS1302 GND --> GND
#include <Servo.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

ThreeWire myWire(4,5,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);
int servoPin = 3;
Servo Servo1;
void setup ()
{
    Serial.begin(57600);
    Servo1.attach(servoPin);
//    Serial.print("compiled: ");
//    Serial.print(__DATE__);
    Serial.println(__TIME__);

    Rtc.Begin();

    RtcDateTime compiled = RtcDateTime(__TIME__);
    printDateTime(compiled);
    Serial.println();

    if (Rtc.GetIsWriteProtected())
    {
        Serial.println("RTC was write protected, enabling writing now");
        Rtc.SetIsWriteProtected(false);
    }

    if (!Rtc.GetIsRunning())
    {
        Serial.println("RTC was not actively running, starting now");
        Rtc.SetIsRunning(true);
    }

    RtcDateTime now = Rtc.GetDateTime();
    if (now < compiled)
    {
        Serial.println("RTC is older than compile time!  (Updating DateTime)");
        Rtc.SetDateTime(compiled);
    }
    else if (now > compiled)
    {
        Serial.println("RTC is newer than compile time. (this is expected)");
    }
    else if (now == compiled)
    {
        Serial.println("RTC is the same as compile time! (not expected but all is fine)");
    }
}

void loop ()
{
    RtcDateTime now = Rtc.GetDateTime();

    printDateTime(now);
    Serial.println();
    delay(5000);

//here is my problem>>>>

    if(now.Hour() == 22 && now.Minute() == 40)
    {
      Servo1.write(0);
      delay(1000);
      Servo1.write(90);
      delay(1000);

    }

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

    delay(5000);

}

#define countof(a) (sizeof(a) / sizeof(a[0]))

void printDateTime(const RtcDateTime& dt)
{
    char datestring[20];
//%02u/%02u/%04u
    snprintf_P(datestring,
            countof(datestring),
            PSTR("%02u:%02u:%02u"),
//            dt.Month(),
//            dt.Day(),
//            dt.Year(),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
    Serial.print(datestring);
}

What is being brought to your attention is the following part of your code...

//here is my problem>>>>

if(now.Hour() == 22 && now.Minute() == 40)
{
  Servo1.write(0);
  delay(1000);
  Servo1.write(90);
  delay(1000);
}

In this code you use an "if" statement and ask:
   if the now.Hour is equal 22 AND if the now.Minute is equal 40 then
    write a 0 to your servo then
    delay for 1000
    then write a 90 to your servo
    and wait another 1000

What is being brought to your attention is that until now.Hour changes or
until now.Minute changes your write 0, delay, write 90, delay will continue
on and on and on until now.Hour changes (which will take a while) or now.Minute
changes. Since minutes are 60 seconds long your code will repeat for all of those
60 seconds...

If you were to change your code to include, oh, lets say now.Second() (like this)--

if(now.Hour() == 22 && now.Minute() == 40 && now.Second() == 00)

Then your code will repeat over and over until now.Second changes (which will take 1 second).

By the time your loop gets back to the "if" statement now.Second will no longer be 00 and it will not be "stuck" for you...

As has been brought to my attention, your 5 second delay will be a problem, so you might find that changing it will allow the now.Second "fix" to work.

In the following part of your code change delay(5000)

void loop ()
{
    RtcDateTime now = Rtc.GetDateTime();

    printDateTime(now);
    Serial.println();
    delay(5000);
}

to something like delay(1000) or so.

That way it will only wait 1 second before dropping out of the loop and checking the loop with the newly added now.Second(). This will make the printDateTime(now) happen every second instead of every 5 seconds, but it shouldn't get "stuck".

Hopefully this helps you to better understand how time (and its parts) work.


Replicate output of pwm pin on another output pin? Ardiuno Mega 2560

I have a legacy PCB that connects PORTA, pins = {22, 23, 24, 25, 26, 27, 28, 29} to the PWM input of a set of actuators. The accompanying code made use of an interupt service routine to generate PWM signals. This in turn caused all sorts of other problems for the system.

So, I would like to leverage the Mega's internal counters & use the PWM available on pins = {2, 3, 4, 5, 6, 7, 8, 9} & use the analogWrite() function. At present there is nothing else connected to these pins but access is limited.

Before I go down the route of redesigning the PCB I was wondering if it was possible to replicate the outputs of pins {2, 3, 4, 5, 6, 7, 8, 9} to pins {22, 23, 24, 25, 26, 27, 28, 29}?

As Jot wrote, you cannot simply route a signal from pin to pin inside the chip/Arduino. So - unless you redesign the PCP, which would be the cleanest way, or use jumper wires, which is not so clean - you are down to using software PWM. There are also libraries for this, if you don't want to write this yourself, for example the SoftPWM library. These libraries have their own limits, especially in frequency. Be sure to check, if they fit your needs.


How to display variables on 0.96" OLED with u8glib library? I have Arduino Uno and 0.96" I2C Oled 4 Pinned display. These are my Arduino codes:

#include "U8glib.h"

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);    // VDD=5V SCL=A5 SDA=A4

int a = 10;

void setup(void) {
}

void loop(void) {

  u8g.setFont(u8g_font_gdr25r);
  u8g.drawStr(8, 30, "E");
  u8g.setFont(u8g_font_gdr25r);
  u8g.drawStr(30, 30,"l");
  delay(2000);

  //  u8g.println(a);  //This code raw is not working
  //  delay(2000);
}

I am trying to indicate integer type variable is called "a" to the OLED screen, but u8glib library hasn't got

  println( (int) a );

function to do this. I only see

  u8g.drawStr();

function that this can't handle integer variables to the display. How can I do that?

The U8glib user reference page mentions a couple of ways to print the value of a number using ASCII characters.

Eg, following the idea at the second mention of sprintf at above link:

char buf[9];
sprintf (buf, "%d", a);
u8g.drawStr(33, 33, buf);

Edit: The above follows the example at the link, but I've struck it out because in general snprintf is safer than sprintf.  See below.

enum {BufSize=9}; // If a is short use a smaller number, eg 5 or 6
char buf[BufSize];
snprintf (buf, BufSize, "%d", a);
u8g.drawStr(33, 33, buf);

The other way is via print.  (Search for U8GLIB::print in above link, and also see arduino.cc's Print docs).

Eg:

u8g.print(a);

To get a newline effect, you may need to have a variable keeping track of the current line number; add 1 to it to get next line's number, and use that as a position parameter in a drawStr call.


LED won't turn on and serial monitor won't display values I am trying to use my Arduino to record some values from a photo-resister. The idea is when a character other than g is read the LED will turn on and 512 values will be recorded.

When I type in a character in the serial monitor whether it is g or not it just says 1 or 0 but doesn't not provide me with the values I need from the photo-resistor. My code is as follows:

int timeOut = 60000;
int pollTime = 0;
int time = 0;
unsigned long startTime = 0;
unsigned long endTime = 0;
int x = 0;
int Vs[512];
int analogPin = 0;

void setup() {
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  while (!waitFor('g', 200, 60e6)) {}
  analogWrite(9, 128);
  startTime = micros();
  for (x = 0; x < 512; x = x + 1)  {
    Vs[x] = (analogRead(analogPin));
  }
  endTime = micros();
  for (int x = 0; x < 512; x = x + 1)  {
    Serial.println(Vs[x]);
  }
  Serial.println(endTime - startTime);
}

void loop() {
}

boolean waitFor(char in, int pollTime, int timeOut)  {
  boolean done = false;
  char charWait;
  time = micros();
  while (time < timeOut)  {
    if (Serial.available())  {
      charWait = Serial.read();
      done = (charWait == in);
      Serial.println(done);
    }
  }
}

Like Edgar says, what you need to do is this:

bool waitFor(char in, int pollTime, unsigned long timeOut)
{
  while (micros() < timeOut)
  {
    if (Serial.available())
    {
      if (Serial.read() == in)
      {
        Serial.println("done");
        return true;
      }
    }
    delay(pollTime);
  }
  return false;
}

If it still doesn't run after that then change setup() to this:

void setup()
{
  Serial.begin(9600);
  Serial.println("Initialising...");
  pinMode(9, OUTPUT);
  while (!waitFor('g', 200, 60e6)) {}
  Serial.println("g command received...");
  analogWrite(9, 128);
  Serial.println("About to start...");
  startTime = micros();
  for (x = 0; x < 512; x = x + 1)  {
    Vs[x] = (analogRead(analogPin));
  }
  endTime = micros();
  Serial.println("Finished...");
  for (int x = 0; x < 512; x = x + 1)  {
    Serial.println(Vs[x]);
  }
  Serial.print("The result is : ");
  Serial.println(endTime - startTime);
  Serial.println("All finished.");
}


Digital I/O threshold voltages for ATmega32u4 What are the voltages on a ATmega32u4 (eg Arduino Leonardo) such that a HIGH or LOW is read?

I want to ensure that I'm reading the chip reference manual correctly, where Table 29-1 says:

VIL: Input Low Voltage, Except XTAL1 and Reset pin

Min: -0.5
Max: 0.2VCC-0.1V (LVTTL)

VIH: Input High Voltage, Except XTAL1 and RESET pins

Min: 0.2VCC+0.9V (LVTTL)
Max: VCC + 0.5V

My questions:

What is LVTTL?
How do I interpret the VIL Max and VIH Min?
Is the input undefined between those two values?

LVTTL is Low Voltage Transistor-Transistor Logic. In general, the
term "TTL" is used for a digital signal.
The "Low Voltage" part is special,
the ATmega32U4 switches from low to high (and vice versa)
at low voltages.
Just as it is written. For example, when the ATmega32U4 runs at 5V,
then:
VILmax = 0.2 * 5 - 0.1 = 0.9 V.
VIHmin = 0.2 * 5 + 0.9 = 1.9 V.
Between those values the input signal is seen as low or high,
but the exact voltage when it switches from low to high may
vary.
When the microcontroller is running at 5.0 V and is used
within the specifications of the datasheet, then a voltage
below 0.9 V is always seen as low and
a voltage above 1.9 V is always seen as high (guaranteed).
Those voltages is what a electronics designer must consider.

In the datasheet of the ATmega32U4 at page 403 is paragraph 30.7 "Pin Threshold and Hysteresis" with figure 30-22 and 30-23.
The figures show that at 25°C and 5V, the input switches from low to high typical at 1.55 V and it switched from high to low at maybe a slightly lower voltage.
The hysteresis is almost none and the voltage depends on VCC and the temperature.

(Thanks to Edgar Bonet for the correction/addition)


Question about button circuit I'm quite a beginner at electronics, but thought I would try venture into it.
Currently I'm working on a project where I need to reuse a button module salvaged from some old hardware, but I can't figure out the wiring. The attached image is what I was able to track down on how the circuit is built. I'm not really sure how to wire it? Would it be possible to use this with an ESP32 and differentiate all the buttons?

Sure. Take a multimeter and measure the resistance between the left-most pin and each of the other pins with all the different combinations of button pairs pressed. Write down the results.
Then build a voltage divider for each output (Connect a resistor to ground on each output, and then connect that pin to an analog input on the Arduino. The resistor value to use will depend on the readings you get, but a 1K ohm resistor would be a good starting point.)
Then set up the 2 input pins on your Arduino as analog inputs and measure the voltage with no buttons, top button, bottom button, and both buttons pressed for each pair. Write those values down. Then write code that checks for voltages roughly equal to your measurements for each button press combo (You will need check for ranges of values, since the values will vary some.)


Regarding using I2C with Arduino for Silicon Micro-structure 5852 D 1.5 psi I am trying to get output from a sensor (micro-structure 5852D), but I only get two outputs: 11 and 255 for even applying pressure.

The following is my code, please show me how to over come this problem.

#include "Wire.h"
#define addrs 0x5F // I2C bus address

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

void loop()
{

   byte lobyte;
   byte hibyte;
   int Press;

   Wire.beginTransmission(addrs);
   Wire.write(1);
   int x = Wire.endTransmission();

   Serial.print("endTransmission: ");
   Serial.println(x, DEC);

   Wire.requestFrom(addrs, 2); // contents of your first two registers
   while(Wire.available() < 2 );          // Check for data from slave
   {
      delay(1000);
      lobyte = Wire.read();       // Read press high byte
      Serial.println(lobyte, DEC);
      hibyte = Wire.read();      // Read press low byte
      Serial.println(hibyte, DEC);

      Press = toPressure(hibyte, lobyte);
      Serial.print("Pressure: ");
      Serial.println(Press);

      delay(1000);
   }

}

float toPressure(byte hi, byte lo)
{
  int a = (hi * 256 + lo) & 0x3FFF;  // see pdf, mask 14 bit

  float rv = (a - 116)* 0.8606; // faster //(t - 1638.0) / 30.84 + 600.0
  return rv;

}

The issues in your code:

When communicating with the sensor, the sensor expects a register address after the device address. Instead of providing it the register address, you sent the number of bytes you would like to receive. Good guess, but unfortunately the device was not designed that way.
You did not combine the least significant bits and most significant bits of the sensor output correctly. The LSB contains the 6 (not 8) least significant bits, while the MSB contains the 6 most significant bits. You first combined them like 00MMMMMM00LLLLLL (where bits marked L come from the LSB and bits marked M come from the MSB), and then masked off the upper two bits as in MMMMMM00LLLLLL. The proper way would have been to only left shift the MSB 6 bits, producing 0000MMMMMMLLLLLL, and then masking away the upper 4 bits leaving MMMMMMLLLLLL.
You should avoid 32 bit floating point math on 8-bit microcontrollers at all costs unless you have a huge amount of processor cycles to spare.

In order to read data from the sensor you must first select the register you want to read. To select a register you must first send the device address (95 in decimal, 5F in hexadecimal) with the write request bit set, and then the register address of the byte you want to read.
You can then read the contents of the selected register by first sending the device address, this time with the write request bit clear, and then receiving one byte of data immediately followed by a not acknowledge (NACK) to end the transmission.

The internal registers are organized as in the following table:

Here is my take on the code. It compiles fine, but obviously I cannot test if it actually works as I don't have the sensor. I removed the scaling routine, as it would be wise to first get it working to some level before implementing less essential features.

#include "Wire.h"
#include <stdint.h>

#define SENSOR_I2C_ADDR 95
#define SENSOR_REG_PRESSURE_LSB 128
#define SENSOR_REG_PRESSURE_MSB 129

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

void loop()
{
    Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the least
    Wire.write(SENSOR_REG_PRESSURE_LSB);            //..significant bits of the pressure measurement are found
    Wire.endTransmission(false);                    //Send a repeated start
    Wire.requestFrom(SENSOR_I2C_ADDR, 1, false);    //Request 1 byte of data, followed by a repeated start

    Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the most
    Wire.write(SENSOR_REG_PRESSURE_MSB);            //..significant bits of the pressure measurement are found
    Wire.endTransmission(false);                    //Send a repeated start
    Wire.requestFrom(SENSOR_I2C_ADDR, 1, true);     //Request 1 byte of data, followed by a stop, ending the transaction.

    uint16_t pressureRaw;

    //There should now be two bytes of data in the receive buffer.
    if(Wire.available() == 2)
    {
        uint8_t lsb = Wire.read();                  //The first byte contains the 6 least significant bits
        uint16_t msb = Wire.read();                 //The second byte contains the 6 most significant bits
        pressureRaw = (msb << 6 | lsb) & 0x0FFF;    //The most significant bits are aligned and combined with the
                                                    //..least significant bits. As the resulting value only has
                                                    //..12 bits of precision the upper 4 bits are masked to zero.

        Serial.print("Raw pressure value: ");
        Serial.println(pressureRaw);
    }
    else                                            //If more or less than 2 bytes have been received something isn't right.
    {
        while(Wire.available())                     //Clear the buffer
            Wire.read();
        Serial.println("I2C transaction error");
    }
    delay(1000);
}

For some unfathomable reason Silicon Microstructures decided to not include the I2C interface specification in the datasheet itself. The information is instead found in a separate application note.

EDIT:
Apparently Wire.flush() does absolutely nothing. Implementation from Wire.cpp:

void TwoWire::flush(void)
{
    // XXX: to be implemented.
}

And no, the implementation isn't in the base class either: virtual void flush() = 0;. To work around this, I replaced the flush call with a read() loop.


Using EEPROM to write a counter value I have made a program that increments a counter everytime the up button is pressed. I am trying to write this value to EEPROM, so that when I turn my board off and on again, the value before power off is shown on screen.

I wrote this code but the value doesn't seem to be written to EEPROM. The counter incrementation works fine.

#include <EEPROM.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

int addr = 0;
byte value;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);
}

int a;
void loop() {
  uint8_t buttons = lcd.readButtons();
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      EEPROM.write(addr, a);
      value = EEPROM.read(addr);
      lcd.print(value);
      delay(100);
    }
  }
}

Thanks for the help!

just add a = EEPROM.read(addr); in your setup
also, you can remove byte value and use a you wrote to memory in the previous line


Disturbed digital out at 4Mhz on Arduino NANO I've written a simple program - it generates signals over Port D at 4 MHz:

#include <Arduino.h>

int main(void) {

    DDRD = B11111111;
    PORTD = B00000000;

    while (true) {
        PORTD = 0;
        PORTD = 5;
        PORTD = 10;
        PORTD = 15;
        PORTD = 20;
        PORTD = 25;
        PORTD = 30;
        PORTD = 35;
        PORTD = 40;
    }
    return 0;
}

and this is the signal coming out on D4:

I've modified the program by inserting NOP after each assignment to POTRD:

#define NOP __asm__ __volatile__ ("nop\n\t")

int main(void) {

    DDRD = B11111111;
    PORTD = B00000000;

    while (true) {
        PORTD = 0;NOP;
        PORTD = 5;NOP;
        PORTD = 10;NOP;
        PORTD = 15;NOP;
        PORTD = 20;NOP;
        PORTD = 25;NOP;
        PORTD = 30;NOP;
        PORTD = 35;NOP;
        PORTD = 40;NOP;
    }
    return 0;
}

and now signal looks fine, but frequency is limited to 800 KHz:

What is the reason for interference at 4 MHz? Is there a limitation to maximal frequency on digital out? I do not really need it for some particular project, just wanted to know it.

I've asked this question on stackoverflow, but then I've discovered this dedicated forum so... I've decided to try it out ;)

This is not a limitation of the Arduino: you can toggle a pin on every clock cycle. It's a synchronization problem between the generated signal and the triggering of the scope. Your scope displays several traces superimposed, and it synchronizes them on the rising edges, but since those are unequally spaced, it gets out of sync with the full period of the signal. By adding a few nops you reached a lucky synchronization in your second version of the code.

The simplest solution is to set the scope mode to Single instead of Normal. Then it only displays a single trace and synchronization is not an issue anymore.

Another option would be to use one of the bits of PORTD as a trigger
signal. This bit should cycle only once inside the loop. PD5 should
work in the current version of your code. Configure the scope for
external trigger and feed this signal into its TRIG input.


How to upload program to board using Arduino sketch ver 1.6? I am having problems uploading my program. I have been using the verify button aka the "checkmark" to upload my programs. I assumed that this was the correct button but now I am having problems uploading. When I attempt to use the "upload" button I get the error "can not open device". What am I doing wrong? How can I fix this error code?

The checkmark button is used to compile your program (which "verifies" your code), but does not upload it to the board. The "arrow" button is used to compile and upload your program.

If you cannot connect to the device, make sure the correct COM port is selected on the Tools->Ports menu, and make sure you have the correct board selected on Tools->Board (usually an Arduino UNO).

If you have not installed the drivers yet, you will not have a port present for your Arduino. If that is the case, here is a great tutorial that will help you get everything installed and set up correctly: https://learn.adafruit.com/lesson-0-getting-started


LCD connection problem First of all, i have some problems with an lcd .
For a better understanding, the lcd datasheet could be found here:
https://www.mikrocontroller.net/attachment/53098/DGF-12232-S1FBLY-325-17231-1006.pdf

i want to connect it to arduino mega but it has 20 pins and i can't figure it out how it should be connected.
Could someone help me ?

For those reading this answer prior to acquiring an LCD for an Arduino project, consider using a more common alpha / numeric LCD rather than a graphic LCD or GLCD.  Likely there will be more examples to follow as well as more software with more community support.

The linked to Graphical LCD (or GLCD) uses a SED1520 controller.  Searching the Arduino community resulted in finding this openGLCD project.  There may be others.  Looking here (near the end of 2019) we see the comment "added custom sed1520 init routine to fully initialize sed1520 chips" next to the sed1520_Device.h file.  Likely this project supports GLCD modules which use the SED1520 chip.

With regards to wiring GLCD module, on page 19 of the specifications linked to in the question, the table in section 5.1 lists the description of the 20 GLCD pins.


Sim900a AT+HTTPREAD does not get fully answer changed the firmware on SIM900B

try to send get request http://dummy.restapiexample.com/api/v1/employee/1
AT+HTTPACTION=0returned +HTTPACTION:0,200,98

but, when I try to read (AT+HTTPREAD or AT+HTTPREAD=0,98)the response data
I got broken response

expected result:

+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999","employee_age":"0","profile_image":""}

and actual results:

+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999","empe_"0"olme"

+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999","empe_"0"fea"}

+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999""pea:,piig"

+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999",moeg""reae}

my Arduino code looks like that

void setup() {
  Serial.begin(9600);
  mySerial.begin(57600);
  delay(5000);
  mySerial.println("AT");
  Serial.println("End of the setup");
}

void loop() {
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Apparently you were running software serial at too high of a baud rate (57600) and bringing it down to 9600 fixed the issue.


Speed sensors for sport Fair warning: I'm a newbie when it comes to Arduino, so if I'm not too great at describing things, let me know so I can learn!

I have recently built a fairly accurate laser timer to time sprinters through a section of a soccer pitch, giving a nice reading of their average speed through the zone.

The limitation is that we would love to be able to see their speed as a progressive measurement throughout the sprint.

My problem? I have NO idea where to start. Google has so far come up empty...

All I have is the following link, Best of the 2015 NHL All-Star Skills Competition, illustrating the sort of thing we would like to accomplish. The bit in question starts at around 0:35 when they are talking about sensors in the players' jerseys.

Any one able to point me in the right direction?

Kinovea is good but this would be post processing not live. You need record video and then you can track each runner on time. Another one is Typhon program but it involves programming and calibrating (then you can track live).


Does Leonardo need a separate power supply? I'm currently using an Arduino Uno (R3), but want to switch to Leonardo for the USB-ability. The Uno can work from the USB's 5V. Looking at the Leonardo's schematic it seems the only input to the voltage regulator is from the power connector. This makes sense as it's a 5V regulator which needs > 5V in. But I don't see the MOSFET which connects the USB's 5V to the board's 5V, like there's one on the UNO.

So, does the Leonardo need the separate power input connected?

Power steering is performed by the assembly labelled "+5V AUTO SELECTOR" at the bottom of the page. The voltage at VIN is halved and then compared with the board's 3.3V output in order to determine whether or not to enable USB power via T1.


In line following robot do this code work perfectly as iam unclear about the right and left moving programing lines #define LS 2      // left sensor
#define RS 3      // right sensor

/*-------definning Outputs------*/
#define LM1 4       // left motor
#define LM2 5       // left motor
#define RM1 6       // right motor
#define RM2 7       // right motor

void setup()
{
  pinMode(LS, INPUT);
  pinMode(RS, INPUT);
  pinMode(LM1, OUTPUT);
  pinMode(LM2, OUTPUT);
  pinMode(RM1, OUTPUT);
  pinMode(RM2, OUTPUT);
}

void loop()
{
  if(digitalRead(LS) && digitalRead(RS))     // Move Forward
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }

  if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
  {
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }

  if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, LOW);
    digitalWrite(RM2, LOW);
  }

  if(!(digitalRead(LS)) && !(digitalRead(RS)))     // stop
  {
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, LOW);
    digitalWrite(RM2, LOW);
  }
}

i got this code from a site.My doubt is if the left sensor is not reading means it has value of zero hence it is on black line and the right sensor is on white line.Then it should move to left side itself.BUt the program says it should moves to right.Iam a beginner.Please help me to clear my doubt

This depends on how the sensors are arranged. However, assuming they are setup like eyes on our heads, then the code would be correct.

If the left sensor does not see the line, but the right sensor does, then that means the line is on the right side of the robot, and thus turning to the right would bring the line back into view of the left sensor.


What happens when I call exit() from my program? In either of setup or loop, if I were to add an exit(0) call, where would control be passed to? What would the next state of the microcontroller be? Would it stop execution and power down?

I am using a revision 2 Arduino Uno.

My initial guess is wrong. I would have thought it would simply return from loop and the core library would just call loop() again. However, I see the following code was created. Noticing that __stop_program is a hard loop...

An extract of Blink.ino's listing, with exit(0) added:

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
  exit(0);
}

The disassembly of the above:

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
 100:   80 91 00 01     lds r24, 0x0100
 104:   61 e0           ldi r22, 0x01   ; 1
 106:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 10a:   68 ee           ldi r22, 0xE8   ; 232
 10c:   73 e0           ldi r23, 0x03   ; 3
 10e:   80 e0           ldi r24, 0x00   ; 0
 110:   90 e0           ldi r25, 0x00   ; 0
 112:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
 116:   80 91 00 01     lds r24, 0x0100
 11a:   60 e0           ldi r22, 0x00   ; 0
 11c:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 120:   68 ee           ldi r22, 0xE8   ; 232
 122:   73 e0           ldi r23, 0x03   ; 3
 124:   80 e0           ldi r24, 0x00   ; 0
 126:   90 e0           ldi r25, 0x00   ; 0
 128:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  exit(0);
 12c:   80 e0           ldi r24, 0x00   ; 0
 12e:   90 e0           ldi r25, 0x00   ; 0
 130:   0e 94 1e 02     call    0x43c   ; 0x43c <_exit>

...

0000043c <_exit>:
 43c:   f8 94           cli

0000043e <__stop_program>:
 43e:   ff cf           rjmp    .-2         ; 0x43e <__stop_program>

Note that if _exit had not called cli, interrupts would be able to do stuff. But that is not the case.


How to clear of contents of string in Arduino? Currently I convert the characters in char received[20] to string using String randomString(received) and I am able to display it using Serial.println(randomString). After displaying the string, I would like to know the easiest way to clear out its contents.

In C and C++ a null terminated array of characters is a string (although not a String). Many routines for reading input terminate the result with a null as does an assignment like"

char foo[] = "This is a string.";

All you would need to do to "clear" this string is to assign a null to the first character. For example:

foo[0] = '\0';


DHT11 analog or digital? I saw some projects with DHT11, some connect it with analog pin, others connect with digital pin.

Is there any difference / advantage connecting to the analog?

The DHT11 is a digital component with its own digital communication protocol.

Analog pins can be used for either analog input or digital input and output.

You can use a digital device like the DHT11 on any pin, whether it is labelled analog or digital (except on a couple of boards which have a few analog-only pins).


Does the arduino board have to be always physically connected to the electronic device you are running? If I have a basic electronic board with some LEDs and sound fx and I want to program them (I'm a beginner, learning about arduino), does the arduino board always have to be connected to the actual electronic board I'm running or is there a way to "upload" the programming to the circuit board?

If the "basic electronic board" is programmable, then yes, you can upload a program to it.

In general, though, "some LEDs" and similar devices are not programmable, and without something to drive them (i.e., the Arduino) they won't do anything at all.  The Arduino is what has the program and it tells the "basic electronic board", moment by moment, what it should be doing.  It is the brain of the operation.  Remove the brain from someone and you'll find their body no longer functions.


Strange values from LSM303 Magnetometer I am having problems with values i get from Pololu MinIMU-9 boards's magnetometer. I am using Arduino-micro and the arduino library from Pololu. The sensor on the board is 3 axis accelero- and magnetometer LSM303.
The problem is - the highest value always seems to be in vertical axis, not horisontal, as i would expect.

For example, here is the data i got when i put sensor flat on the table and made 360 clockwise turn in horizontal plane:
(values are X Y Z)

-6 102 -516
-11 103 -515
-11 103 -515
-21 102 -514
-31 109 -515
-40 114 -512
-57 116 -509
-57 116 -509
-77 111 -507
-93 109 -506
-104 106 -507
-104 106 -507
-114 99 -508
-126 88 -504
-131 74 -507
-142 52 -507
-142 52 -507
-151 31 -506
-150 4 -509
-147 -27 -513
-147 -27 -513
-133 -60 -513
-119 -80 -519
-112 -87 -517
-102 -97 -521
-102 -97 -521
-89 -101 -522
-77 -101 -524
-50 -104 -527
-50 -104 -527
-43 -105 -529
-14 -98 -532
2 -92 -535
23 -92 -535
23 -92 -535
36 -81 -534
66 -54 -534
76 -32 -531
76 -32 -531
76 -21 -532
78 -7 -531
85 10 -528
91 39 -524
91 39 -524
94 50 -524
91 63 -524
76 75 -525
76 75 -525
63 82 -526
47 93 -525
44 98 -522
44 98 -522
38 104 -521
26 110 -521
26 112 -518
21 116 -519
21 116 -519
18 116 -518
12 120 -517
11 120 -515
11 120 -515
8 120 -517
5 122 -515
-5 123 -514

Turning the sensor "upside down" and then rotating it in horisontal plane again gives similar results, only Z axis has positive 500+ value.

Shouldn't the magnetometer always point in the direction of the magnetic field - in X or Y direction?
I have tried this in different rooms and buildings and got the same results.
Rotating the sensor on other axes yields the same results - vertical axis has the largest (and constant) value.

For reference, here is the code i used to get the values.

#include <Wire.h>
#include <LSM303.h>
LSM303 compass;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  compass.init();
  compass.enableDefault();
}

void loop(){
  compass.readMag();
  Serial.print(compass.m.x);
  Serial.print(" ");
  Serial.print(compass.m.y);
  Serial.print(" ");
  Serial.print(compass.m.z);
  Serial.print("\n");
  delay(100);
}

The earth's magnetic field is not parallel with the ground. In some locations it can be pointing more down than across.

NOAA has a magnetic field calculator where you can enter you latitude and longitude. For example, I am located at approx  19deg S 147degE and the field is

North Comp    East Comp    Vertical Comp    Total magnitude
32,434.4 nT   4,280.6 nT   -36,035.1 nT     48,670.7 nT

So the downwards strength is more than the other two combined for my location. I'm guessing the calculator will also show a very strong down component for your location.

Some other things to be aware of are that the LSM303DLHC magnetometer can have quite large offsets, up to the equivalent of 2 earth magnetic fields, and therefore requires calibration. Also hard and soft iron distortions can affect the readings.

Edit: Please see my answer here for methods to calibrate the sensor.


Arduino Piccolo Example Script Error So I am trying to make an audio visualizer from this tutorial listed here.

So I downloaded all the files needed, and downloaded the code. But when I try to verify it, I get this Error:

C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp: In constructor 'RobotControl::RobotControl()':
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'LCD_CS' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'DC_LCD' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'RST_LCD' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp: In member function 'void RobotControl::begin()':
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXA' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXB' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXC' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXD' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:19: error: 'MUX_IN' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:22: error: 'BUZZ' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:25: error: 'Serial1' was not declared in this scope
core.a(main.cpp.o): In function `main':
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\hardware\arduino\cores\arduino/main.cpp:11: undefined reference to `setup'
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\hardware\arduino\cores\arduino/main.cpp:14: undefined reference to `loop'

I've looked this up before, and couldn't find anything on it. So I came here for a last resort.

Any ideas?

EDIT: So I reinstalled the folders, and renamed the LED folder but now I get a new error:

Piccolo:112: error: 'Adafruit_BicolorMatrix' does not name a type
Piccolo.pde: In function 'void setup()':
Piccolo:130: error: 'matrix' was not declared in this scope
Piccolo.pde: In function 'void loop()':
Piccolo:168: error: 'matrix' was not declared in this scope
Piccolo:168: error: 'LED_RED' was not declared in this scope
Piccolo:169: error: 'LED_YELLOW' was not declared in this scope
Piccolo:170: error: 'LED_GREEN' was not declared in this scope
Piccolo:207: error: 'LED_OFF' was not declared in this scope
Piccolo:210: error: 'LED_OFF' was not declared in this scope

EDIT 2: Deleted Robot_Control and got this error:

In file included from Piccolo.pde:34:
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:94: error: expected class-name before '{' token
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:103: error: expected class-name before '{' token
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:112: error: expected class-name before '{' token
Piccolo.pde: In function 'void loop()':
Piccolo:168: error: 'class Adafruit_BicolorMatrix' has no member named 'fillRect'
Piccolo:169: error: 'class Adafruit_BicolorMatrix' has no member named 'fillRect'
Piccolo:170: error: 'class Adafruit_BicolorMatrix' has no member named 'fillRect'
Piccolo:207: error: 'class Adafruit_BicolorMatrix' has no member named 'drawLine'
Piccolo:210: error: 'class Adafruit_BicolorMatrix' has no member named 'drawLine'

As I mentioned in the comments, reinstalling/updating all your 3rd party libraries to the latest versions is probably the first thing to try. Updating the IDE itself may also help.

If that hasn't worked then a forum topic here seems to describe the same kind of issue: http://forum.arduino.cc/index.php?topic=168854.0

One of the users seems to have tracked the problem down to a couple of Adafruit libraries. He suggests the following:

  1) Delete the folder "Robot_Control" from Program
  Files\Arduino\libraries\

  2) Make sure, that the two Adafruit folders in the same folder are
  named Adafruit_GFX and Adafruit_ST7735. I had them named "AdafruitGFX"
  and "AdafruitST7735", but that was wrong.

Deleting the Robot_Control folder doesn't sound like an ideal solution to me, but perhaps there's an incompatibility which can't be easily fixed. Unfortunately, the Arduino IDE handles libraries in a slightly strange way, so weird problems can happen from time to time.


Arduino C++ library syntax I am looking at modifying the H3LI331DL I2C library posted by Seed Studio for communicating with the H3LI331DL accelerometer. The library hardcodes the address for the accelerometer in the header file. My end goal is to make the library require a slave address input argument so I can talk to 2 accelerometers on the same I2C bus. The chip has a pin that sets the LSB of its address.

Now onto the question. The library's .h file has the following statement:

#define H3LIS331DL_MEMS_I2C_ADDRESS     0x18//0x32

Is the 0x32 simply commented out or am I missing something here?

Thanks,

Emach

It is indeed commented out. SeeedStudio is a great company but their code (including code prettifying) is pretty sloppy, and sometimes a little dumbfounding.


Arduino Uno's RX and TX lights not blinking. Unable to upload sketches! When arduino starts up, RX TX lights doesn't blink. Only the PIN 13 and Green light turns on. Pin 13 light blinks thrice before getting stable. RX TX lights are not blinking at all. I am not able to upload any sketches. The error I get is "Not in sync resp=0x00" or "Programmer not responding" or "Not in sync resp=0x95" or "Not in sync resp=0x69" and so on. A new error everytime. Most probably the error is with serial communication.

A brief history of what I have done

I have a Relay which is operated at 12V. But Arduino works at 5V logic. So I used a comparator (IC741) to improve the logic (By setting Vcc and -Vcc at 12 and 0 and the input pins connected to arduino). I also connected HC-05 bluetooth module to use the relay using my cellphone. You know what I was trying was home automation. Also Arduino was connected to 12V DC supply (I think this was my mistake). Everything was going right.

Suddenly IC741 started burning,maybe I shorted some pins when I was trying to measure the voltages using multimeter. I quickly removed it. Suddenly HC 05 started burning. I immediately removed all the connections. After some time I turned on Arduino again (This time using USB connected to laptop). I connected HC05. The bluetooth module heats up again. I thought the module is now gone. I turned to check Arduino and as I stated I am unable to upload any more sketches. Most probably the bluetooth module cause an error in serial communication. May be not.

So my question is
1. What's the real problem. Is my bluetooth module gone? Or is Arduino gone? If arduino is still fine, how can I get the serial to work back and enable me to upload sketches?
2. If Arduino is gone, most probably the microcontroller Atmega328 is still fine. How can I use it now without Arduino (I don't have any extra Arduino)?

Things I have already tried :

Loopback test : No echo back. Serial data can neither be sent nor received.
When I open the Serial window, Arduino doesn't resets as it it earlier.
RX TX Vin and 5V pin reads 4.99V. I hope they are fine.

Pin 13 light blinks thrice before getting stable.

It is supposed to do exactly that. See What happens when code is uploaded using the bootloader?

  RX TX lights are not blinking at all.

That's not so good. See Have I bricked my Arduino Uno? Problems with uploading to board


Can RX and TX be temporarily transposed on demand? Only 2 arduinos can normally be linked via serial port because TX and RX need to be cross-linked, and connecting multiple TXs together would cause conflict.

RS485 allows multiple nodes connected in parallel on a 2 wire differential 'bus', using a TX ENABLE pin to allow one master to transmit while all other slaves listen.

I suspect it should be possible to similarly connect multiple serial RXs together to give a common listening bus, and be able to use TX ENABLE on any one node at a time to transpose its RX and TX to allow its TX to transmit to the other RXs. This might be physically done using a changeover relay swapping RX with TX, but is it possible to somehow temporarily switch the TX and RX assignments on demand by software?

I doubt the actual pin assignments can be changed in-situ, but perhaps the same results are achievable with some programming wizards sleight-of-hand trickery?

On an AVR-based Arduino, you can selectively enable the transmitter and
receiver side of the UART (c.f. the datasheet of your MCU). Thus, you
could in principle just connect all the TX and RX together, and make
sure only one transmitter is enabled at a time, while all the others are
in high impedance. If you do this, I would strongly recommend you put a
current-limiting resistor in series with each TX, just in case.

For example, on an Arduino Uno
(Atmega328P),
you can use the following functions:

static inline void enable_tx()  { UCSR0B |=  _BV(TXEN0); }
static inline void disable_tx() { UCSR0B &= ~_BV(TXEN0); }
static inline void enable_rx()  { UCSR0B |=  _BV(RXEN0); }
static inline void disable_rx() { UCSR0B &= ~_BV(RXEN0); }

Edit: Beware that Serial.begin() enables both the transmitter and
the receiver.


problem in uploading the code Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 12452 bytes (38%) of program storage space. Maximum is 32256 bytes.
Global variables use 970 bytes (47%) of dynamic memory, leaving 1078 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0
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.

It means there is no proper communication between the IDE and your Arduino. The reason can be many things:

RX/TX UART port used
USB port broken
USB cable broken
Arduino broken
USB port drivers not properly installed
Problem inside IDE
...

To troubleshoot you could try:

Disconnect RX/TX jumpers
Try another USB port
Remove other USB devices
Try another USB cable
Try another Arduino
Try another PC/laptop
Reinstall IDE
Reinstall USB drivers


HC-05 Module not receiving commands and not pairing I'm working on a project where I'll need to establish a connection between two HC-05 modules, each connected to an Arduino, but for now I'm just trying to get one to work and connect to my phone, but I'm not sure if I'm doing anything right...
I'm not able to give AT-Commands, and as a result the device is not able to pair with my phone.
My setup looks something like this:

With minor differences being that I'm using an Uno board instead of a Mega, the RX and TX pins are connected to...well, I tried a lot of different pins, from the default RX/TX pins to specifying other pins like the ones in the code, as well as reversing the connections (RX to TX, TX to RX), also this schematic neglected to mention the 'ENABLE' pin, which I connected to my Arduino's 3,3V pin.
I tried a lot of different code samples, the latest one I tried is the following:
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(38400);
  Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
  // Deleted while loop, unnecessary

  mySerial.begin(38400);
}

void loop() { // run over and over
  //if (Serial3.available()) { // we don't use Serial3 any more
  if (mySerial.available()) {
    //Serial.write(Serial3.read());
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    //Serial3.write(Serial.read());
    mySerial.write(Serial.read());
  }
}

Which I blatantly ripped-off from this answer, with minor changes.
So, I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen, just an alternating sequence of the characters 'x' and '?', to my understanding that's actually the message "Enter AT commands:" written in my code...
Now, with this exact setup, I'm now actually receiving a response to my commands, except the response is also gibberish, this is as far as I've gotten.
EDIT: By following some of the comments and setting the Serial baud rate to 38400, I managed to get other Reponses to my commands, but it's just a new type of gibberish and it's still not actually responding to my commands.
The thing is, all of the tutorials I've seen online are contradicting each other, some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board, some don't bother with the ENABLE pin entirely, some don't use a voltage divider, some connect VCC pin to the 3,3V instead of the 5V, some even skip the AT-Command setup entirely!
One last detail I feel like I should mention, there's a red light that blinks on and off every two seconds, I believe that means the module is read to receive commands but I've seen contradicting information about this as well so I'm not sure.
I want to know what I'm doing wrong, and what's the right way to do this?

You have seen contradictory statements, because there are many variables here, that might be different for each of the tutorials.

some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board

There are basically 2 ways to communicate between the Serial Monitor and the HC-05:

You can connect the HC-05 directly to the USB Serial chip on the Arduino board, thus you would communicate directly with the HC-05. In that case the TX and RX pins are used, since they are connected to the USB Serial chip. But the labels TX and RX are referring to the Arduinos chip (Atmega328p at the Arduino Uno). Since serial connections need to be connected alternating (RX to TX and TX to RX), the pin labeled TX leads to the RX pin of the USB Serial chip and vice versa.
Thus you would connect TX of HC-05 to the TX pin on the Arduino and RX of HC-05 (through the voltage divider) to the RX pin on the Arduino. Also you should program the Arduino with an empty sketch before doing that, so that the Arduino does not interfere in the Serial communication with its own Serial usage.

Or you can use a SoftwareSerial interface and let the Arduino code translate between the devices. The Arduino received from the PC and sends the data to the HC-05. Also it receives from the HC-05 and sends that data to the PC. This is what you were trying. But you absolutely need to specify a different set of pins for the SoftwareSerial interface, than 0 and 1. These pins are doing the hardware Serial interface, which is connected to the PC. So change these pin numbers (for example to 2 and 3).
In fact: Whenever you see a code for Uno, Nano or Mega using SoftwareSerial on pins 0 and 1, you can be sure, that it is garbage.

I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen

Even when you change the pins as described above, your code still uses 9600 baud for the connection to the PC. When you set the Serial Monitor to 38400 while the code uses 9600 baud for that interface, you will get just gibberish. Either change your Serial Monitor to 9600 baud or change your code to Serial.begin(38400). The last option is better, since that makes sure, that you are using the same baudrate for both interfaces.

some don't bother with the ENABLE pin entirely

The ENABLE pin seems to have a pulldown resistor on the HC-05 board, which pulls it to ground, when nothing is connected. Ground means data mode, HIGH command mode. So when they don't connect anything, they want to stay in data mode. Though this also depends on if the specific HC-05 board has a pulldown or pullup resistor there. Pulldown is more likely, but since there is no one single producer of these modules, you cannot be sure. Since you want to get into AT mode, you should use command mode and connect it to 3.3V. For normal operation it would go to ground. Though you can also connect it to a digital output pin of the Arduino and let the code decide in which mode the module should be.

some don't use a voltage divider

The chip on the HC-05 board is a 3.3V device. The actual breakout boards, that can be bought everywhere, mostly only add a voltage regulator from 5V to 3.3V, an LED for status display and break out the necessary pins. The data pins are mostly directly connected to the chip. There are many resources, that claim the HC-05 to be 5V tolerant, but also many that antagonize that. To be sure not to destroy the HC-05, you should also use a voltage divider.

some connect VCC pin to the 3,3V instead of the 5V

This is only done, when the used board does not have a 5V to 3.3V voltage regulator. Depends on the exact board, that you own.

some even skip the AT-Command setup entirely!

When they don't need to configure the HC-05 in a special way, why would they go into command mode. That might be different for you.


is the Arduino shield pinout a standard, so that any Arduino shield can work with any Arduino board I'm new to Arduino and dying to delve in.

There are lots of Arduino base board vendors, and lots of shield vendors.

In general, should I be able to plug any shield into any Arduino board, even with existing shields?

Most shields will fit most of the "regular sized" boards. the obvious exception is the boards like the nano which are tiny. Shields are going to have the best compatibility with the Uno, just because that one is the most common, so if you are going to get one arduino and a bunch of shields, get an uno. Some shields (the gen 1 ethernet and wifi shields in particular had an issue where they could not be used on Megas because the mega listens to SPI on pins 50+ which simply were not connected to the shield, however most of the newer shields will connect to the 6-pin block in the center now-adays to allow Mega usage.

The next thing you want to look at is if you are stacking shields, if they will collide on pin usage (SPI gets around this through multiplexing) and some of the 3.3 volt devices may have conflicts with 5-volt shields. Although the 3.3v devices do provide 5v power-out pins in the same locations as the Uno, it becomes more of an issue with trying to read a 5v on a 3.3v pin, which could damage the microchip.

the best thing to do is to check the documentation of the shields and check which pins they use, what voltages they need/supply, and comparing this with the particular arduino you are using.


What's wrong with my undetected, unresponsive Arduino Robot? I was wondering if someone could try and solve a major problem I've been having with a brand new Arduino Robot (similar to an Arduino Leonardo). Any input would be very much appreciated!

I've been working with an Arduino Robot on a summer internship for the last week with no major problems. However, a couple of days ago, it stopped running programs and couldn't be detected when being plugged into the computer.

When plugged in or turned on, the LCD turns on with nothing displayed on the screen and the power LED also switches on. However, no program is run (I had a working program involving the LCD uploaded at the time it stopped functioning, which would normally run). Also when plugged in, the Arduino is completely undetected by the computer, with the 'Serial Port' option under Tools grayed out, the device not showing up in device manager, and no signs that a device has been plugged-in. I've tried 3 different USB cables - one of which I tested on another device - and 3 different computers (with Windows 7, 8.1 and Linux Ubuntu installed). On the Linux computer, I ran lsusb before and after plugging in the device and saw no change. I've also tried various solutions such as re-installing the drivers and the Arduino software, using MProg and various rebooting/unplugging-replugging variations.

So I think the problem is almost definitely with the Arduino Robot itself. I'll give a little information about the problems I encountered previously, to see whether something I did affected it or not.

Problem 1:

The first problem I had with the robot was entirely by my own fault and was pretty foolish of me (I'm new to electronics - this being my first project involving it). I ran code from this website (the first set of coding on the page) to try and see whether I could get the LCD to work - not realizing that it wouldn't work for a different type of LCD. After uploading the code, the speaker made a loud constant buzzing noise. Fortunately after uploading a different code, the problem was resolved. I'm doubtful that this could have affected the robot, but since I'm so new to this I'll leave it to one of you to decide.

Problem 2:

The next problem was one to do with uploading. The robot worked fine for a couple of days after the first problem until I came across this one:

When uploading programs, there would be a 'device disconnecting' sound from the computer and the program would fail to upload (I can give details on the error messages if you need them). I managed to solve the issue using an odd solution involving hitting the reset button at just the right time while a program was uploading.

After this, the robot worked for a few hours. In this time I tried to play with the 'turn' function, which didn't seem to work very well at all (the robot would turn angles very different to the ones given) and started creating programs playing around with the LCD. It was at this point the robot stopped functioning properly.

So does anyone have any idea what might be wrong? I have no idea how to fix this problem and I've been trying to find a solution for almost 2 full days now. Any input at all would be greatly appreciated.

I'm pretty sure and sadly to announce you that the usb communication of your Arduino Leonardo Compatible is dead and the arduino is connecting to the computer just like an alimentation Source no more.
And since Arduino Leonardo based on The ATmega32U4 which has built-in USB communication ,so the Atmedga32U4 is dead(u-processor) too.

It's not a software matter but hardware one.


Using the SD library with the ESP8266 DevKit The situation is as follows, I've connected a SPI TFT screen to the ESP8266 DevKit, set my own MISO,MOSI, CD, SCK pins and it works fine, wanted to do the same for using the SD card reader, but then I realized that the SD library is using the pre-defined pins with no visible way override this.. There must be a way, no?

I did try editing the pins_xxx files:

static const uint8_t SS   = 10;
static const uint8_t MOSI = D7; //11;
static const uint8_t MISO = D5; //12;
static const uint8_t SCK  = D6; //13;

But it did not work, I'm not that well familiar about the build process..
So, is there a way to accomplish this? Maybe a different library?

P.S. I am using the Arduino IDE for the ESP.

After some trial and error got both the screen and sd card reader working sharing the MISO and SCK lines.
I was using a display wit the Adafruit ST7735 driver (and their library), worked fine with both hardware and software, but the SD card reader (generic, not even a part number on it) was able to work only with hardware SPI as the standard SD library does not support software SPI for some reason.
The most important takeaway is this: The SD library internally uses the predefined MOSI,MISO and SCK pins, but fot the ESP8266 dev kit they were mapped to pins labeled HMOSI, HMISO and HSCLK - D7, D6 and D5. Now that I think about it, the H must stand for "Hardware", if only I had this epiphany sooner.


DS3218MG Servo - Not working with power supply I'm trying to run my DS3218MG Servo Motor with an external power supply and my arduino nano.
I'm using the following code:
#include<Servo.h>
Servo Myservo;
int pos;
void setup()
{
Myservo.attach(3);
}

void loop()
{

for(pos=0;pos<=180;pos++){
Myservo.write(pos);
delay(15);
}
  delay(1000);

  for(pos=180;pos>=0;pos--){
Myservo.write(pos);
delay(15);
}
  delay(1000);

}
According to the datasheet the servo needs a DC 4.8-6.8 voltage. My first attempt was to only use the arduino and no external power supply. So did the following connections:

servo's ground to arduino's ground
servo's + to arduino's 5V
servo's data to arduino's GPIO pin 3

Using this connection works fine and the servo rotatates to the desired positions. However, because the arduino does not supply enough current, i bought a power supply with the following specs:

With that, i did the following connections:

connect the ground of the power supply to arduino's ground (and servo)
keep the data pin
connect + of power supply to servo's +

Unfortunately, the servo does not move with the external power supply. IMO, it should have the right voltage and also supply enough current (at least as much as the Arduino).
Do you see the problem?

@starcat,  regular  usb cable for  powering  arduino


How can I get additional Slave Select pins? I have a project where I want to connect a number of SPI devices, and I'm running out of Slave Select pins (SPI) on the Arduino. So I thought that I could use something like an MCP23S17 to get additional pins and use those as SS pins, but most libraries require to pass the pins when initialising, and it seems that I can't pass the MCP's pins as a function/class argument (or can I?). For example:

U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /*cs*/ 12, /*dc*/ 4, /*rst*/ 6);

So my question is: How can I get more SS pins? Thank you

My solution would be to keep it simple. Use real pins for every SPI SS. Buy an other Arduino board with more pins if you need more pins.

What else is connected to your Arduino board ? Perhaps it is easier to reduce those pins. Almost all analog pins can be digital pins as well. You could use external ADC modules. Perhaps replacing 1-Wire or DHT11 or DTH22 with I2C sensors. Using a I2C display. There are many options to use buttons and leds with a few pins. And so on.


Is it possible to use Adafruit's Circuit Playground Express's 2MB storage in Arduino IDE? I understand that the extra 2MB of memory is for circuit python.  However, I wouldn't mind having access to 2MB of storage and using the Arduino IDE/low level C to access it.  Is that possible?  If so, how?

In their guided tour of the Adafruit Circuit Playground Express, it specifically states:

You can use this in Arduino or CircuitPython to store files.

So yes, it is possible. As far as the how, according to this guide (also from Adafruit), that they have also made a library, Adafruit SPI Flash, which has a bunch of examples showing how to read from, write to, and format the SPI flash whilst retaining compatibility with CircuitPython, among other things.


Arduino IDE Unable to detect ZumoMotor.H ( PIXY PET ) recently i trying to make the pixy pet work for my project. (https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/playing-with-your-pet).

I used the given code for the arduino IDE, but i keep on getting this error Arduino: 1.5.7 (Windows 7), Board: "Arduino Leonardo"

sketch_sep17a.ino:27:24: fatal error: ZumoMotors.h: No such file or directory compilation terminated.

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

The Code, im using, was given by the official maker of the Pixy Pet. Please have a look. ( https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code)

Thank You.

It looks like you need to install the ZumoMotors library.

There's one available at the following link, although I don't know for sure that it's the same one your Pixy Pet requires:

https://github.com/pololu/zumo-shield

That page includes instructions on how to install the libraries. If you get stuck, there's more help in the official Arduino documentation:

http://arduino.cc/en/Guide/Libraries