Button isn't working properly I am new in arduino trying to make race game. My problem is that my button (all buttons) is working sometimes and sometimes not. I am pretty sure that it's because of my code. Could you please help me with it?
Here is my code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int pausebetween = 1;
int spaceBetween = 1;
int maxElemnets = 4;
int obstacleArray[4][2];
int obstacles[4] = {3,3,2,3};
bool gameStart = false;
byte player[8] =
{
 B00000,
 B00000,
 B10100,
 B11110,
 B11111,
 B11110,
 B10100,
 B00000
};
byte obstacle[8] =
{
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111
};
byte enemy[8] =
{
 B00000,
 B00000,
 B00101,
 B01111,
 B00101,
 B00000,
 B00000
};
byte empty[8] =
{
 B00000,
 B00000,
 B00000,
 B00000,
 B00000,
 B00000,
 B00000
};
byte fire[8] =
{
 B00000,
 B00000,
 B00000,
 B11111,
 B00000,
 B00000,
 B00000
};
int mat[2][24] = {
  {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
  {1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
  };
int up = 0;
int down = 0;
int reset=0;
int atack=0;
void setup() {
 pinMode(9, INPUT);
 pinMode(8, INPUT);
 pinMode(7, INPUT);
 pinMode(6, INPUT);
 Serial.begin(9600);
 lcd.createChar(0, player);
 lcd.createChar(1, empty);
 lcd.createChar(2, enemy);
 lcd.createChar(3, obstacle);
 lcd.createChar(4, fire);
 lcd.begin(16, 2);
}
void loop() {
  up  = digitalRead(9);
  down  = digitalRead(8);
  atack  = digitalRead(7);
  reset  = digitalRead(6);
  if(atack){
    for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
            if(mat[j][i]==1){
              mat[j+1][i]=4;
              Serial.println(mat[j+1][i]);
            }
        }
      }
  }
  if(reset){
    clearStage();
    gameStart = true;
  }
  if(gameStart){
    generateObstacles();
    redrawGame();
    moveObstacles();
  }
  delay(1000);

 }

void generateObstacles(){
  int obscount = random(1,4);
  int types[4][2] = {{1,3},{2,1},{1,1},{2,1}} ;
  int type = random(0,4);
  for(int i = 0; i< obscount; i++){
    mat[0][16+i] = types[type][0];
    mat[1][16+i] = types[type][1];
  }
  int spacecount = random(2,5);
  pausebetween = obscount + spacecount;
}
void redrawGame(){
   for(int j = 15; j >= 0; j--){
    for(int i = 0; i < 2; i++){
      lcd.setCursor(j,i);
      lcd.write(mat[i][j]);
    }
  }
}
void clearStage(){
  for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
            if(i!=1 && j!=1){
               mat[i][j] =1;
          }
        }
      }
}
void moveObstacles(){
   for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
           if(mat[i][j]!=0){
            mat[i][j] = mat[i][j+1];
          }else{
            mat[i][j-1]=1;
          }
          if(mat[i][j]==4){
            mat[i][j-1]=0;
            mat[i][j-2]=1;
           }
        }
      }
}

Scheme:

I have two suggestions.

Get rid of the delay(1000); in the loop and replace it with code from the BlinkWithoutDelay example that comes with the Arduino IDE: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.
Debounce the buttons. There are several libraries on Github that simplify this, for example: https://playground.arduino.cc/Code/Bounce.


Arduino Standalone - photo shows incorrect pin wired to MOSI I have been building a standalone Arduino on a breadboard following the guide, Building an Arduino on a Breadboard. The guide is generally very good, however, I have yet to get the Arduino working, for a number of various reasons, be it misinterpreted, or misread instructions (the reset pull-up resistor connected to GND instead of Vcc, Tx to Tx, instead of Tx to Rx (and vice versa), to name but a few issues that I have had to resolve).  However, I am sure that the following issue is not down to my careless interpretation or lack of attention.

Look at the photo taken from the webpage, Building an Arduino on a Breadboard, on the Arduino website, showing the Sparkfun AVR programming adapter connected to the ATmega IC.

The MOSI on the adapter is shown to be connected, via a dark green wire, to pin 16 on the ATmega chip, whereas the instructions say:

  Be sure to refer to the Arduino pin mapping for help wiring this up.

  The MISO pin of your adapter will go to pin 18 or Arduino digital pin    12 of your Atmega chip.
  The SCK pin of your adapter will go to pin 19 or Arduino digital pin    13 of your Atmega chip.
  The RESET pin of your adapter will go to pin 1 of your Atmega chip.
  The MOSI pin of your adapter will go to pin 17 or Arduino digital pin    11 of your Atmega chip.

According to the pinout below, Pin 16 is SS and pin 17 is indeed MOSI.

So, to my mind, the photo is definitely wrong. Indeed I was getting avrdude errors when trying to use a USBasp to load a bootloader, when using the wiring as shown in the photo. When I correctly wired MOSI, from the adapter, to pin 17, the avrdude errors disappeared.

Am I correct in my thinking? Has anyone else attempted to build this circuit, following the instructions on the Arduino website, and come across this issue?

I am just looking for confirmation that I am right, before I contact the owner of the web page.

I have programmed AVR microcontrollers for a while. I would follow the datasheet, instead of the guide you have.

The Atmega168 Pin Mapping shows SS on 16, MOSI 17, MISO 18, SCK 19 and you will also need to connect to RST 1


can i give a vcc to 14v? What is maximum voltage PWM pins can give?
can i give a vcc to 14v?

Since PWM pins are digital outputs, the maximum output voltage is VCC.


Using L298N to control DC Motor I am developing a system where I want to control the direction of the DC motor (12V) from Arduino Mega/Uno. For that, I am using L298N H-bridge chip without the board as shown below.

My question is, do I need to add extra hardware or is it enough on its own?

Thanks in advance!

In theory, this particular device should work on its own.  However you should search for and read the datasheet for it. (I'll leave you to do that yourself, just to make sure you really do read it.)

You should consider a heatsink too by the way, and provision for things like a fuse on the power, and whether you will be using a separate 5V for the logic (again you need the datasheet for that).


Adafruit motor shield + Adafruit stepper not working I have the Adafruit Motor Shield V2 and an Adafruit stepper motor. I have not soldered the shield onto the Arduino (which is an Uno) yet because I don't want to make anything permanent yet. I have the Arduino plugged into a DC wall adapter and have the VIN jumper in the shield, and the green power light on the shield is lit. This is how the stepper is connected.

As you can see in the picture, all the wires from the stepper are plugged in. The order of the wires is what it says it should be on the website, which is orange-pink-red-blue-yellow.  My sketch's code is an adapted version of the StepperExample from the Adafruit motor library. Here's the full code

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_StepperMotor *myMotor = AFMS.getStepper(513, 2);

void setup() {
  Serial.begin(9600);
  Serial.println("Stepper test!");

  AFMS.begin();
  myMotor->setSpeed(5);
}

void loop() {
  myMotor->step(100, FORWARD, SINGLE);
}

But the stepper still doesn't move. Can anyone point out what I'm doing wrong here?

As far as I know, you have to solder the header pins. Here is a nice video demonstrating the assembly: Motorshield V2 assembly


loading custom code onto SparkFun Blynk Board we're trying to add some code to the SparkFun Blynk Board. We don't want to overwrite the firmware, because that allows it to work with the iphone app, but we need to add our own voids and Blynk. Write commands in order to control this servo RC car via wifi wit the Joystick XY. any ideas?

our code:

#include <Servo.h>
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>
//#define BLYNK_PRINT Serial

char BlynkAuth[] = "6dfb81c116d84003a505056239c23559";
char ssid[] = "Linksys23266";
char pass[] = "roboboyz";

Servo servoR;
Servo servoL;

int pos = 90;

void forward()
{
  servoR.write(110);
  servoL.write(110);
}

void turnRight()
{
  servoR.write(80);
  servoL.write(90);
  delay (2000);
}

void turnLeft()
{
  servoR.write(90);
  servoL.write(80);
  delay(2000);
}

void reverse()
{
  servoR.write(70);
  servoL.write(70);
  delay(2000);
}

void Stop()
{
  servoR.write(94);
  servoL.write(94);
  delay(2000);
}

void setup()
{
  Blynk.begin(BlynkAuth, ssid, pass);  // wifi username and password
  servoR.attach(12);
  servoL.attach(13);
  Serial.begin(9600);
  delay(1000);
}

BLYNK_WRITE(V1)
{
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("; Y = ");
  Serial.println(y);
  if(y>220)
  forward();
  else if(y<35)
  reverse();
  else if(x>220)
  turnRight();
  else if(x<35)
  turnLeft();
  else
  Stop();
}

void loop()
{
  Blynk.run();
}

That's not how microcontrollers work. You have one firmware and only one firmware. When you upload firmware you replace the existing firmware. You cannot "add" to it.

Instead you will have to write a new firmware that contains all the code you need to do the entire job.


Changing the tick time in FreeRTOS I am trying to use FreeRTOS's vTaskDelay() function in order to periodically execute tasks.  The latest version of FreeRTOS came with the "tick" time set to 15 ms. Therefore, the smallest resolution I can delay for is 15 ms. I would like to lower this resolution to at least 1 ms.  Is it possible to configure FreeRTOS in this way?  I found this answer online : http://www.freertos.org/FreeRTOS_Support_Forum_Archive/November_2012/freertos_Problem_changing_Tick_time_from_1ms_to_10ms_6231539.html.

But for me, the configTICK_RATE_HZ is not defined and it seems to be using a watchdog timer to enforce the 15 ms resolution. I think the forums are referring to an earlier version.

See the configTICK_RATE_HZ configuration option.
Also note it is better to specify times in milliseconds, rather than ticks, so you can change the tick frequency without effecting the timing (other than the resolution of the time).

The pdMS_TO_TICKS() macro can be used for that purpose, for example to create a delay of 100ms.

const TickType_t xBlockTime = pdMS_TO_TICKS( 100 );
vTaskDelay( xBlockTime );


Sending data from a GUI to an Arduino nano via USB Can somebody point me in the right direction for information on sending data to an Arduino nano?

My project is to send data that is updated from a GUI (presently written in Python) to an Arduino nano that then makes adjustments to a number of servo motors.

I have the servo code working but am presently using potentiometers to control the servo positions & would like the control done via a GUI.

What libraries would I need to be looking at. Have any of you done anything similar.

Thanks

Nic

Arduino Nano supports FTDI i.e. Virtual Serial Port. So all you have to do is initialize the serial communication using pySerial.

When the data is entered into the GUI, store it in some variables. Send the data in variables to Arduino using Serial Communication. You might have design your own communication protocol on top of Virtual Serial Port in order to identify the data.

You can also use the same library to send the acknowledgement or some data from Arduino to PC, if you want.

Hope this helps you.


Setting up 433 MHz Transmitter and Receiver in the same Arduino sketch using Radiohead I have set up a 433 MHz transmitter and receiver pair on one Arduino Uno board. Using the RCSwitch library, I could successfully send and receive signals. Using the Radiohead library however, I could only send and got no reception. I am curious why and grateful for any help.

Here is the sketch. Both receiver and transmitter draw power from Arduino 5V and GND. The DATA pin of transmitter is attached to pin 12 of Arduino. The DATA pin of receiver is attached to pin 11. These appear to be "hard-coded" in the Radiohead library. My reciever has an additional chip select (CS) pin which I have wired to pin 10.

Using the serial monitor, it looks like transmitter and receiver are initialized without problem and message is sent. I have used the RCSwitch library with transmitter and receiver on the same board and that worked, (i.e. messages sent were received correctly) so I am curious why the issue with Radiohead.

// Include RadioHead Amplitude Shift Keying Library
#include <RH_ASK.h>
// Include dependent SPI Library
#include <SPI.h>

// Create Amplitude Shift Keying Object
RH_ASK rf_receiver;
RH_ASK rf_transmitter;

void setup()
{
    // Initialize ASK Object
    if (!rf_receiver.init())
        Serial.println("Failed to initialize receiver.");
    if (!rf_transmitter.init())
        Serial.println("Failed to initialize transmitter.");

    Serial.begin(9600);

    digitalWrite(10, HIGH);   // enable CS on some receiver devices
}

void loop()
{
    const char *msg = "Hello world!";
    rf_transmitter.send((uint8_t *)msg, strlen(msg));
    rf_transmitter.waitPacketSent();
    Serial.print("Message sent: ");
    Serial.println((char*)msg);

    uint8_t buf[12];
    uint8_t buflen = sizeof(buf);

    if (rf_receiver.recv(buf, &buflen))
    {
      Serial.print("Message received: ");
      Serial.println((char*)buf);
    }
    else
    {
      Serial.print("No message rec'd: ");
      Serial.println(*&buflen);
      Serial.println((char*)buf);
    }

    delay(1000);
}

The answer can be found in the source code 0f RH_ASK.h (you should read the well made documentation before using this library):

  At present only one instance of RH_ASK per sketch is supported.

So you will have to write such an extension yourself, use two Arduinos or use another lib for testing.


Bluetooth module not working I was following a tutorial on YouTube to build a Bluetooth car with Arduino.
#include <AFMotor.h>

//initial motors pin
AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);

char command;

void setup()
{
  Serial.begin(9600);  //Set the baud rate to your Bluetooth module.
}

void loop(){
  if(Serial.available() > 0){
    command = Serial.read();
    stop(); //initialize with motors stoped
    //Change pin mode only if new command is different from previous.
    //Serial.println(command);
    switch(command){
    case 'F':
      forward();
      break;
    case 'B':
       back();
      break;
    case 'L':
      left();
      break;
    case 'R':
      right();
      break;
    case 'S':
      stop();
      break;
    }
  }
}

void forward()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor4.setSpeed(255);//Define maximum velocity
  motor4.run(FORWARD); //rotate the motor clockwise
}

void back()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void left()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(FORWARD);  //rotate the motor clockwise
}

void right()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwiseclockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void stop()
{
  motor1.setSpeed(0); //Define minimum velocity
  motor1.run(RELEASE); //stop the motor when release the buttonbutton
  motor4.setSpeed(0); //Define minimum velocity
  motor4.run(RELEASE); //stop the motor when release the button
}

Here's the schematic:

I didn't use the resistor, I used 4 aa batteries, and I used 2 motors instead of 4, but the bluetooth module is flashing.

I used an HC-05 module to do over-the-air programming for an Arduino MCU some time back, and documented the procedure in this post.  Maybe that will help?


Breaking out of while loop using IR remote input I'm trying to control a series of LEDs using an IR remote. I have a problem when I try to play a sequence with the LEDs where they all light up in a line and turn off accordingly. I loop through the sequence and I am trying to make it so the instant I press a button on the remote it breaks out of that sequence. The issue lies in the Flash(); function, I think. What can I do?

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

int recvPin = 11;
IRrecv irrecv(recvPin);
decode_results results;

#define BUTTON_ON 0xF076C13B    // codes for different buttons on the remote
#define BUTTON_OFF 0xFF9186B7
#define BUTTON_R 0xE5CFBD7F
#define BUTTON_G 0x8C22657B
#define BUTTON_B 0x2A89195F
#define BUTTON_FLASH 0x35A9425F

int rLED = 5;
int gLED = 4;
int bLED = 3;
int stR = LOW;  // intital state of red LED
int stG = LOW;  // intital state of green LED
int stB = LOW;  // initial state of blue LED
int flash = false;

void setup() {
  Serial.begin(9600);   // Status message will be sent to PC at 9600 baud
  pinMode(rLED, OUTPUT);
  pinMode(gLED, OUTPUT);
  pinMode(bLED, OUTPUT);

  irrecv.enableIRIn();
}

void Flash() {    // flashing function
  while (flash == false) {
    digitalWrite(rLED, LOW);
    digitalWrite(gLED, LOW);
    digitalWrite(bLED, LOW);
    digitalWrite(rLED, HIGH);
    delay(75);
    digitalWrite(gLED, HIGH);
    delay(75);
    digitalWrite(bLED, HIGH);
    delay(75);
    digitalWrite(rLED, LOW);
    delay(75);
    digitalWrite(gLED, LOW);
    delay(75);
    digitalWrite(bLED, LOW);
    delay(75);
    stR = LOW;
    stG = LOW;
    stB = LOW;
    if (results.value == BUTTON_OFF)    // attempting to make it so when i press the OFF button on the remote,
    {                                   // the loop breaks/stops and I can go back to pressing any button on
      break;                            // the remote
    }
  }
}

void loop() {
  if (irrecv.decode(&results))
  {
    if (results.value == BUTTON_ON)
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, HIGH);
      digitalWrite(bLED, HIGH);
      stR = HIGH;
      stG = HIGH;
      stB = HIGH;
    }
    if (results.value == BUTTON_OFF)
    {
      digitalWrite(rLED, LOW);
      digitalWrite(gLED, LOW);
      digitalWrite(bLED, LOW);
      stR = LOW;
      stG = LOW;
      stB = LOW;
    }
    if (results.value == BUTTON_R)
    {
      digitalWrite(rLED, !stR);
      stR = !stR;
    }
    if (results.value == BUTTON_G)
    {
      digitalWrite(gLED, !stG);
      stG = !stG;
    }
    if (results.value == BUTTON_B)
    {
      digitalWrite(bLED, !stB);
      stB = !stB;
    }
    if (results.value == BUTTON_FLASH)
    {
      Flash();    // calling flash func
    }
    irrecv.resume();
  }
}

Replace delay with millis in Flash().

You do this by making every delay it's own state and give each state a number. Then inside flash you check which state you are in to set the LEDs and how long you have been in it to trigger the next state.

boolean flashing = false;
int flashingState = -1;
long nextFlashingState = 0;

void Flash() {    // flashing function
  if(!flashing ){
    flashingState =-1;
    return;
  }

  long ms = millis();
  switch(flashingState ){
  case -1:
    flashingState =0;
    nextflashingState = ms+75; //init "timer"
    //fallthrough
  case 0:
    digitalWrite(rLED, LOW);
    digitalWrite(gLED, LOW);
    digitalWrite(bLED, LOW);
    digitalWrite(rLED, HIGH);
    if(nextflashingState < ms){
        flashingState =1;
        nextflashingState +=75;
    }
    break;
 case 1:
    digitalWrite(gLED, HIGH);
    if(nextflashingState < ms){
        flashingState = 2;
        nextflashingState +=75;
    }
    break;
 case 2:
    digitalWrite(bLED, HIGH);
    if(nextflashingState < ms){
        flashingState = 3;
        nextflashingState +=75;
    }
    break;
  case 3:
    digitalWrite(rLED, LOW);
    if(nextflashingState < ms){
        flashingState = 4;
        nextflashingState +=75;
    }
    break;
  case 4:
    digitalWrite(gLED, LOW);
    if(nextflashingState < ms){
        flashingState = 5;
        nextflashingState +=75;
    }
    break;
  case 5:
    digitalWrite(bLED, LOW);
    if(nextflashingState < ms){
        flashingState = 0;
        nextflashingState +=75;
    }
    break;
  }
}

I used state -1 as the init state to start the timer, the case block will fall through to the next case. The millis() function returns the number of milliseconds since the arduino booted up (it overflows every ~1.5 months). So when I start a timer I set the the nextFlashingState to the time when it should start the next state.

Then in loop you call it every time.

void loop() {
  if (irrecv.decode(&results))
  {
    if (results.value == BUTTON_ON)
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, HIGH);
      digitalWrite(bLED, HIGH);
      stR = HIGH;
      stG = HIGH;
      stB = HIGH;
    }
    if (results.value == BUTTON_OFF)
    {
        flashing =false;
      digitalWrite(rLED, LOW);
      digitalWrite(gLED, LOW);
      digitalWrite(bLED, LOW);
      stR = LOW;
      stG = LOW;
      stB = LOW;
    }
    if (results.value == BUTTON_R)
    {
      digitalWrite(rLED, !stR);
      stR = !stR;
    }
    if (results.value == BUTTON_G)
    {
      digitalWrite(gLED, !stG);
      stG = !stG;
    }
    if (results.value == BUTTON_B)
    {
      digitalWrite(bLED, !stB);
      stB = !stB;
    }
    if (results.value == BUTTON_FLASH)
    {
        flashing =true;
    }
    irrecv.resume();
  }

  Flash();
}


Is arduino a single board computer? First excuse me if tags are not reflecting the content,

While watching a video about single board computer (SBC) I got confused that it doesn't mention arduino as SBC. I always considered it as SBC.

After digging around a bit I got more confused. It seems single board computer is where processor, memory, I/O this things are built on single circuit board rather than using expansion card attached on to a circuit board (motherboard).
According to that is not arduino a SBC? It's processor, memory,storage are on single ATMega32A (for uno) attached on a single board which provides some I/O port (I/O pin, USB, UART, I2C etc.).

From some digging I learned that arduino code runs on bare metal unlike SBC like Rpi and that's the reason for it not being SBC. This seems weird reason.

(1) Is Arduino a SBC?
If (1) is no then next questions are,

(2) Is Being less powerful is the cause? If yes where do you draw the line?

(3) Not having an OS hosted environment for execution is the cause?

If (3) is Yes then,

(4) Arduino has some bootloader code to load the program through USB. Isn't it  kinda like OS, I admit it's not giving some nice api for h/w usage but is it all?

This link comment section kind of started a debate but ended without giving clear answer about my question.

The Arduino isn't a computer. It is a programmable microprocessor / microcontroller.

Generally a computer can run multiple applications where most programmed devices like the Arduino are running only one program. This is not an official definition but it is one way to differentiate.

It can be difficult to draw a line where it is one but not the other.

  (4) Arduino has some bootloader code to load the program through USB.
  Isn't it kinda like OS, I admit it's not giving some nice api for h/w
  usage but is it all?

No that isn't like an operating system. The Arduino does not have a real operating system when compared to a computer system. And someone being able to load in a new program is just changing the current single program that is runnable.

  An operating system (OS) is system software that manages computer
  hardware and software resources and provides common services for
  computer programs.

I think the programs being plural is an important factor, but this is only my opinion.

There is no one definition so you will get a number of different opinions. And most will be reasonable.


Float to int conversion not working right in method using varargs I am trying to convert a floating point number to an integer, but it seems like the conversion is not working properly.
I am using the math library to calculate the power of 10 based on the number of varargs, where the first argument is the number of arguments followed by the varargs.
int charsToIntValue(int argc, ...) {
  int multiplier = (int) pow(10, argc - 1);
  va_list argp;
  va_start(argp, argc);
  Serial.println(multiplier);
  ...
  va_end(argp);
}

For some reason, multiplier is always stored as 1 less than the actual result.
e.g. If charsToIntValue(4, 1, 2, 3, 4) is executed, the multiplier is stored as 999 rather than 1000. However, when it is printed as a float, it does show 1000.00. And whenever I change it to a constant ((int) pow(10, 3)) it works fine, returning 1000.
I've tired storing the value of argc into a local variable but that didn't seem to change anything.
Full project is here for context: https://github.com/Pyrodron/charger-destination-board
File in question is charger-destination-board.ino; lines 32 to 51

With some inspiration from timemage's comment, I decided in the long run to implement my own power function that takes two int arguments and returns an int. Rather than use the pow function in the <math.h> library which returns a double when I only need an int.
int power(int x, int y) {
  return y == 0 ? 1 : x * power(x, y - 1);
}

Now the program works as intended!


How to install Arduino IDE on Raspberry Pi How do you install the Arduino IDE on the Raspberry Pi running an ARM version of Ubuntu or Raspbian? There doesn't seem to be any official ARM release. Both distros have an "arduino" package in their standard repos, but it only includes an ancient 1.0 version that's missing a lot of features.

Arduino at http://playground.arduino.cc/Linux/Raspbian recommends:

sudo apt-get update && sudo apt-get install arduino

but indeed warns that the version is old:

  Note: This will install an old version of Arduino, and may not support
  some of the newer boards. You can not download a newer version from
  the website, because there is no ARM version. -- Arduino wiki on Raspbian

Looking at the raspbian respository at http://archive.raspbian.org/raspbian/pool/main/a/arduino/ currently lists 1.0.5

There are folks working newer versions of Arduino for ARM at https://github.com/arduino/Arduino/issues/3334 but it isn't finished yet.


Building an adjustable low frequency PWM controller with Arduino I am looking for a way to create an adjustable PWM controller capable of modulation frequency from 0-100 (more preferably 0-1000) Hz, duty cycle from 0-100%, and able to accept a voltage range of 5-30V DC. I have looked through Sparkfun and Adafruit for product or PWM shields capable of this and I have yet to find one. Some servo shields can be programmed down to 50Hz and arduino itself can be slowed to like 30Hz using timer0 and timer1 changes. However none of these options make it easy to vary frequency and none of them can accept much more than 6V.

I have searched far and wide and found a few interesting things:

1) http://www.instructables.com/id/The-ultimate-PWM-driver-for-many-applications/
 This instructable shows an analog un-sensored PWM driver. It would get the job done here however, I need a way to read my Frequency and Duty Cycle

2) https://www.electronicsblog.net/arduino-frequency-counterduty-cycle-meter/

Here there is a way using pulsein() and other arduino functions to read both frequency and duty cycle as seen above. But then this is also assuming you're PWM voltage is 5V. So maybe you use a 5V regulator on the signal into the arduino? Would something that simple work or would it skew the signal and prevent accurate measurements?

Obviously, if anyone has a better idea I'm open to it. I've been searching for a solution for some time. The trouble really seems to be the low frequency PWM request.

The ATmega328 in the Arduino Uno has a 16-bit timer (Timer/Counter 1) which can do PWM. It has a prescaler that can divide by 1024.  The lowest frequency that it can generate is about 0.12 Hz:

16MHz / 1024 / 65535 / 2 = 0.1192 Hz

We change the PWM frequency by changing the "top" value. For higher frequencies, lower the top value, and/or pick a smaller prescaler.

(And, really, what does 0 Hz PWM even mean?!? :-)

The duty cycle can vary from 0-100%, with the resolution changing with the specific frequency you generate.

As for the high-voltage... use a motor driver, or darlington, or hexfet, or whatever...

I'm confused as to why you're reading the frequency. With the 16MHz crystal, you set it and you get what you asked for (within the crystal tolerances, temperature, etc.)

At least, that's how I think it works.
Good luck!


Why doesn't my 7 segment update every second like in the program? I used sevseg.h library to write numbers to my 4 digit seven segment. The display should update every second with the current time since program started running. This is my code so far:

#include <SevSeg.h>

SevSeg sevseg;

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
}

void loop() {
    unsigned long timer = millis();
    for (int i = 0; i < 500; i++) {
        sevseg.setNumber(timer/1000, -1);
        sevseg.refreshDisplay();
        delay(2);
    }
}

Since the delay is 2, the for loop loops 500 times, resulting in 1000ms or 1 second. The current second is written to the display. For some reason, the display is updated every other 5 or 6 seconds. Why is this occurring? How can this be fixed so that my display turns into a stopwatch in a way?

This is the code that fixed the issue:

  #include <SevSeg.h>
  SevSeg sevseg;

  void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
  }

  void loop() {
    unsigned long timerGlobal = millis();
    sevseg.setNumber(timerGlobal/1000, -1);
    sevseg.refreshDisplay();
  }

In this, no delays are needed. millis is divided by 1000 and the integer second is drawn on the display. Proved to be much easier than I previously thought.


Send String to a function inside a class I made a little class for handling menus. When creating a new instance, I pass a reference to the oled object made in main.cpp. Yet when I want to render a string using a variable, it throws an error. But I can pass a string directly to the render function with no problems. See comments in the code for what is working and what is not.

#include "Arduino.h"
#include "U8glib.h"
#pragma once

class Menu {
  U8GLIB_SSD1306_128X64& oled;

  public:
    Menu(U8GLIB_SSD1306_128X64& oled): oled(oled) {
      this->oled = oled;
    };
    void render() {
      this->oled.firstPage();
      do {
        String text = "test2";
        this->oled.setFont(u8g_font_unifont);
        this->oled.setPrintPos(0, 20);
        this->oled.drawStr(text); // not working
        this->oled.drawStr(text.c_str()); // not working
        this->oled.drawStr("works"); // works
      } while (this->oled.nextPage());
    }
  };

In the case of this->oled.drawStr(text); the error is:

error: no matching function for call to 'U8GLIB_SSD1306_128X64::drawStr(String&)

In case of this->oled.drawStr(text.c_str()) the error is:

error: no matching function for call to 'U8GLIB_SSD1306_128X64::drawStr(const char*)

How I create the instance in main.cpp:

U8GLIB_SSD1306_128X64 oled(U8G_I2C_OPT_NONE);
Menu menu(oled);
menu.render();

Try with the new version, U8g2lib.

With that version, you can write code like this:

String t1 = "Grow";
String t2 = "Room";
u8g2.firstPage();
do {
  u8g2.setFont(u8g2_font_logisoso24_tf);
  u8g2.drawStr(32, 24, t1.c_str());
  u8g2.drawStr(32, 60, t2.c_str());
} while(u8g2.nextPage());


How to pass rx/tx led outputs to a shield I have an Arduino Uno. I am building a custom shield and was wondering how I would connect two of the LEDs on the shield to the TX / RX LEDs on the Uno. Digital pins 0 and 1 seem obvious, but after further research, it appears that they are not for this.

In better terms, I want two LEDs on my shield that replicate the TX / Rx LEDs on the Arduino Uno.

How would I do this?

The TX/RX LEDs on the Uno are not connected to the main MCU but are instead connected to the USB communication chip, be it a FTDI or ATmega16U2. You would need to solder wires to the appropriate connections on the board and then connect them to the shield in question.


Read only one line in SD card I have some C++ code, but I cant convert it to Arduino language.
I just want to ask, what is the same as getline() (C++ code) function in Arduino?

I just wanted to get the first line in my SD card...
I can only display all text inside my SD card...

Example:

line1   <-   only this line should display(and this line will delete in text
             file... but that is another issue... i will just focus to get the
             line1 and get the value)

line2

line3

line4

line5

This code displays all lines

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

    File myFile;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port                          only
       }

       Serial.print("Initializing SD card...");

       if (!SD.begin(4)) {
         Serial.println("initialization failed!");
         while (1);
       }
       Serial.println("initialization done.");

       // open the file. note that only one file can be open at a time,
       // so you have to close this one before opening another.
       myFile = SD.open("test.txt", FILE_WRITE);

       // re-open the file for reading:
       myFile = SD.open("test.txt");
       if (myFile) {
         Serial.println("test.txt:");

         // read from the file until there's nothing else in it:
         while (myFile.available()) {
           Serial.write(myFile.read());
         }
         // close the file:
         myFile.close();
       } else {
         // if the file didn't open, print an error:
         Serial.println("error opening test.txt");
       }
     }

     void loop() {
       // nothing happens after setup
     }

There is no builtin way to do that but you got all the necessary tools at hand.

End of line should be signaled by a decimal 10, aka LF(Line Feed) character.
So what you do is keep reading until you encounter LF or end of file, which then is the entire line you want to read.

while (file.available() && file.peek() != 10) // peek returns the next character without incrementing the read index
    file.read();

This code does exactly that. Now you could either store the read bytes in a buffer (big enough!) right away or instead find out the number of bytes beforehand to create a precisely sized buffer afterwards and use the read(buffer, length) overload to read all bytes at once.

Please keep in mind that the LF character has to be there in order to be read. So if you are the one creating the files, be sure to place it. (most desktop text editors do that for you)

Example:

char buffer[20];
uint8_t i = 0;

while (file.available() && file.peek() != '\n' && i < 19)    // note how this also prevents the buffer from overflowing (18 max to leave space for '\0'!)
{
    buffer[i] = file.read();
    i++;
}
buffer[i + 1] = '\0';    // it is good practice to end strings with a terminating NULL character


Connect arduino with C# Desktop application wireless using esp8266 I am using wifi module esp8266 , what is easiest way to communicate arduino with desktop application and make a wireless communication between them. Please refer any useful resources

Either use TCP or UDP to communicate. With TCP one end will be the server and will open a socket (your choice) and the other end will connect to it (much like communicating with a web server). With UDP both ends will open a socket and send discrete packets backwards and forwards.

How you would do either of those in C# is outside the scope of this website.

The ESP8266 has AT commands that perform the task for you - chiefly AT+CIPSTART.

The simplest to understand is probably TCP communication where you can just follow any of the myriad of website based examples. However instead of communicating with a website using HTTP you will be communicating with your own server software written in C# using your own custom designed protocol.

A simpler option may be to use a real web server as a "man in the middle" to which both the ESP8266 and your C# program communicate. That website could become a database back-end for your program.

Of course, what you decide to do depends entirely on how complex your program is and what data it is you want to transfer.


time error in controlling a clock I have designed and 3d printed a clock.

I am controlling the clock using a Arduino sketch running on a Attiny2313. The stepper motor I am using is a 12v 1:12 ratio stepper. The total number of steps per revolution are 288.

The problem I am facing is that I am unable to get the time right. I have got the steps per revolution of the minute ring bang on, but some how the motor gains 10/11 minutes every 24 hours.

I have used a lot of the code from the stepper motor library. I am not using the stepper motor library as the code gets larger than what can fit into the 2k attiny memory.

Any help is appreciated.

int number_of_steps = 288;
int motor_pin_1 = 9;
int motor_pin_2 = 10;
int motor_pin_3 = 11;
int motor_pin_4 = 12;
int ledpin = 13;
int delayTime = 4;
int buttonPin = 4;
int buttonState = 0;
int enablepin = 8;
int whatspeed = 40;
int last_step_time =0;
int step_number = 0;
[color=red]int blinkDelay = 939; [/color]
int step_delay = 60L * 1000L / number_of_steps / whatspeed;
int step_direction = 0;
void setup() {

 pinMode(motor_pin_1, OUTPUT);
 pinMode(motor_pin_2, OUTPUT);
 pinMode(motor_pin_3, OUTPUT);
 pinMode(motor_pin_4, OUTPUT);
 pinMode(buttonPin,INPUT);
 pinMode(ledpin, OUTPUT);
 pinMode(enablepin,OUTPUT);

}

void loop() {
 buttonState = digitalRead(buttonPin);
 if (buttonState ==HIGH){
   enablemotor();
   movestep(20);
   digitalWrite(ledpin,HIGH);
 }
 else{
   digitalWrite(ledpin,LOW);

   for (int xx = 0; xx<59;xx ++){

     enablemotor();
     movestep(42);
     //delay(100);
     motoroff();
     blinkk();
   }
   enablemotor();
   movestep(89);//85;

   motoroff();
   blinkk();
  //delay(3000);
 }
}

void enablemotor(){
 digitalWrite(enablepin,HIGH);
}

void movestep(int steps_to_move){
 int steps_left = abs(steps_to_move);

 if (steps_to_move > 0) {
   step_direction = 1;
 }
 if (steps_to_move < 0) {
   step_direction = 0;
 }

 while(steps_left > 0) {
   // if (millis() - last_step_time >= step_delay ) {
   //last_step_time = millis();
   if ( step_direction == 1 ){
     step_number++;
     delay(step_delay);
     if (step_number == number_of_steps) {
       step_number = 0;
     }
   }
   else {
     if (step_number ==0){
       step_number = number_of_steps;
     }
     step_number--;
   }
   steps_left--;

   stepmotor(step_number % 4);

   //}
 }
}

void stepmotor(int thisStep){

 switch (thisStep) {
 case 0:    // 1010
   digitalWrite(motor_pin_1, HIGH);
   digitalWrite(motor_pin_2, LOW);
   digitalWrite(motor_pin_3, HIGH);
   digitalWrite(motor_pin_4, LOW);
   break;
 case 1:    // 0110
   digitalWrite(motor_pin_1, LOW);
   digitalWrite(motor_pin_2, HIGH);
   digitalWrite(motor_pin_3, HIGH);
   digitalWrite(motor_pin_4, LOW);
   break;
 case 2:    //0101
   digitalWrite(motor_pin_1, LOW);
   digitalWrite(motor_pin_2, HIGH);
   digitalWrite(motor_pin_3, LOW);
   digitalWrite(motor_pin_4, HIGH);
   break;
 case 3:    //1001
   digitalWrite(motor_pin_1, HIGH);
   digitalWrite(motor_pin_2, LOW);
   digitalWrite(motor_pin_3, LOW);
   digitalWrite(motor_pin_4, HIGH);
   break;
 }

}

void blinkk(){
 for (int i = 0 ; i<30;i++){
   buttonState = digitalRead(buttonPin);
   if (buttonState ==HIGH){
     break;
   }
   else{
     digitalWrite(ledpin, HIGH);   // set the LED on
     delay(blinkDelay);  // 968           // wait for a second
     digitalWrite(ledpin, LOW);    // set the LED off
     delay(blinkDelay); //968
   }
 }
}

void motoroff(){
 digitalWrite(enablepin,LOW);
 digitalWrite(motor_pin_1, LOW);
 digitalWrite(motor_pin_2, LOW);
 digitalWrite(motor_pin_3, LOW);
 digitalWrite(motor_pin_4, LOW);

It is very difficult to accurately control timings with delay(),
because you have to account for the time needed to execute the rest of
the code, including interrupts. You can easily have better accuracy by
using millis() like this:

static unsigned long last_step_time;
unsigned long now = millis();
if (now - last_step_time >= step_delay) {
    do_one_step();
    last_step_time += step_delay;
}

This is almost what you have commented out in your own code, except that
millis() should be called only once per iteration, hence the now
variable.

This may still have less than perfect accuracy due to your clock source.
If your Arduino is clocked from a quartz you should be able to get
decent timing accuracy. If it is clocked from a ceramic oscillator you
are out of luck. In any case, you can always improve the accuracy by
calibrating your clock: you measure its drift and correct for it in
software. Then you have only to worry about thermal fluctuations of the
clock frequency, which should not be an issue with a quarts.

For best accuracy, you can use either an RTC or a watch crystal
connected directly to your ATmega chip. This last solution is only
possible if you go for a bare microcontroller, without the Arduino
board. See this answer
for more details about this option, as well as the way to correct
for the drift in software.


Structure Array Initialization I'm trying to initialize a char array which is part of a structure as follows:

#define TRUE 1
#define FALSE 0

struct s_field_def { // structure for managing display field
  char f_txt[16]; // option text
  bool f_inhibit; // set this to inhibit updating of the field on the display
};

enum field_name {F_STATE, F_PULSE};

void setup() {

  // initialize display fields structure
  struct s_field_def fields[2]; // initialize the display fields
  fields[F_STATE] =  {"HALTED", FALSE}; // displays the current run state
  fields[F_PULSE] =  {"@", TRUE}; // displays indicator of system running
}

void loop() {

}

The initialization of the structure is producing an error at these lines:

  fields[F_STATE] =  {"HALTED", FALSE}; // displays the current run state
  fields[F_PULSE] =  {"@", TRUE}; // displays indicator of system running

no match for 'operator=' (operand types are 's_field_def' and '<brace-enclosed initializer list>')

What am I doing wrong here?

As explained in Michel Keijzers' answer, you cannot use the = operator
to assign something to a string (a character array). However, you can
initialize a string using =. There is an important distinction
between assignment, which you can do anywhere in a program, an
initialization, which can only be done at the time you define a
variable.

For example:

int i = 2;  // initialization

void setup() {
    i = 4;  // assignment
}

In your specific case, you can initialize fields as follows:

struct s_field_def fields[2] = {
    {"HALTED", FALSE},  // displays the current run state
    {"@", TRUE}         // displays indicator of system running
};


Arduino YUN server crashes after few hours! I have made a simple server using the YUN SERVER and CLIENT Libraries./
The server runs on a loop and waits for a client to connect. After connection it sends the client a simple message and then disconnects the client.

#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

#define PORT 6666
YunServer server(PORT);
int pin =13;

void setup() {
  Serial.begin(115200);
  Bridge.begin();
  server.noListenOnLocalhost();
  server.begin();
}
void loop() {
  YunClient client = server.accept();
  if(client.connected())
  {
    digitalWrite(pin,HIGH);
    //startup
    startup_msg(client);
  }
  else
    digitalWrite(pin,LOW);
    delay(500);
}
void startup_msg(YunClient client)
{
    client.print("SAndTerm");
    client.stop();
}

Well this code runs smoothly for few hours. But after that, it stops responding to any client request. I guess the server crashes.
I have to restart the YUN to get it working again.

Is there anyway I can run this without it getting to crash?
Well I want it to be running just like a normal server would.

Updating your YUN might solve this problem. It is recommended to update it after you buy it because they usually come with old firmware. Make sure its up to date.
Here a link on how to do this

Another thing to try is to add delay(50); at the end of the loop() function. It prevents the processor from doing lots of work.


DS1302 as a counter/count-up timer I would like to use the DS1302, as a count up timer.
My goal is to have the arduino time the amount of me driving my car.
So it DS1302 will be used a count-up timer ie accumulate time. however when the car is switched off, I don't want to lose the value, and when I use my car again I would like to the time to continue accumulating. The resolution can be in minutes, as this will probably be the best.

I would like something like an odometer of a car, except its going to be the time, instead of distance.

Q: Can this be done with the DS1302 Module? and also how can I do this? Is there a sample code for a count-up timer?

Do you mean only accumulate during powered/driving, or also during standing still?

If the former, just get the start time in setup, then in loop continuously get the time and calculate the difference between it and the time read in setup. Since you don't know when power is lost you need to continually write the elapsed time to some form of non-volatile memory. You could use the Arduinos EEPROM, but that can wear out over time. It's better the use the DS1302s 31 byte of battery backed RAM. Next time the arduino starts up you need to read out this value and add this to the difference.

In case of the latter, you can halt the DS1302 so it stops incrementing time.


WS2812 HELP. Need name of Unkown component https://i.imgur.com/u5SIvLo.png

I need to know what the little "thing" that i marked in blue is and how it works.

Thanks.

picture taken here: https://www.sparkfun.com/products/13282

It's most likely a decoupling capacitor meant to smooth out the voltage supply to the internal control chip.

This is standard practice to add to any chip. Power cables create a small bit of parasitic inductance in relation to the area between the lines. This inductance can induce voltage spikes when current draw changes significantly. A capacitor shrinks the effective area between the power lines.

This is also why the general advice for decoupling capacitors is to put them as close to the chip as physically possible.


Do I need an external power supply for the SG90 micro servo? I have a Uno R3 and although I can add an external power supply for the SG90 micro servo it would make the project more complicated. Can I power the servo using the 5v pin of the Uno R3?

I measured the current and it does not seem to pass 160mA and in normal use, it uses only 60mA.

I'm not sure if the data sheet for every SG90 servo is the same, but if you look at this one, SG90 Specifications, you'll see the "stall current" can be between 570mA and 730mA. You may want to test your servo under this condition before deciding to power it with an Uno.


Can you make it so, when your phone connects to the Hc-05 on a Arduino, a variable changes? So whenever my phone gets close, and it connects to the Hc-05, the Arduino changes a variable? I want to avoid the use of apps, where the user has to do anything after first time connecting. The project is an automatic door opener, wherein the user for whatever reason can't use their hands, like if they have groceries in their hands.

Thank you for your time

Detecting successful connection with HC-05

The HC-05 can be configured to do what you are after.

Search for "POLAR" in the AT set documentation.

AT+POLAR=0,1

should be what you need as per their examples.
Hook up PI09 to your arduino and wait for it to go HIGH.
You may even want to wake up your arduino with an hardware interrupt using that signal.

Depending on your package, this may require soldering to the HC-05 module.
The datasheet features a pinout in that case. Be sure to checkout the manual of your breakout board first.


Can I include a header file into a new header file? Can I include a header file into a new header file that I created? I put #include <MCP23S17.h>. I want to create a another header file.

Yes, a header can include another header.  But if you are using the Arduino IDE and the headers aren't in the same folder, then you'll also need an #include line for it in the .ino file.


Unexpected output for simple code involving calculating a time interval of 10ms I had written some code that involved doing something after 10 milliseconds had elapsed, however it was performing unexpectedly. Upon debugging, I think I have identified the error, and I wrote some code with just that block:
unsigned long int newtime=0;
unsigned long int prevtime=0;
int time;
void setup()
{
  Serial.begin(9600);
}

void loop()
{
newtime=millis();
time=newtime-prevtime;
if(time==10){
  Serial.println(prevtime);
  prevtime+=10;
}

}

The serial monitor "freezes on 150. it shows the values 0,10,20...as expected but it freezes on 150...and then nothing happens.
What exactly is causing this?

The problem is, that you are filling up the Serial buffer rather fast, because you try to send ASCII numbers every 10ms at only 9600ms. When the buffer is full, Serial.println() will wait, until there is enough space free in the buffer for the current data. That makes your loop lasting significantly longer.
In that case the time, where the time is exactly 10 is missed. Thus the code does nothing at that point, until time rolls over and gets 10 again (48 days I think).
While you can mitigate the problem by using a higher baudrate, the main problem is still
if(time==10){

You have only provided an example code. Your real code might sometimes take longer than 10ms out of some other reason (actually this already gets critical, when the loop takes longer than 1ms, since it then might already miss the one moment, where time is 10). To futureproof your code and make sure, that you don't hunt down the same bug again and again, you should do, what you were told in the comments, and use
if(time>=10){

Depending on your code the event will still happen after 10ms the absolute most of the time. But this variant also doesn't break, if the loop takes longer than 10ms sometimes.


How to interface with a mobile phone LCD? I have a LG mobile phone LCD (model:KG 285). How could I interface with this LCD with an AVR microcontroller? Also, why are there articles on websites showing only interfacing of Nokia LCD?

How could I interface with this LCD with an AVR microcontroller?

Mobile phone manufacturers do not usually release information about the hardware they use. The first step would be looking if it has a controller on-board. Without a controller board you can't use the LCD, an Arduino can't handle being a controller. If it has a controller you have to update your post with pictures of the screen then we can help you a bit more.

  Also, why are there articles on websites showing only interfacing of Nokia LCD?

Nokia LCD's are easy to interface with, they're cheap and really good quality that's why they're popular that means there are more websites showing how to use them. As a beginner it is a good idea to use popular things, people can then help more.


Why I cannot connect directly Arduino UNO and Xbee S2? I'm connecting Arduino UNO to Xbee S2 Zigbee module directly, and X-CTU cannot find Xbee module via arduino. i'm not using shield, it finds with non-arduino board connecter, but not by arduino UNO board.

i checked all parameters like baud rate, etc.., wirings, and it seems no problem at all, but it keeps msg like 'reset your radio module' and even i swtiched pin 5 and GND, it doesn't works.

what i have to do?

If you want X-CTU to see the Xbee while it's connected to the Arduino, you have to connect the Arduino's reset pin to ground. This bypasses the Arduino's MCU and allows the Arduino to act as a USB to serial adapter.

Also don't forget to connect the Arduino's Tx to the Xbee's Tx when it's connected like this, and likewise with the 2 Rx's.


Arduino Micro project with Bluetooth low energy I created my project prototype with Arduino Micro and Adafruit Bluetooth low energy device.

Now I need to develop the prototype to production (like a small USB device). I just need Rx, Tx, 3V pin from Arduino Micro.

I started design with ATmega32U4, USB and BLE by using Fritzing IDE. I am confused with Arduino Micro parts like reset, bootloader and other pins. Is there any problem if I leave the unwanted pins from Arduino unconnected, for my project? Will it work correctly like a Arduino micro?

This is my first PCB design. Please help me to design a final PCB with the unwanted pins left unconnected.

I have started to look at the Arduino Uno schematics, which are free on the website. To make an Arduino is very simple, just need the chip, crystal, a few capacitors and that's it.

Try to copy the same schematics then add the Bluetooth to the RX and TX pins, but be careful about the 3.3V as you don't want to fry your Bluetooth module :)


arduino suddenly shows “avrdude: ser_open(): can't open device ”\\.\COM3" after last upload I am using arduino uno to make a sound detector. I uploaded a program, found error in the code that it returns unintended numbers unreasonably big. I also think I used wrong code for the module, but it was connected in the way that can work properly with the proper code.

The code I uploaded was:

const int ledPin =13;
const int middleValue = 512;
const int numberOfSamples =128;

int sample;
long signal;
long averageReading;

long runningAverage = 0;
const int averagedOver = 16;

const int threshold=400;

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

void loop(){
    long sumOfSquares = 0;
    for (int i=0; i<numberOfSamples; i++){
        sample = analogRead(0);
        signal = (sample - middleValue);
        signal *= signal;
        sumOfSquares += signal;
    }
    averageReading = sumOfSquares/numberOfSamples;
    runningAverage=(((averagedOver -1 )*runningAverage)+averageReading)/averagedOver;

    if(runningAverage>threshold){
        digitalWrite(ledPin, HIGH);
    }else{
        digitalWrite(ledPin, LOW);
    }
    Serial.println(runningAverage);
}

When the arduino suddenly stopped sending serial numbers, I pressed reset button and uploaded the default code:

void setup() {
}

void loop() {
}

but now it shows that it cannot connect to COM3 (arduino) and cant find the device, When I can see arduino uno successfully connected to PC using device manager (windows 8.1). The led light of arduino also turns on when I connect it to power source or usb.

it shows "port not found" when I click to see the serial output

Did I just fry Arduino? How should I fix this?

Also, i checked the led pin 13 blinking three times when i plug in the usb. I just cant upload anything

my arduino revived the next day.... don't know why but it works!


Measure Vcc on ATtiny13a? I am trying to figure out if I can measure the Vcc of attiny13a, but the code I use for arduino's and attiny85 does not work. This is where I got the code from. I know that it works by using the 1.1v reference and the ADC, and in the attiny13a datasheet it says that it has these, but I can't get it to work.

The code you linked to measures the 1.1 V internal reference using
Vcc as a reference. The ATtiny13A cannot do that. It does have a 1.1 V
internal reference, but it can only use it as a reference for the ADC,
not as a measured channel.
What you can do, if you don't mind adding extra hardware, is divide Vcc
with some resistors in order to get a voltage proportional to Vcc but
lower than 1.1 V. Then use the 1.1 V reference to measure that
voltage. In other words, measure a scaled-down Vcc against the
1.1 V reference instead of measuring the 1.1 V reference
against Vcc. The datasheet should help you with the details.


Connect two SD cards to one Arduino board and copy from one to another I'm trying to connect 2 SD cards to an Arduino Uno board.

My first question is: Is it possible to connect two SD cards to one Arduino simultaneously?
The second question is: If it is possible to connect 2 SD cards, How can I copy card 1 data to card 2

My project goal is to copy data from one peripheral memory to another peripheral memory when an external interrupt occurs.
Can anyone help me please ?

You can't do it with your Arduino-Uno (and usual SD libraries).
SD cards are organized in 512 byte "sectors". You need at least one sector for the file system itself and one sector for the data. If you try to have two files open simultaneously, all your 2048 bytes RAM are required for the SD buffers and you can't return from the file open() call any more.


How to perform a data transfer to an external server So I'm doing a project that involves getting sensor data from several sensors, and then sending them to an external server when a tragic occurs. But I've been having trouble figuring out how to send this data, and I am welcome to advice (I'm still relatively new to Arduino coding).

I'm using an Arduino mega, with a sim900 GSM shield and an SD card. The sensors are just analog reads and a GPS.

I've looked into FTP, a Xively account and http requests to a web server but couldn't figure it out.

There is a good example of using the SubmitHttpRequest() in this article:
GPRS Shield SIM900 Arduino

You could easily modify:
mySerial.println("AT+HTTPPARA=\"URL\",\"www.yourwebsite.com/testing.php\"");

to include a string of the sensor value, and then using a PHP script to MySQL on your webserver. Maybe something like:
http://yourwebsite.com/testing.php?sensor1=5&sensor2=10


Should I use an Arduino or not? I am building an electronic gadget eventually to sell.

I think the Atmega IC is used in the arduino and could this be programmed as easily as the arduino?

I'm wondering if I can use the chip and buy just what I need for my circuit, which would be cheaper as there would be no licensing obligations to the Arduino company

Cheers
Eamonn

Short answer: Yes. After all, Arduinos are made by starting with an ATMega (or other AVR) IC.

Longer answer: People - including myself - routinely build with a bare ATMega328p (or other MCU), programming them off-board on another system, or providing connections to allow programming them in place. Beyond that you only need the soldering skills for the chip you choose (if you're building the boards yourself). I use DIP ICs and off the shelf through-hole PCBs and hand-build one or a couple at a time. Quad Flat-Package or Surface-Mount chips are another step up in complexity for the hand-builder.


changing from long to bytes and vice versa I want to converse data from long to bytes and vice versa. After searching around, I sticked together some code, which seems to work (the same code works for int and floats as well).

The long value LongVal changes to a byte array, and the four bytes construct LongVal2. Obviously LongVal = LongVal2.

long LongVal = -4080;
long LongVal2;

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

//byte* my_function(long LongVal){
//  byte *LongVal_byte = (byte *) & LongVal;
//  return & (LongVal_byte[0]);
//}

//long my_function2(byte & LongVal_byte){
//  long LongVal2;
//  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
//  return  LongVal2;
//}

void loop(){

  byte *LongVal_byte = (byte *) & LongVal;
  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
  Serial.println(LongVal2);
  Serial.println(" ");

//byte LongVal_byte = my_function(long LongVal);
//LongVal2 = my_function2(byte & LongVal_byte);

}

But should I try to wrap the two first lines of loop() in two individual functions, errors occur. The remarked lines are my attempts to create two functions.

How to wrap them up properly?

EDIT
This is what appears if I try to use the remarked functions:

 In function 'long int my_function2(byte&)':
15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]
25:0,
1:
117:14: error:   initializing argument 2 of 'void* memcpy(void*, const void*, size_t)' [-fpermissive]

 In function 'void loop()':
26:33: error: expected primary-expression before 'long'
27:30: error: expected primary-expression before '&' token

So many problems here:

1) in function call there shouldn't be types, only arguments. byte LongVal_byte = my_function(LongVal);

2) & before variable means "get variable address". However in function prototype long my_function2(byte & LongVal_byte) it means reference to passed variable (and it must be byte), not a pointer.

3) pointer to local variable is returned from my_function. It might be working until pointed memory gets rewrited by something else (another function call or so)

And whole code might look like that:

long LongVal = -4080;
long LongVal2;

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

byte * my_function(long & LongVal) {
  return (byte*)&LongVal;
}

long my_function2(byte * LongVal_byte) {
  return *((long *)LongVal_byte);
}

void loop(){

  byte * LongVal_byte = my_function(LongVal);
  LongVal2 = my_function2(LongVal_byte);

  Serial.println(LongVal2);
  Serial.println(" ");
}

But it is basically exactly the same as before without functions (just no need for memcpy)


LiPo batteries with L298N controller I built an avoidance detector robot from this kit.

When I drove the robot, the two motors performed unequally, so I tested replacing the four x 1.5 AA battery pack with a 9 volts battery. It did the trick. I realized, after having read around Stackexchange a bit, that the L298N controller steals a 1.5 V cell just for "heating up".

So... my question is: Can I run the controller off a LiPo battery? If so, which voltage should I choose, when I want to power my Arduino Uno (copy) and the two motors off it?

I don't really understand what voltage the motors can take.

First off, congratulations on entering the world of robotics.  I hope you enjoy it as much as I have.  You are correct that the L298N has a voltage drop that is between 1.8V and 3.2V (at 1 Amp) or 4.9V (at 2A).  This is a problem I sometimes see in older generations of H-bridge designs.  After you figure this problem out and move on, I'd recommend switching to something a little newer like the TB6612FNG or maybe the DRV8871, both of which are pretty common, smaller, and more efficient.  But that's a future step.  First lets get this current project powered.

I'm having to make some assumptions based on the images that you linked to but I'm going to assume that the motor board can take up to 12V and that it ouputs 5V that you are using to power the arduino.  I'm also going to assume that those yellow motors are the familiar cheap hobby motors that run at 3-6V.  If any of those are not true, please comment and we can see how things change.

Now as to what kind of batteries to use; there are literally thosands of ways to power this.  One option is AA batteries as you are doing now.  I would use maybe 6-7 AA batteries to account for the voltage drop of the hbridge but remember that they start at 1.5 but can quickly drop voltage.  And the more current you pull from them, the faster they will drop.  This will be cheaper if you only want to run it a few times since AA batteries are like $0.50 a piece in bulk.  But if you want to run it a lot to experiment, it's going to get expensive (and annoying) fast.  Another option is to use NiCad or NiMH batteries that are rechargable.  The batteries will be a little more expensive initially and you'll have to buy a seperate charger but this will save money in the long run and be able to supply more current to your motors.  NiCad and NiMH batteries are 1.2V (nominal) but come packaged in battery packs so I'd recommend probably an 8.4V pack.  Finally there is the Lipo battery packs, also called Li-Ion (which is a much better and more accurate name but I won't get started on that).  Li-Ion are rechargable like NiCad and NiMH but are much smaller and lighter for the same energy capacity (mAh).  Because of this they have become very popular and have become pretty economical.  For instance you can get a decent li-ion for under $20 on hobbyking and be very happy for several years.  Li-ion do have an inherant risk but as long as you don't do anything stupid, you'll be fine.  They also require a special charger but as long as you aren't worried about super fast charging this isn't too expensive.  Li-ion come in individual cells of 3.6V nominal (sometimes advertised as 3.7V) but also come in packs of 7.2V, 11.1V, or 14.4V.  Remember that these are the nominal values.  A 7.2V pack will start at 8.4V and drain to 6V before it is "dead"  If you go this route, I'd go with the 7.2V pack.

I would highly recommend you go with one of the three rechargable options since that will be more economical in the long term and will also allow for longer run times and will supply more current to the motors.  Hobbyking.com is a great resource for cheap rechargable batteries as is amazon.

I can't explain everything but here are some further quesitons you should google to get started:

-LiPo safety

-Lipo C rating

-Lipo voltage range

-Lipo mAh rating

I just want to fix a couple misconceptions from other answers:

1) Lipos are not expensive as hell if you take into acount how long they last and their other benefits such as size, weight, and ability to supply current.

2) For a given battery capacity, a LiPo will be smaller and ligher than AA batteries and will provide more current and longer battery life than AA batteries.  The ammount of current the Arduino draws will be tiny compared to the current of the motors so don't worry much about it.

3) Not only are Lipos recommended by many people for ground (and air and water) robots, they are becoming the standard for RC cars of almost every size.  The motors you are using here are 6V max so 7.2V lipo is a good way to go.  Later you might use motors that are 12V and will move up to a 11.1V or 14.4V lipo.  Some of the nicer lipos can deliver hundreds of amps to motors and are commonly use in battlebots and similar competions.  But you aren't there yet so you're going to use smaller lipos with these smaller motors and maybe someday you'll use big lipos with big motors.  Every project has different needs.

4) Sometimes a rechargable battery back will get hot if you are pulling a lot of curernt from it.  But as long as you respect the "C" rating (google it) you will be absolutely fine.


How to modify this code to simulate a binary encoder? I have come across the following SPI slave code at this site:

#include <SPI.h>

char buf [100];
volatile byte pos;
volatile bool process_it;

void setup (void)
{
  Serial.begin (115200);   // debugging

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode (MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;

    // example: newline means time to process buffer
    if (c == '\n')
      process_it = true;

    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set

}  // end of loop

How to modify the above code so that it responds to input clock signal just like in this SSI protocol? Uno or Nano can be used.

Basically I want to let an arduino  act as an absolute encoder so that it will transmit 13-bit binary data(it can be any random fixed binary data) as shown in the above SSI protocol. So the Arduino will output 13-bit binary data along with with start bit and tm taken into account as shown in the document above without parity.

The master's code I plan to use:

const int CLOCK_PIN = 2;
const int DATA_PIN = 3;
const int BIT_COUNT = 16;
void setup() {
    pinMode(DATA_PIN, INPUT);
    pinMode(CLOCK_PIN, OUTPUT);
    digitalWrite(CLOCK_PIN, HIGH);
    Serial.begin(115200);
  }
void loop() {
    float reading = readPosition();
    Serial.println(reading,2);
    delay(25);
  }

//read the current angular position
float readPosition() {
 unsigned long graysample = shiftIn(DATA_PIN, CLOCK_PIN, BIT_COUNT);
 delayMicroseconds(100); // Clock must be high for 20 microseconds before a new sample can be taken
unsigned long binarysample = grayToBinary32(graysample);
 return ((binarysample * 360UL) / 65536.0); // ouptut value from 0 to 360 with two point percision
}
//read in a byte of data from the digital input of the board.
unsigned long shiftIn(const int data_pin, const int clock_pin, const int bit_count) {
 unsigned long data = 0;
 for (int i=0; i<bit_count; i++) {
 data <<= 1; // shift all read data left one bit.

 //digitalWrite(clock_pin,LOW);
 PORTD &= ~(1 << 5); // clock pin goes low
 delayMicroseconds(1);
 //digitalWrite(clock_pin,HIGH);
 PORTD |= (1 << 5); // lock pin goes high
 delayMicroseconds(1);
 data |= digitalRead(data_pin); // cat the new read bit to the whole read data.
 }
 return data;
}
unsigned int grayToBinary32(unsigned int num)
{
 num = num ^ (num >> 16);
 num = num ^ (num >> 8);
 num = num ^ (num >> 4);
 num = num ^ (num >> 2);
 num = num ^ (num >> 1);
 return num;
}

You may try to bit-bang the protocol using direct port access. This
is less convenient, but way faster than digitalWrite(). Below is an
example, untested program. I am assuming the pinout is

data = PB0 = digital 8
clock = PB1 = digital 9
pins PB2 – PB5 (10 – 13) are unused

Edit: This updated program uses the clock as an input, and the data
as an output. The previous version used both lines as outputs, which was
due to a misunderstanding of mine.

#include <avr/io.h>

int main(void)
{
    uint16_t data = 0x155;

    DDRB  |= _BV(PB0);
    PORTB |= _BV(PB0);
    TCCR1B = _BV(CS10);  // start timer 1 @ F_CPU
    loop_until_bit_is_clear(PINB, PB1);

    for (;;) {
        loop_until_bit_is_set(PINB, PB1);
        PORTB = data & 1;
        data >>= 1;
        TCNT1 = -304;        // 20 us * 16 MHz - 16 cycles
        TIFR1 |= _BV(TOV1);  // clear overflow flag
        while (bit_is_set(PINB, PB1)) {
            if (bit_is_set(TIFR1, TOV1)) {  // timer overflowed
                PORTB = 1;  // data high
                data = 0x155;
                loop_until_bit_is_clear(PINB, PB1);
                break;
            }
        }
    }
}

This should be able to operate at frequencies up to about
200 – 250 kHz. There is a delay of about 0.5 µs
between the rising edges of the clock and the data been sent out, with a
jitter of 3 clock cycles.

The data word is sent least significant bit first, contrary to what the
protocol diagram shows. However, if you send arbitrary data, this should
not be an issue.

Note that this is a pure avr-libc program, which does not use the
Arduino core. It uses polling to check the inputs and the timer. The
interrupts are never enabled.


Arduino Uno - relay with separate power i want to operate a relay with an ARDUINO UNO, but i want to use a separate power supply for the relay. Ive seen relays with VCC and jVCC (dont know what that is), but mine only has this pins: GND, IN1, IN2, VCC.
how should i connect it to the Arduino and the external power supply?

This relay is designed to operate on 5V.

Most commonly this will come from the Uno's 5v pin.

If you want to externally power the relay itself then make sure to connect the +5 to the Vcc on the relay board and the - lead to the GND on the relay board.

Uno's GND must also be connected to the GND on the relay so the Digital outputs from the Uno will properly control the IN1 and IN2 inputs to the relay board.

The Uno has multiple GND connections so it makes the most sense to connect the - to one of them then another to the relay.

Note that the Uno's 9V Vcc external power comes in through the barrel connector on the Uno itself. The Uno will pass power through its internal regulator to provide 5v at the appropriate connection.

If you are switching external devices that run on 120V it would be on the screw-terminal side of the board only.

  To prevent accidental activation of the relays, note that this particular board is ACTIVE-LOW which means that as you initialize the output pins you should first set them HIGH so setting the pinMode will not default to LOW which would trigger the relay.

In the setup() section, using pins D5 and D6 as an example:

digitalWrite(5,HIGH); pinMode(5,OUTPUT);
digitalWrite(6,HIGH); pinmode(6,OUTPUT);


Is there any way I can stop the Arduino Mega 2560 from resetting all variables after losing and reconnecting power? I am using an Arduino Mega 2560 board. I have tried connecting a 115 Ω resistor from 5V to Reset, and 10 µf capacitor form reset to GND (to disable autoreset), and the variables still seem to reset themselves when I unplug and replug-in the Arduino. Any way to stop this from happening?

Basically I am making a device that is sensitive to time, and must run for about 2 months, but if it is unplugged, it can't lose its place in time and reset the whole program.

I think one alternative would be for me to have it actually write how long it has been running into a .txt file on the microSD card and then verify that in the start-up...

Any ideas?


Powering 5V Accesories I'm using an Uno to control NeoPixels LED strips (60 per metre). These are powered with a 5V DC supply. Now, when using USB to power the Arduino it works lovely. However I want to move the Arduino into a standalone "installation" where I'll only want one power supply.

I've already got a 5V DC supply which outputs about 5.2V. What is the best way to power both the Arduino and the LEDs? I understand the need for at least 7V at the Arduino's voltage regulator input. Would my best bet be to get a 12V supply (or similar) and use a buck converter to power the LEDs? The total current draw could reach 3.6A but will be 400mA for the majority of the time.

If your supply is regulated (put a 47ohm resistor across it and measure the AC voltage with a DMM; it should be almost nothing if properly regulated) then you can use it for both the Uno and the NeoPixels. The ATmega328P has a maximum input voltage of 5.5V, and the WS2812B has a maximum voltage of 5.3V, putting the supply within the proper range to run them.


Delay function broken? I noticed timing inconsistencies in my project, and further debugging pinpointed it to the problem below. The text should be updating every second, but the returned values are >> 1000ms.

To clarify, the text is not showing up every second.  The delays between texts vary according to fluctuating start and finish values.

I'm using a Teensy 3.2. Changing the baud rate doesn't help.

Is my timing crystal busted? Is there a serial buffering issue? I don't know how to fix either of these.

Any help would be appreciated!

Edit:

Here's the code if anyone wants to test.  I found that adding more delay functions screws the output up in completely unlinear ways.

unsigned long start, finished, elapsed;

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

void loop() {
  Serial.println("Start...");
  start = millis();
  Serial.println(start);
  delay(1000);
  finished = millis();
  Serial.println(finished);
  Serial.println("Finished");
  elapsed = finished - start;
  Serial.print(elapsed);
  Serial.println(" milliseconds elapsed");
  Serial.println();
}

Edit #2:

I thought it was worth showing everyone this screenshot.  It looks like delay(1000) just isn't functioning at all.

Edit #3:

I debugged it with an LED and it blinked at exactly 1s intervals.  It seems like delay(1000) works, so the problem must be related to the serial buffering.  I also updated my software but that didn't help.

Edit #4:

New developments from further debugging:

The problem is not reproducible on a different computer.  The Arduino serial monitor on other computers displays correctly.
Updating to the latest OSX, arduino IDE, and teensyduino did not help.
Terminal 'screen' command surprisingly prints correct serial communication.
Serial monitors from 3rd party apps, like CoolTerm and Arduino IDE do not work.

After correcting the syntax error (missing semicolon) I tried your code on my Teensy 3.0. The results look OK to me:

Start...
1250
2250
Finished
1000 milliseconds elapsed

Start...
2250
3250
Finished
1000 milliseconds elapsed

Start...
3250
4250
Finished
1000 milliseconds elapsed

Start...
4250
5250
Finished
1000 milliseconds elapsed

Start...
5250
6250
Finished
1000 milliseconds elapsed

Start...
6250
7250
Finished
1000 milliseconds elapsed

Start...
7250
8250
Finished
1000 milliseconds elapsed

Start...
8250
9250
Finished
1000 milliseconds elapsed

Since the code you posted doesn't compile, can you re-test please with your posted code, assuming you add in the semicolon, and put a space before "milliseconds elapsed".

Further down my test I see this:

Start...
153258
154258
Finished
1000 milliseconds elapsed

Start...
154259
155259
Finished
1000 milliseconds elapsed

Start...
155259
156259
Finished
1000 milliseconds elapsed

Now are you talking about the "creep" in the start time? That doesn't totally surprise me, because the rest of the code must take some time to execute.

I know this isn't an "answer" per se, but I can't post this much information into a comment.


Code For Lighting RGB Led I am doing this simple introductory exercise to light an RGB Led, but I am confused about the code in the exercise. The following is the code:
/* Adafruit Arduino - Lesson 3. RGB LED
*/

int redPin = 11;
int greenPin = 10;
int bluePin = 9;

 //uncomment this line if using a Common Anode LED //#define
 COMMON_ANODE

void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);   }

void loop() {
  setColor(255, 0, 0);  // red
  delay(1000);
  setColor(0, 255, 0);  // green
  delay(1000);
  setColor(0, 0, 255); // blue
  delay(1000);
  setColor(255, 255, 0);  // yellow
  delay(1000);
  setColor(80, 0, 80);  // purple
  delay(1000);
  setColor(0, 255, 255);  // aqua
  delay(1000); }

void setColor(int red, int green, int blue) {
#ifdef COMMON_ANODE
     red = 255 - red;
     green = 255 - green;
     blue = 255 - blue;
#endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);   }

In this code, why were they able to carry out setColor before expanding upon what it means later through void setColor(int red, int green, int blue)? Should that portion of the code come earlier or does it matter? Also I don't quite understand how the definition of the colors red, green, and blue were defined towards the bottom. I know what 255 would indicate maximum brightness, but why do you have to subtract the color from 255? Any help would be much appreciated.

why were they able to carry out setColor before expanding upon what it means later

You are correct in C that is the case. However the Arduino IDE adds "function prototypes" to the top of your code automatically. That means you no longer have to abide by the "define before use" of C and C++.

I know what 255 would indicate maximum brightness, but why do you have to subtract the color from 255?

This is for if your LED is "common anode" instead of "common cathode". With a common anode LED you write a LOW to turn it on and a HIGH to turn it off - this is the exact opposite of a common cathode.
So to set the brightness of a common anode LED you need to use the opposite value, and since PWM goes from 0-255 the opposite is 255-0: 255 is off, and 0 is fully on.


4.7v as HIGH on digital output instead of 5v I'm new to Arduino, just got my starter kit, and I noticed that digital outputs 3 & 4 have 5v as HIGH level while 5 to 13 have 4.7v as HIGH level.
Is it as it suppose to be?

Also depends on what your driving via this output. Standard TTL is:

But CMOS will be a bit different:


Arduino OBD connection I am using this code on a arduino nano and works fine.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);           // select the pins used on the LCD panel

#include <OBD2UART.h>

COBD obd;

void setup()
{

  // start communication with OBD-II UART adapter
  obd.begin();
  lcd.begin(16, 2);
  // initiate OBD-II connection until success
  while (!obd.init());
}

void loop()
{
  int value;
  obd.readPID(PID_RPM, value);
  int value2;
  obd.readPID(PID_COOLANT_TEMP, value2);
  lcd.setCursor(0,0);
  lcd.print("RPM = ");
  lcd.print(value);
  lcd.print("     ");
  lcd.setCursor(0,1);
  lcd.print("ECT = ");
  lcd.print(value2);
  lcd.print("     ");
    }

But if OBD is not connected, then it's get stuck in the setup.
What I want to do is to go over setup even if obd is not connected, and try connect to OBD meanwhile...something like display "Connecting..." on first row and count something on second...

Thank you in advance

The while() loop in setup() is what gets hung up. Instead of calling odb.init() until it returns true, just call it once just to get it initiated, then call/check in loop() and react accordingly:

void setup()
{
  // start communication with OBD-II UART adapter
  obd.begin();
  lcd.begin(16, 2);
  // initiate OBD-II connection once
  obd.init()
}

void loop()
{
  static int error_count;
  if (!obd.init()) {
    // Not connected
    lcd.setCursor(0,0);
    lcd.print("Connecting");
    lcd.setCursor(0,1);
    lcd.print("Count: ");
    lcd.print(error_count);
    error_count++;`
  } else {
    int value;
    int value2;

    obd.readPID(PID_RPM, value);
    obd.readPID(PID_COOLANT_TEMP, value2);
    lcd.setCursor(0,0);
    lcd.print("RPM = ");
    lcd.print(value);
    lcd.print("     ");
    lcd.setCursor(0,1);
    lcd.print("ECT = ");
    lcd.print(value2);
    lcd.print("     ");
  }
}


2D Tracking of an object - which sensor? I'm currently working on a project for which I require a sensor. I've made a quick and simplified drawing of what the result is supposed to do:

Basically, I want one LED of a LED-Strip to light up dependent on the location of a moving object. If the object in above image (say a slow rolling ball) were to move from bottom to top, then the LED strip should also light up from bottom to top. I have no problem getting the LED strip to light up adequately, however I'm not sure which sensor actually can pick up objects as required in this case.

As I've understood regular IR sensors can only detect if there is an object and how far it is away, however they can't pick up said object's relative position on the y-axis. Is there any way to do this rather easily, perhaps with triangulation? I've looked into Bluetooth and RFID but haven't found anything particularly useful.

I feel that an array of IR transmitters and receivers could work for you.

If you put the transmitters/receivers in an recessed tube with (black, non-ir reflectant) separations, you can avoid crosstalk.
You should be wary that it may require some tweaking to find the right sensitivity.

Here is a video (and here) that shows this in practice. I like the fact that you don't need sensors on either side of the object.

You may also consider video-processing, but that's out of scope for Arduino.
Or use a Lidar.


Grove A12-200 current sensor I am trying to measure current from an LFG with Arduino Uno and Grove current sensor (A12-200). I found a code at this link you can see Arduino code here.

The code works, but there are some operations that I don't understand. Let me copy and paste the code here (for further information, please follow the link above).

/****************************************************************************/
//  Function: Measure the amplitude current of the alternating current and
//            the effective current of the sinusoidal alternating current.
//  Hardware: Grove - Electricity Sensor
//  Date:    Jan 19,2013
//  by www.seeedstudio.com
#define ELECTRICITY_SENSOR A0 // Analog input pin that sensor is attached to

float amplitude_current;               //amplitude current
float effective_value;       //effective current

void setup()
{
    Serial.begin(9600);
    pins_init();
}
void loop()
{
    int sensor_max;
    sensor_max = getMaxValue();
    Serial.print("sensor_max = ");
    Serial.println(sensor_max);
    //the VCC on the Grove interface of the sensor is 5v
    amplitude_current=(float)sensor_max/1024*5/800*2000000;
    effective_value=amplitude_current/1.414;//minimum_current=1/1024*5/800*2000000/1.414=8.6(mA)
                        //Only for sinusoidal alternating current
    Serial.println("The amplitude of the current is(in mA)");
    Serial.println(amplitude_current,1);//Only one number after the decimal point
    Serial.println("The effective value of the current is(in mA)");
    Serial.println(effective_value,1);
}
void pins_init()
{
    pinMode(ELECTRICITY_SENSOR, INPUT);
}
/*Function: Sample for 1000ms and get the maximum value from the SIG pin*/
int getMaxValue()
{
    int sensorValue;             //value read from the sensor
    int sensorMax = 0;
    uint32_t start_time = millis();
    while((millis()-start_time) < 1000)//sample for 1000ms
    {
        sensorValue = analogRead(ELECTRICITY_SENSOR);
        if (sensorValue > sensorMax)
        {
            /*record the maximum sensor value*/
            sensorMax = sensorValue;
        }
    }
    return sensorMax;
}

effective_value=amplitude_current/1.414

I don't understand why dividing amplitude_current by 1.414 we'll get effective_current.

And in the function getMaxValue(), I know what it does, but I don't understand why we just need maxvalue.

You are measuring a sinusoidal "signal" that is alternating in polarity. What the code notes as "effective" current the equivalent DC current for purposes of measuring power consumption. In EE, it's called "RMS" or Root Mean Square, and it's the mathematical derivation to calculate consumed power or current in a situation where the current flows symmetrically back and forth, and thus a time average would give zero.

It's dividing the peak current by the square-root of 2 (1.414).


Arduino with OV7670 - a buffer I have an Arduino UNO and OV7670 camera sensor without FIFO. I wanted to build a device, that would take frame once in a while, and would send it through bluetooth (HC-05) or wi-fi (esp-01). I didn't know though, that the microcontroller inside Uno has so little RAM memory, that the frame doesn't fit inside. Moreover, even Arduino Mega has too little memory...

My question is- is there anything I could do to take a VGA-resolution photo (circa 1MB) and send it through any serial medium?

I suppose it'd be some kind of a buffer or memory- I'm asking for references to concrete chips or solutions (like- would it be possible to encode or compress an image on-the-fly)?

If you're okay with grayscale, you don't need 1 MB buffer space. With the YUV422 colour space, you can extract only the Y component and need only 640*480 = 307kB buffer for a VGA grayscale image.

However, according to this, you can set the hardware serial baud rate to 1M-baud and transmit the image bytes as you receive them without buffering. main() shows how to set up the serial port and you can also see how they received each VGA pixel byte in Bayer-RGB and transmitted immediately; notice that all interrupts are disabled first, given the high-speed nature of the transfer. But instead of Bayer, I'd recommend you use YUV422 instead, meaning the camera sends 2 bytes per pixel. Because you're only interested in the Y byte, you can place that in the UART buffer and use the time spent in receiving (and discarding) the second U/V byte to give the UART peripheral some additional breathing room to send the Y byte, before you send the next one.

Regarding the high baud rate, the crystal frequency of the Arduino doesn't matter so much because you'll only be transmitting to your PC, which should be able to handle the speed even given the rate error. Note that in main(), double speed async is enabled, and UBRR is set to 500 kBaud to obtain 1-Mbaud. Also notice that an 8MHz PWM signal was used to clock the camera (XCLK signal) with no PLLs activated in the camera register settings. This is another tutorial related to the same code; may clear up a few things.

If you really want to use a chip solution, you can look up parallel SRAM like the HM628128; it's only 128kB though, you'll need to find a bigger one to hold an entire frame of 307kB. Parallel SRAM are great because you can attain really high write speeds because of the simple interface. You'll need some sort of counter connected to the SRAM address lines clocked by the PCLK line (divided by 2, since you only want every other byte) so that every pulse increments the address. This same clock will feed the nW signal to actually clock the data into the SRAM (after satisfying address setup times somehow). The camera data lines will be connected directly to the SRAM and you activate the SRAM's chip select signal based on your monitoring of the camera's VSYNC signal (to know when a new frame's about to start). When the frame's done, you read from the RAM and forward the bytes to your destination.

All this assumes you aren't trying for video, merely taking frames "once in a while". Though the first solution will work for video, albeit poor video.


Two pots controlling 2 servos -- odd behavior I'm trying to control 2 servos with 2 pots. I thought I could just amend the tutorial code by adding in the extra pot on a1 and extra servo on d8 (am using a Nano).

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
Servo myservo_2;

int potpin = 0;  // analog pin used to connect the potentiometer
int potpin_2 = 1;
int val;    // variable to read the value from the analog pin
int val_2;

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

void loop() {
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val_2 = analogRead(potpin_2);
  val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
  val_2 = map(val_2, 0, 1023, 0, 180);
  myservo.write(val);                  // sets the servo position according to the scaled value
  myservo_2.write(val_2);
  delay(15);                           // waits for the servo to get there
}

...but the servos only respond to one of the pots (on a0) & both move to the same position regardless of what value is on a1.

Am I missing something really obvious? Why is the value on a1 ignored & why is the value mapped from a0 sent to both d8 & d9?

I have swapped out the pot on a1 just in case it was faulty but I get the same behavior.

EDIT: Added schematic

EDIT: I swapped out the Nano for another Nano but that failed to upload the sketch. So I put the original back in & now evrything is working fine!

Darn'd if I can get my head around it, possibly a bad connection with the bread board?

Anyway all working now thanks for your suggestions.

I have no idea whats wrong with your system, but this might help you diagnose it.

#include <Servo.h>

static const size_t MaxServos = 2;              // The number of pots and servos attached
const int servoPins[MaxServos] = {9, 8};        // The pins that the servos are controlled through
const int potpins[MaxServos] = {A0, A1};        // analog pin used to connect the potentiometer
Servo myservo[MaxServos];                       // create servo object to control a servo

void setup ()
{
    for (size_t index = 0; index < MaxServos; ++index)
    {
        myservo[index].attach (servoPins[index]);
    }
}

void loop ()
{
    for (size_t index = 0; index < MaxServos; ++index)
    {
        readAndSet (potpins[index], myservo[index]);
    }
    delay (15);                           // waits for the servo to get there - might want to multiply a value by the number of degrees turned to give a better value.
}

// \brief   Read the specified analog pin and set the server proportionally
// \param   The analog pin that the pot is connected to.
// \param   The servo that will be moved
void readAndSet (const int& pin, Servo& servo)
{
    const int value = analogRead (pin);            // reads the value of the potentiometer (value between 0 and 1023)
    const int mappedValue = map (value, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
    servo.write (mappedValue);                  // sets the servo position according to the scaled value
}

I have refactored your code to eliminate the duplication.  This means you will get more test coverage and you should find the bug quicker.  You could add a Serial print statement to the readAndSet function to ensure that you are passing and calculating the right values, but I suspect you are.

There appears to be nothing wrong with the code, so is it possible that there is some hardware limitation?  Is there a short between the lines that causes the pot on A1 to be bypassed?


What components I need for a small GPS tracker I am new to Arduino and want to create a graduation project for my university.
I am thinking to create a GPS tracker that can be attached to a cloth to track kids, for example.
So the requirements for this project is as follows:
- The device should be small
- It should upload its location to a web server constantly.
- the device should work with battery for at least 8 hours

Now what components are needed for this project?
What concern me a lot is that how can I find battery last this much time, if I need bigger battery, it may hinder the device from being attached easily.

You have two options. Option 1. Buy a ready made pet tracking device from online market e.g (https://www.aliexpress.com/item/Pets-Smart-Mini-GPS-Tracker-Anti-Lost-Waterproof-Bluetooth-Tracer-For-Pet-Dog-Cat-Keys-Wallet/32887784462.html?spm=2114.search0104.3.1.26793604pFMLma&ws_ab_test=searchweb0_0,searchweb201602_3_10065_10068_319_10059_10884_317_10887_10696_321_322_10084_453_10083_454_10103_10618_10307_537_536,searchweb201603_52,ppcSwitch_0&algo_expid=09c58262-a0e7-4205-8fba-cd8265c15b3e-0&algo_pvid=09c58262-a0e7-4205-8fba-cd8265c15b3e). Then you can download the app and start tracking movement.

Option 2: The other alternative is to build one from scratch by purchasing all the necessary components. This is option is most appropriate for students. You can check this page for more https://electronicsforu.com/electronics-projects/hardware-diy/gsm-gps-based-vehicle-tracking-system. However, you may not be able to achieve the small size as you wanted but you should have something close to it if you carefully select your components.


WiFi connections being lost on connection reset Look at the trick in the last few lines of this code:

#include <ESP8266WiFi.h>

const char* ssid = "xxxxx";
const char* password = "yyyyyyy";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

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

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

 int delays = 0;

 // Wait until the client sends some data
 Serial.println("new client");
 while(!client.available()){
    delay(1);
    delays++;  // First line of trick.
    if (delays > 10) {
       return;
    } // Trick ends.
  }
  ...// Handle some events.
}

Code works ok without the trick (only delay(1); inside the loop), but the problem is it gets stucked there, if some responses are asked from browser so that tab is closed in between the requests.

One response is for favicon:

 if (req.indexOf("favicon.ico") != -1) {
    String s = "HTTP/1.1 404 WTF Favicon !!\r\n";
    client.print(s);
    client.flush();
    return;
 }

I had also one similar response starting with 200 OK for certain URLs and then a response of plain json text.

I would like to know why my server gets stucked on this delay(1);? Also, when the trick is needed, what is correct delays value?

Also I did add a client.flush(); after every client.print();. May that affect anything?

WifiServer class has a bug that is now resolved. It causes a phenomenom described like follows:

  When I send message to client via WifiServer.avalible, the user is disconnected from server - I can connect to it again, so server is not stopping.

And latest comment on topic is that it is corrected in latest commits.