ATtiny85 (Sparfun Clone/Trinket), detect/read operation voltage I just started with Arduino programming and currently I'm using this Sparkfun clone board:

o http://nl.aliexpress.com/item/Digispark-kickstarter-Micro-development-board-ATTINY85-module-for-Arduino-usb/32584975067.html

It's really nice and like the way to program it and 'burn' it, it's easy to do. For the first project, I came along this instructable, an USB volume knob:

o http://www.instructables.com/id/Digispark-Volume-Control/

I'm using the Sparkfun Arduino programming IDE with added AdaFruit Trinket USB library (Trinket is also ATtiny85), download source, tweak it a bit to my needs and it's working perfectly. Had some programming question though, see also:

o https://stackoverflow.com/questions/37740026/change-override-trinket-attiny85-usb-identification-name-device-name/37743886#37743886

o  https://stackoverflow.com/questions/37769451/arduino-make-a-library-more-optional-by-project?lq=1

o https://stackoverflow.com/questions/37824336/arduino-trinket-attiny85-usb-possible-to-read-the-state-of-all-keys

Anyway, optimized the source code (original not really a beauty), play with it and added also a fade-In/fade-out idle feature to the LED on PIN 1 and it blinks when turning the dial encoder.

I want to add add some more features to this knob, such as pushbuttons to change some internal modes. For example:

Toggle button for knob sensitivity (3-modes: slow (default), normal, fast)
A mute button

I want to that device 'remember' the state of the toggle button but there is no option (flash memory) to save the state. So I came with the idea to use a backup button cell to keep the device 'alive' when disconnected from USB (or computer turned off). A Button cell is 3V and USB is 5V so maybe is possible to 'test' the input voltage. If this is possible you can put the device in sleep mode (low power mode) directly after detecting USB connection lost and this voltage drop.

I have read already an article how to put the device into sleep mode (and awake from it):

o https://bigdanzblog.wordpress.com/2014/08/10/attiny85-wake-from-sleep-on-pin-state-change-code-example/

Question is:

Can I measure somehow the voltage is used to power the device? Any ideas (code example please if it is possible)?

There are a few solutions.

If you want to save te state of your toggle button you can save it in the eeprom of your attiny85
You can use an ADC pin to check your VCC against the internal 1.1V reference
alternatively you can read the 1.1ref aganist Avcc. https://digistump.com/board/index.php?topic=1104.0


Arduino - stepper motor wrong steps number I just bought a new stepper motor (400 steps for revolution, 0.9°/step) and I would like make a turn of 180° by 200 steps, but it doesn't work as expected.
It looks like the motor needs only 110 steps to make a turn of 180° and I don't know the cause. The driver motors is the Keyes L298. It is wired to my Arduino UNO rev3.

In order to clarify, please see the image below:

The code is as follows:

#define negativeSteps -55
#define positiveSteps 55
#define Speed 7500

int motorPin1 = 11;
int motorPin2 = 10;
int motorPin3 = 9;
int motorPin4 = 8;

int steps;
unsigned int tmp2;

byte modeR[] = {B00001001, B00001010, B00000110, B00000101};
byte modeF[] = {B00000101, B00000110, B00001010, B00001001};

void setup() {

  Serial.begin(115200); //Opens serial connection at 115200 baud.

  pinMode(11,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);

  pinMode(3,OUTPUT);    // Enable pin motorA
  pinMode(2,OUTPUT);    // Enable pin motorB

  digitalWrite(2,HIGH);
  digitalWrite(3,HIGH);
}

void loop()
{
    while (Serial.available())
    {
      char cmd = (char)Serial.read();
      if (cmd == 's')   while(1) Seek();
    }
}
void motorR(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeR[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void motorF(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeF[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void Seek() {
  steps = negativeSteps;      //Init Steps
  while (1)
  {

    while (steps<positiveSteps) //  starts from "negative" steps to "positive" steps ( -55 to +55)
    {
       if (steps<0) motorF(); // if steps = 0 it will change the direction
       else motorR();

      Serial.println(steps);
      steps++;
   }
 }
}

You're driving the stepper too fast, unintentionally though.

The while loop you use to delay is likely optimized out by the compiler:

while (tmp2++<Speed);

Easiest way to fix would be to declare tmp2 as a volatile variable when you declare it up in the top of your program.  Thusly:

volatile unsigned int tmp2;

This will inform the compiler that tmp2 might possibly change at any time and not to optimize it away. It's more complicated than that really, but it'll fix your issue in a single tweak.

Better, would be to use the delay() function, to pause execution for some specified milliseconds, much like you're attempting to do with the empty while loop.

You're using an UNO, so probably running at 16Mhz, so your delay of 7500 loops is technically about 5 instructions long, multiplied by 7500... so 37,500 instructions executed, and at approximately 16,000,000 instructions per second, that's (37500/16M) that's about 2.34 milliseconds.  So maybe a delay() of 3-5 milliseconds would be useful.

Basically, you're trying to step the motor too fast, and it can't keep up.  Mass, inertia and all that stuff are involved too.

Try replacing the while statements with delays, start with big delays (25 or so), and work lower as long as stepper motion is consistent.  As you said, 200 steps should be 180°.

replace:

while (tmp2++<Speed);

with:

delay(Speed);

and change Speed to an appropriate value (25 or so to begin with, play with it!).

There are many improvements to your code which could be discussed, but you need to crawl before you walk, before you run.  Get THIS code working, then finesse it.


Can't upload code to Arduino board on Mac I'm using a MacBook Pro with 10.13.6, an Official Arduino Uno Board and Arduino 1.8.13 IDE.
I'm having troubles uploading code to the Arduino Board.
I have 5 ports available:

dev/cu.-AvnetaSPPPort
dev/cu.Bluetooth-Incoming-Port
dev/cu.SRS-BTX300-DataInteract
dev/cu.RS-XB41-BluetoothSeria-1
dev/cu.UEMEGABOOM-LWACP-2

I'm not sure if any oh these ports is the correct one but I've already tried all of them and I keep getting errors like: "avrdude: ser_open(): can't open device "/dev/cu.-AvneraSPPPort": Resource busy"
Some weeks ago I was trying Arduino on the same computer and all went good but right now I can't get it to work, however I don't remember wich port was selected.
In the IDE the board I have selected is "Arduino Uno" and as Programmer option I have "AVRISP mkll".
Does anyone know how to solve this?

I finally solved the problem.
Although the Board has no information about being a clone (it only says "Uno" and was provided by the faculty so I think it is official), I was looking on the web for similar problems and found out that installing CH340 Driver was working for a lot of users.
So that was what I did and now it works like a charm.


problem in integrating the slave code in attiny 84 I tried the whole process by using two arduino unos.It worked perfectly.
Though when i tried to replace the slave uno with attiny 84 uC it showed following errors in compiling.

Arduino: 1.6.7 (Windows 7), Board: "ATtiny24/44/84, ATtiny84 @ 1 MHz  (internal oscillator; BOD disabled)"

WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void setup()':

sketch_may12c:12: error: 'SPCR' was not declared in this scope

   SPCR |= bit (SPE);

   ^

In file included from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/WProgram.h:12:0,

                 from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/Arduino.h:4,

                 from sketch\sketch_may12c.ino.cpp:1:

sketch_may12c:12: error: 'SPE' was not declared in this scope

   SPCR |= bit (SPE);

                ^

C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/wiring.h:158:25: note: in definition of macro 'bit'

 #define bit(b) (1UL << (b))

                         ^

sketch_may12c:15: error: 'MISO' was not declared in this scope

   pinMode (MISO, OUTPUT);

            ^

sketch_may12c:22: error: expected unqualified-id before '.' token

   tinySPI.attachInterrupt();

          ^

C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void SPI_STC_vect()':

sketch_may12c:30: error: 'SPDR' was not declared in this scope

 byte c = SPDR;  // grab byte from SPI Data Register

          ^

exit status 1
'SPCR' was not declared in this scope

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

You are trying to compile the wrong program for the wrong chip.

The nice thing about the Arduino core library is that it enables you to
write code that is portable across various Arduino boards. However, this
library provides very limited access to the capabilities of the
underlying hardware. Then, it is quite common for users to mix Arduino
code with C statements that directly access the hardware registers.
Doing this provides full control over the hardware, at the cost of
reduced portability.

Just an example from your code:

SPCR |= bit (SPE);

This line is accessing the control register of the SPI port (SPCR means
“SPI Control Register”) in order to set to 1 the bit named SPE (for “SPI
Enable”). This is the “bare metal” way of turning on the SPI port.

Now, your problem is that, unlike the ATmega328P powering your Unos, the
ATtiny84 does not have a hardware SPI port. Thus the line above just
makes no sense.

The solution: you have to figure out some other means for your chip to
talk SPI. You could emulate it purely in software, but it would
certainly be more efficient to use the USI port. The USI (“Universal
Serial Interface”) is a multipurpose serial port found in many ATtinies.
It can be configured to do SPI, I2C or simplex/half-duplex UART.

Recommended readings:

AVR319: Using the USI module for SPI
communication, an
application note by ATmel
Using an ATtiny2313/4313 as SPI
master on the Arduino
Playground

You may be able to find ready-made libraries for doing this.


Arduino keypad and RF 433MHz transmitter problem So, the basic idea is that user presses a key on keypad, and key that is pressed is sent with RF transmitter.
I got individual parts to work(keypad and transmitter), but can't send the actual key. When I try to send it, I get a strange string on the other end. I am convinced its simple issue with my syntax, so if anyone could help me, that would be great. Code is below:

#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile
RH_ASK driver; //use this driver for transmitter

#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
    Serial.begin(9600);   // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{

    char key = keypad.getKey();

    if (key){
      Serial.println(key);//outputs correct key
      //transmitter part
//      const char *msg = "Hello World!";
      const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
      driver.send((uint8_t *)msg, strlen(msg));
      driver.waitPacketSent();
      Serial.println(key);//outputs correct key
      Serial.println("packet_sent");
    }
}

The problem is you send a character of type char, thus exactly one byte.
However, when you send it you have to give the length and you use strlen. However, msg is an array (at least that is what you want), but that array contains only the character to sent. What you want is to send only 1 character, so use 1 instead of strlen.

Also, you can get rid of the special msg pointer and instead of

  const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
  driver.send((uint8_t *)msg, strlen(msg

use

  driver.send(&key, 1);

Where &key defines the address (pointer to) key, and since there is always exactly 1 byte in key (the key itself), 1 can be used. To be more safe, you can use sizeof(key) thus

  driver.send(&key, sizeof(key));

What you also can do is create a string that ends with \0, so the first is the character to send, and strlen can be used, but the easiest way is to set the length to exactly 1.

Actually, using strlen on a string that does not end with \0 can result in strange behavior, because maybe there is no \0 in memory.


DC motor with L289N driver cannot set RPM lower than 130 My setup is using an Uno r3, and the motor driver is an L289N.

I am going to set it to run at a lower RPM, but when adjusting enA or enB to set to below 130, it won't spin.

// connect motor controller pins to Arduino digital pins
// motor one
int enA = 2;
int enB = 7;
int in3 = 5;
int in4 = 6;
int in1 = 3;
int in2 = 4;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  analogWrite(enB, 130);
  // turn on motor B
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  delay(500);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  delay(5000);
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 130);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  delay(100); //this function to set masa untuk rotation
  // now change motor directions
  // now turn off motor
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(200);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  delay(200);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(100);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);

  analogWrite(enB, 130);
  // turn on motor B
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  delay(400);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  delay(5000);
}

void loop()
{
  demoOne();
  delay(3000);

}

Looks like you are controlling two motor outputs via the H-bridge, where the logic inputs are in1,in2 and in3,in4.  First of all, you need

pinMode(in1,OUTPUT);
pinmode(in2,OUTPUT);

One reason why the motors may not spin for analogWrite value less than 130 is that, coincidentally, the voltage output is too low and motor stalls.  Test this two ways: does (1) changing the motor supply voltage or (2) changing the argument of analogWrite actually change the speed?

If no, it may be that pinMode(enA,OUTPUT); sets the output as digital and should be removed.  In that case a number less than 128 gets interpreted as a logic 0 and the motor will not spin.

P.S. your code can be neatened up using port syntax and bitwise operators.

digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);

can be written on a single line with

PORTD |= _BV(in1);

Also

digitalWrite(in1,LOW);
digitalWrite(in2,LOW);

becomes

PORTD &= ~(_BV(in1) | _BV(in2));


DC Motor Control L298N I am trying to control the speed of two motors using L298N. I use "Arduino Nano ATmega 168". I change the analogWrite between 0-255 but I cannot see any difference. When I assign it to something like 120 the motor stops.

The pwm pins of the motor drive is connected to the 7th and 8th pins of the Arduino. My code is like that:

const int in1=9; //motor 1
const int in2=10;//motor 1
const int in3=11;//motor 2
const int in4=12;//motor 2
const int p1=7;//pwm pin for motor 1
const int p2=8; //pwm pin for motor 2

void setup() {
  // put your setup code here, to run once:
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
pinMode(in3,OUTPUT);
pinMode(in4,OUTPUT);
pinMode(p1,OUTPUT);
pinMode(p2,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  analogWrite(p1,255);
  analogWrite(p2,130);
  digitalWrite(in1,HIGH);
  digitalWrite(in2,LOW);
  digitalWrite(in3,HIGH);
  digitalWrite(in4,LOW);

}

PS:

My Arduino and Motor Shield have same the ground
I use a power supply and not a battery.

I would be happy if anyone could help me)

const int p1=7;//pwm pin for motor 1

const int p2=8; //pwm pin for motor 2

PWM pins on a '168 are 3,5,6,9,10,11


Arduino due temperature reading shows random temperatures I am using an Arduino Due board to read three temperatures from three separate smt160-30 digital sensors but the program is behaving very randomly. the code I am using is one I got from arduino official site and changed the structure to get three temp readings and display them on a 16x2 lcd. The problem is when I use one sensor the output is reasonable but when I use all three the temperature showing are all off by 4 degrees. also I tried removing the line lcd.print(temperature1, 1) and the output temperatures changed. Is this odd behavior because of SRAM issues ? if so how can I find out about it and fix it ?

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

unsigned long now;
unsigned long lastSample;
unsigned int sampleSize;

unsigned int highCount1;
unsigned int highCount2;
unsigned int highCount3;

unsigned long lastOutput;

float temperature1;
float temperature2;
float temperature3;
float hcf1, hcf2, hcf3;
float ssf;

int sensorPin1 = 23;
int sensorPin2 = 24;
int sensorPin3 = 26;

void setup(){

    pinMode(sensorPin1, INPUT);
    pinMode(sensorPin2, INPUT);
    pinMode(sensorPin3, INPUT);

    digitalWrite(sensorPin1, LOW);
    digitalWrite(sensorPin2, LOW);
    digitalWrite(sensorPin3, LOW);

    lastSample = 0;
    sampleSize = 0;

    highCount1 = 0;
    highCount2 = 0;
    highCount3 = 0;

    temperature1 = 0;
    temperature2 = 0;
    temperature3 = 0;

    lastOutput = 0;

    delay(2000);
    lcd.setCursor(0, 0);

}

void loop() {
    now = micros();
    if (now - lastOutput > 3000000) {
        lcd.clear();

        hcf1 = highCount1;
        hcf2 = highCount2;
        hcf3 = highCount3;

        ssf = sampleSize;

        temperature1 = ((hcf1 / ssf) -0.32)/0.0047;
        temperature2 = ((hcf2 / ssf) -0.32)/0.0047;
        temperature3 = ((hcf3 / ssf) -0.32)/0.0047;

        lastOutput = now;
        sampleSize = 0;

        highCount1 = 0;
        highCount2 = 0;
        highCount3 = 0;

        lcd.print(temperature1, 1);
        lcd.print(" ");

        lcd.print(temperature2, 1);
        lcd.print(" ");

        lcd.print(temperature3, 1);

    }
    if (now - lastSample > 50) {
        sampleSize++;
        highCount1 = highCount1 + digitalRead(sensorPin1);
        highCount2 = highCount2 + digitalRead(sensorPin2);
        highCount3 = highCount3 + digitalRead(sensorPin3);
        lastSample = now;
    } else {
        delayMicroseconds(10);
    }
}

Thank you!

Did you read about this smt160 sensor ? It relies on the calculation of duty cycle of the square wave output from the sensor, to calculate the temparature.

  temperature = (dutyCycle) -0.32)/0.0047

The square wave output has to be sampled at 8KHz or at 125us for no loss of information. This block samples that data.

  if (now - lastSample > 50) {

  sampleSize++;

  highCount1 = highCount1 + digitalRead(sensorPin1);

  highCount2 = highCount2 + digitalRead(sensorPin2);

  highCount3 = highCount3 + digitalRead(sensorPin3);

  lastSample = now;
      }

  else {
          delayMicroseconds(10);
      }

when you increased the number of code lines , information loss also increased, cz more number of instructions have to be executed now , till reaching the corresponding digital reads.


HobbyTronics UNO PRO Board Definition does not work in newer IDE versions I have a HobbyTronics UNO PRO that replaces the UNO's 328P in DIP with an ATMega1284 on an adapter board:

I cannot link to the original page since it does not exist anymore.  But, it is available through archive.org.
The original board definition, supplied by the distributor, stopped working after 1.8.10 and throws errors in 1.9.
The particular error when trying to compile:
recipe.preproc.macros pattern is missing

It is not about a particular library or similar; I cannot compile at all (even an empty sketch).
How can I migrate this board? I'd really like to use a current version of the compiler & IDE.

Making your board definition work
What I did was slightly different from their directions, but:
Close any instances of the IDE you have running.
Create the directories along this path:
<sketchbook>/hardware/uno_pro/avr/variants/uno_pro

Where <sketchbook> refers to to where your IDE is saving sketches by default.
Place the following slightly modified boards.txt at <sketchbook>/hardware/uno_pro/avr/boards.txt:
uno_pro.name=Arduino Uno*Pro

uno_pro.upload.tool=avrdude
uno_pro.upload.protocol=arduino
uno_pro.upload.maximum_size=130048
uno_pro.upload.maximum_data_size=16384
uno_pro.upload.speed=115200

uno_pro.bootloader.tool=avrdude
uno_pro.bootloader.low_fuses=0xFF
uno_pro.bootloader.high_fuses=0xDE
uno_pro.bootloader.extended_fuses=0xFD
uno_pro.bootloader.unlock_bits=0x3F
uno_pro.bootloader.lock_bits=0x0F
uno_pro.bootloader.file=optiboot/optiboot_atmega1284p.hex

uno_pro.build.mcu=atmega1284p
uno_pro.build.f_cpu=16000000L
uno_pro.build.board=AVR_UNO_PRO
uno_pro.build.core=arduino:arduino
uno_pro.build.variant=uno_pro

This is the original file with one important modification, and that's the addition of arduino: in the second to last line reading uno_pro.build.core=arduino:arduino
Place the following (unmodified from original) pins_arduino.h at <sketchbook>/hardware/uno_pro/avr/variants/uno_pro/pins_arduino.h:
#ifndef Pins_Arduino_h
#define Pins_Arduino_h

#include <avr/pgmspace.h>

// ATMEL ATMEGA1284 on Hobbytronics UNO*Pro
//
//
// 2014-01-24 - Modified for Software Serial Library to work
//
//   ATMEGA1284 Pin     Arduino Mapping    Features
//     PA0                   D21  A7
//    PA1                   D20  A6
//     PA2                   D19  A5
//    PA3                   D18  A4
//     PA4                   D17  A3
//    PA5                   D16  A2
//     PA6                   D15  A1
//    PA7                   D14  A0
//
//     PB0                   D4
//    PB1                   D5
//     PB2                   D2
//    PB3                   D3               PWM
//     PB4                   D10                    PWM  SS
//    PB5                   D11                   MOSI
//     PB6                   D12              PWM  MISO
//    PB7                   D13              PWM  SCK
//
//     PC0                   D22                   SCL
//    PC1                   D23                   SDA
//     PC2                   D24
//    PC3                   D25
//     PC4                   D26
//    PC5                   D27
//     PC6                   D28
//    PC7                   D29
//
//     PD0                   D0                    RX
//    PD1                   D1                    TX
//     PD2                   D6                    RX1
//    PD3                   D7                    TX1
//     PD4                   D30              PWM
//    PD5                   D8               PWM
//     PD6                   D9               PWM
//    PD7                   D31              PWM
//

static const uint8_t SS   = 10;
static const uint8_t MOSI = 11;
static const uint8_t MISO = 12;
static const uint8_t SCK  = 13;

static const uint8_t SDA = 23;
static const uint8_t SCL = 22;
static const uint8_t LED = 13;

static const uint8_t A0 = 0;
static const uint8_t A1 = 1;
static const uint8_t A2 = 2;
static const uint8_t A3 = 3;
static const uint8_t A4 = 4;
static const uint8_t A5 = 5;
static const uint8_t A6 = 6;
static const uint8_t A7 = 7;

#define NUM_DIGITAL_PINS            32
#define NUM_ANALOG_INPUTS           8

// Macros
#define analogInputToDigitalPin(p)  ((p < NUM_ANALOG_INPUTS) ? (p) + 14 : -1)
#define digitalPinToAnalogPin(p)    ((p) >= 14 && (p) <= 21 ? (p) - 14 : -1 )
#define analogPinToChannel(p)         ((p) < NUM_ANALOG_INPUTS ? NUM_ANALOG_INPUTS - (p) - 1: -1 )
#define digitalPinHasPWM(p)         ((p) == 3 || (p) == 8 || (p) == 9 || (p) == 10 || (p) == 12 || (p) == 13 || (p) == 30 || (p) == 31 )

#define ifpin(p,what,ifnot)     (((p) >= 0 && (p) < NUM_DIGITAL_PINS) ? (what) : (ifnot))

extern const uint8_t digital_pin_to_pcint[NUM_DIGITAL_PINS];

#define digitalPinToPCICR(p)    ifpin(p,(&PCICR),(uint8_t *)0)
#define digitalPinToPCICRbit(p) ifpin(p,(digital_pin_to_pcint[p] >> 3),0)
#define digitalPinToPCMSK(p)    (((p) <= 1) ? (&PCMSK3) : (((p) <= 5) ? (&PCMSK1) : (((p) <= 9) ? (&PCMSK3) : (((p) <= 13) ? (&PCMSK1) : (((p) <= 21) ? (&PCMSK0) : (((p) <= 29) ? (&PCMSK2) : (((p) <= 31) ? (&PCMSK3) : ((uint8_t *)0))))))))
#define digitalPinToPCMSKbit(p) ifpin(p,digital_pin_to_pcint[p] & 0x7,0)

#define digitalPinToInterrupt(p)  ((p) == 6 ? 0 : ((p) == 7 ? 1 : ((p) == 2 ? 2 : NOT_AN_INTERRUPT)))

#ifdef ARDUINO_MAIN

#define PA 1
#define PB 2
#define PC 3
#define PD 4

const uint8_t digital_pin_to_pcint[NUM_DIGITAL_PINS] =
{
  24, // D0  PD0
  25, // D1  PD1 1
  10, // D2  PB2
  11, // D3  PB3
  8,  // D4  PB0
  9,  // D5  PB1 5
  26, // D6  PD2
  27, // D7  PD3
  29, // D8  PD5
  30, // D9  PD6 9
  12, // D10 PB4
  13, // D11 PB5
  14, // D12 PB6
  15, // D13 PB7 13
  7,  // D14 PA7
  6,  // D15 PA6
  5,  // D16 PA5
  4,  // D17 PA4
  3,  // D18 PA3
  2,  // D19 PA2
  1,  // D20 PA1
  0,  // D21 PA0 21
  16, // D22 PC0
  17, // D23 PC1
  18, // D24 PC2
  19, // D25 PC3
  20, // D26 PC4
  21, // D27 PC5
  22, // D28 PC6
  23, // D29 PC7 29
  28, // D30 PD4
  31  // D31 PD7 31
};

// these arrays map port names (e.g. port B) to the
// appropriate addresses for various functions (e.g. reading
// and writing)
const uint16_t PROGMEM port_to_mode_PGM[] =
{
    NOT_A_PORT,
    (uint16_t) &DDRA,
    (uint16_t) &DDRB,
    (uint16_t) &DDRC,
    (uint16_t) &DDRD,
};

const uint16_t PROGMEM port_to_output_PGM[] =
{
    NOT_A_PORT,
    (uint16_t) &PORTA,
    (uint16_t) &PORTB,
    (uint16_t) &PORTC,
    (uint16_t) &PORTD,
};

const uint16_t PROGMEM port_to_input_PGM[] =
{
    NOT_A_PORT,
    (uint16_t) &PINA,
    (uint16_t) &PINB,
    (uint16_t) &PINC,
    (uint16_t) &PIND,
};

const uint8_t PROGMEM digital_pin_to_port_PGM[] =
{
  PD, // D0
  PD, // D1
  PB, // D2
  PB, // D3
  PB, // D4
  PB, // D5
  PD, // D6
  PD, // D7
  PD, // D8
  PD, // D9
  PB, // D10
  PB, // D11
  PB, // D12
  PB, // D13
  PA, // D14
  PA, // D15
  PA, // D16
  PA, // D17
  PA, // D18
  PA, // D19
  PA, // D20
  PA, // D21
  PC, // D22
  PC, // D23
  PC, // D24
  PC, // D25
  PC, // D26
  PC, // D27
  PC, // D28
  PC, // D29
  PD, // D30
  PD, // D31
};

const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] =
{
  _BV(0), // D0  PD0
  _BV(1), // D1  PD1
  _BV(2), // D2  PB2
  _BV(3), // D3  PB3
  _BV(0), // D4  PB0
  _BV(1), // D5  PB1
  _BV(2), // D6  PD2
  _BV(3), // D7  PD3
  _BV(5), // D8  PD5
  _BV(6), // D9  PD6
  _BV(4), // D10 PB4
  _BV(5), // D11 PB5
  _BV(6), // D12 PB6
  _BV(7), // D13 PB7
  _BV(7), // D14 PA7 (A0)
  _BV(6), // D15 PA6 (A1)
  _BV(5), // D16 PA5 (A2)
  _BV(4), // D17 PA4 (A3)
  _BV(3), // D18 PA3 (A4)
  _BV(2), // D19 PA2 (A5)
  _BV(1), // D20 PA1 (A6)
  _BV(0), // D21 PA0 (A7)
  _BV(0), // D22 PC0
  _BV(1), // D23 PC1
  _BV(2), // D24 PC2
  _BV(3), // D25 PC3
  _BV(4), // D26 PC4
  _BV(5), // D27 PC5
  _BV(6), // D28 PC6
  _BV(7), // D29 PC7
  _BV(4), // D30 PD4
  _BV(7), // D31 PD7
};

const uint8_t PROGMEM digital_pin_to_timer_PGM[] =
{
  NOT_ON_TIMER, // D0  PD0
  NOT_ON_TIMER, // D1  PD1
  NOT_ON_TIMER, // D3  PB2
  TIMER0A,      // D3  PB3
  NOT_ON_TIMER, // D4  PB0
  NOT_ON_TIMER, // D5  PB1
  NOT_ON_TIMER, // D6  PD2
  NOT_ON_TIMER, // D7  PD3
  TIMER1A,      // D8  PD5
  TIMER2B,      // D9  PD6
  TIMER0B,      // D10 PB4
  NOT_ON_TIMER, // D11 PB5
  TIMER3A,      // D12 PB6
  TIMER3B,      // D13 PB7
  NOT_ON_TIMER, // D14 PA0
  NOT_ON_TIMER, // D15 PA1
  NOT_ON_TIMER, // D16 PA2
  NOT_ON_TIMER, // D17 PA3
  NOT_ON_TIMER, // D18 PA4
  NOT_ON_TIMER, // D19 PA5
  NOT_ON_TIMER, // D20 PA6
  NOT_ON_TIMER, // D21 PA7
  NOT_ON_TIMER, // D22 PC0
  NOT_ON_TIMER, // D23 PC1
  NOT_ON_TIMER, // D24 PC2
  NOT_ON_TIMER, // D25 PC3
  NOT_ON_TIMER, // D26 PC4
  NOT_ON_TIMER, // D27 PC5
  NOT_ON_TIMER, // D28 PC6
  NOT_ON_TIMER, // D29 PC7
  TIMER1B,      // D30 PD4
  TIMER2A,      // D31 PD7
};

#endif // ARDUINO_MAIN

#endif // Pins_Arduino_h
// vim:ai:cin:sts=2 sw=2 ft=cpp

Open the IDE and your board should be listed.  It should compile with a blank sketch.  I did not test further than that.
MCUDude MightyCore
Your board could also likely be made to work with MCUdude MightyCore.  However, MightyCore will not have your pin mapping.  So, although you could use it, you would need to ignore the normal UNO pin labeling and instead of work out which pin number used by the chosen MightyCore variant routes to which pin on the UNO headers.  It would be annoying to do, but you could do that by comparing entries in your adapter's pins_arduino.h file with the entries in the chosen variant from the MightCore package.  But, the modifications above seem to work fine.  So, I don't necessarily suggest that route; I'm just saying it could be used that way also.
MightyCore could also be modified, but that works out to the same or more work than just using your board definition, I think.


Modbus master arduino code is throwing weird errors on upload I am using the following https://code.google.com/p/simple-modbus/ arduino master library code. In order to communicate with my industrial drive.

All seems right but I am getting some weird errors. I am using the arduino master code as it is. With just the difference in modbus_construct.

Here is the error I am getting

 This report would have more information with
 "Show verbose output during compilation"

enabled in File > Preferences.
Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
In file included from SimpleModbusMasterArduino.ino:29:

C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:131: error: expected ',' or '...' before numeric constant
In file included from C:\Program Files\Arduino\hardware\arduino\cores\arduino/HardwareSerial.h:28,
                 from C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:215,
                 from SimpleModbusMasterArduino.ino:29:
C:\Program Files\Arduino\hardware\arduino\cores\arduino/Stream.h:57: error: expected ',' or '...' before numeric constant
In file included from SimpleModbusMasterArduino.ino:29:
C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:222: error: expected ',' or '...' before numeric constant
SimpleModbusMasterArduino:37: error: 'Packet' does not name a type
SimpleModbusMasterArduino.ino: In function 'void setup()':
SimpleModbusMasterArduino:45: error: 'packets' was not declared in this scope
SimpleModbusMasterArduino:45: error: 'READ_HOLDING_REGISTERS' was not declared in this scope
SimpleModbusMasterArduino:45: error: 'modbus_construct' was not declared in this scope

SimpleModbusMasterArduino:49: error: 'modbus_configure' was not declared in this scope SimpleModbusMasterArduino.ino: In function 'void loop()': SimpleModbusMasterArduino:56: error: 'modbus_update' was not declared in this scope

Here is my code:

#include <SimpleModbusMaster.h>

/*
   The example will use packet1 to read a register from address 0 (the adc ch0 value)
   from the arduino slave (id=1). It will then use this value to adjust the brightness
   of an led on pin 9 using PWM.
   It will then use packet2 to write a register (its own adc ch0 value) to address 1
   on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
*/

//////////////////// Port information ///////////////////
#define baud 115200
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 10

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 2
#define LED 13

// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 8
#define TOTAL_NO_OF_CONSTANTS 1

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  //PACKET2,
  TOTAL_NO_OF_PACKETS // leave this last entry
};

// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];

// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];

void setup()
{
  // Initialize each packet
  modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0x3000, 8, 0);
  //modbus_construct(&packets[PACKET2], 2, READ_HOLDING_REGISTERS, 0x3000, 8, 16);

  // Initialize the Modbus Finite State Machine
  modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  Serial.println(regs[0]);
  //regs[0] = analogRead(0); // update data to be written to arduino slave

  //analogWrite(LED, regs[0]>>2); // constrain adc value from the arduino slave to 255
}

Your issue is that you define constants, such as timeout, which are widely used in Arduino library as parameter names. After preprocessing your definitions, correct code in "Arduino.h" such as

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

becomes

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long 1000);

No wonder the latter line fails to compile.

You will need to find unique names for your defines, or use constant variables instead.


Counter on my coin acceptor goes up without a coin input, any advice? I'm working on a project that makes use of a CH926 coin acceptor. The problem we're having is that when I read the serial monitor, the coin value is continuously going up and adding credits when it's supposed to remain at 0 until a coin Is fed into the acceptor.

We've tried a different coin acceptor, different codes, arduinos, wiring, resistors, breadboards, the lot. nothing seems to be solving this problem and we can't determine why, it had been working fine until we tried to tidy up our wiring and untangle it.

we're using a basic code that had worked fine up until we had the issue of the counter value no longer remaining at 0:

const int coinpin = 2;
const int ledpin = 3;
const int targetcents = 100;

// Variables
volatile int cents = 0;
int credits = 0;

// Setup
void setup() {

  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(coinpin), coinInterrupt, RISING);
  pinMode(ledpin, OUTPUT);

}

// Main loop
void loop() {

  // If we've hit our target amount of coins, increment our credits and reset the cents counter
  if (cents >= targetcents) {
    credits = credits + 1;
    cents = cents - targetcents;
  }

  // If we haven't reached our target, keep waiting...
  else {
  }

  // Debugging zone
  Serial.print(cents);
  Serial.print(" cents toward current credit and ");
  Serial.print(credits);
  Serial.println(" credit(s) earned so far.");
  delay(1000);

  // Turn off LED
  digitalWrite(ledpin, LOW);

  // Now, write your own cool code here that triggers an event when the player has credits!
  if (credits > 0) {
    // Play music?
    // Spin up a motor?
    // Start a game?
    // It's up to you!
  }

}

// Interrupt
void coinInterrupt(){

  // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
  cents = cents + 1;
  digitalWrite(ledpin, HIGH);

}

any advice on what may be causing this problem?

cheers

I'm also complicated by that. The advice I saw here was to connect a COIN wire also against an electric "R" 10K and connect  to the second hole on the left in the Arduino "IOREF" now it works.


Connecting ESP8266 with Arduino Uno - WiFi shield not present I have an Arduino Uno and ESP8266. I want to connect and control an LED from a web server. I made a connection referring to this:

I uploaded the WifiWebServer code to the Arduino, and applied my router's credentials.

char ssid[] = "Router SSID";      // your network SSID (name)
char pass[] = "Router's WPA Password"; `

I'm getting a "Wifi Shield not present" message from the Serial Monitor. I even tried giving external 3.3v power supply to my ESP8266 module, but no change. What am I missing here? Can someone help me fix this issue?

You can program and upload code to ESP8266 using Arduino programming environment, reusing code and libraries with small changes. Check https://github.com/esp8266/Arduino for more information.

For most tasks ESP8266 may substitute Arduino board completely. It has more flash, more RAM and integrated WiFi, and is faster (80MHz).


Motor for a winch (with controller and external power supply) I'm in need of a motor or continuous servo to power a winch. The motor must be continuous* and reversible, but it does not need to be fast, precise, nor bear a load when powered off. It just needs to overcome ~50 Newton of friction force (to winch open my bedroom curtains laterally).

(* it needs to, given a discrete drum (maybe max 4cm diamater), winch about 1m)

I am using a MEGA2560 R3 which has a 5V port. I've tried using a 12V DC stepper motor (24BYJ48) with a standard ULN2003 controller, with a winch drum of ~2cm diameter, but it could not overcome the friction. I didn't spare much thought for the parameters of the arduino Stepper instance though; I just used a configuration which worked for winching lighter loads.

I'm a rookie, but I'm assuming my board cannot sufficiently power the motor(s) (I have 3), and possibly that they themselves are too weak. Hence I'm looking for a stronger motor and controller, controllable by my arduino, but which has a direct power supply (from mains). So:

have I got this all wrong? Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?
is there a shield for my MEGA which can enable these motors to function in parallel?
otherwise, is there a strong continuous servo with an external power supply that would work here?

Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?

No, you should never ever power a motor through an Arduino. It can only provide a limited amount of current, before it gets fried. You need to provide the motor driver with voltage directly from your power source. You haven't stated, what you are using as a power supply. I assume, you are just using an USB port of a PC. That is also a no-go, since it will only provide 500mA at max (that's even less, than the Arduino can bear). You should power your motor with a power supply of 12V, since it is rated for that voltage. You can buy a simple wallwart for that.

Also, currently you are providing the 12V motor with only 5V, so it cannot give you it's full power. Use a power supply with the correct voltage and more than enough current capability. Though you should keep an eye on the current ratings of the ULN2003. The datasheet is not really clear, if that chip supports 12V supply voltage. Some variants like the ULN2004 seem to support it, but I'm not sure about the ULN2003. If it is not rated for 12V, you can destroy the chip that way.

We cannot know, if the motor with it's driver will be able to rotate the winch, since the seller does not name the torque of the motor. You could try to contact the seller and ask directly about this. More specialized sites, where you can buy motors, will tell you exactly, what the torque of the motor is, that you are buying. Buying a cheap part at Amazon is somewhat the lightweight variant of buying it directly from china: The documentation is a bit better, but still not great. Without documentation or information from the seller, you are stuck with just buying and trying.

  is there a shield for my MEGA which can enable these motors to
  function in parallel?

It isn't clear, what you mean by that. You can control as many motors simultaneously, as you have pins and as you have enough computation time (meaning not too much steps per second or other stuff going on in the program). As mentioned above the power has to be supplied to the drivers from outside of the Arduino, so that does not apply here.

  otherwise, is there a strong continuous servo with an external power supply that would work here?

Power supply and motors are 2 different parts, that aren't usually sold together. Also you should start with the motor: Look for a motor, that can provide the torque, that you need. Then look for a driver circuit, that can provide the functionality, is rated for the same voltage as the motor and can provide enough current for the motor (the max. motor current is also information, that a good seller will provide). Then look for a fitting power supply. Unless you are buying some kind of kit, you need to choose these parts yourself. (We don't do product recommendations here)

A possibility, that you might not have though about: You could buy a normal DC motor, which provides enough torque. As speed is not your biggest concern, you could buy a geared DC motor, which can be rather strong. For a driver you would need to buy or build a H-bridge controller (which is essentially just 4 transistors put together). Be sure to use a MOSFET based driver, if you want to buy a driver chip. The standard L298n is pretty lossy.

It seems, that you generally don't know, how to build such a project. So here are some notes, that might help you with that:

Connecting everything together: In most cases (and especially when handling high current motors) you cannot get around soldering. You can buy a perfboard (cheap PCB material, with some pads already connected for ease of use), put the parts onto it and solder everything to the perfboard. Using shields as no-solder solution can only work, when you find a fitting shield and fitting motor for your requirements. That can be a far fetch. So if you want to get into electronics and Arduino, you probably should get yourself a soldering iron (there are also many tutorials about using it on the web).
Connecting the power supply: When buying a walwart power supply, it will normally come with a cable attached to it. At the end of this cable may be a connector. You have 2 options: Cut the connector and solder the wires in the cable directly to your perfboard, or buy the counter part of the connector, which you then can solder to your perfboard. Depends on if you want to disconnect the power supply from the circuit or not.

As I'm suggesting here to invest in this a bit, I want to also sketch an alternative, if you just want to get it work and don't experiment (this site is full of makers, you do this for fun, but that does not have to apply to everyone):

You may be able to use a shield to do, what you want to. This might cost a more, than putting the parts together yourself, but it will safe you the investment in tools, which you might not need in future. As above you need to choose the parts fitting your requirements. Decide on the type of motors, that you want to use (if money is not such a deal, you can nearly use any motor with enough power, stepper motor, DC motor, ...). Look for a shield, that can provide the needed current and voltage to the motor.

Every motor shield has a terminal for connecting the external power supply for the motors. On good shields this is a screw terminal, so you would simply strip the cable of the power supply and put the wires of it into the screw terminal.


What are the causes of Arduino lockup? We know watchdog timer if enabled RESETs when Arduino is locked up somewhere inside the code. As the title suggests has anyone experienced this unless they put deliberately a while(1) loop inside the code? Of course, buffer overflow or memory related issues are excluded.

I mean is it worth in Arduino to use watchdog and RESET rather than to fix the code to not get locked up. Are there still some behavior which are not predictable here?

Most Arduino projects involve sensing the physical world or controlling the physical world (hopefully with some feed back).  When sensing the physical world, it is best to add extra code to protect the project from locking up.  And then, even more code concerned with what to do when the unlikely happens.  Unfortunately, many projects leave out this extra code.  Reasons vary:

The project is a prototype and the effort is thought necessary.
There is no time in the schedule to create this "extra code".
The unexpected event is thought to be an impossible situation.
There is no room left to add code that is not expected to run.

As an example:

A bicycle is outfitted with an Arduio base digital speedometer.  Speed is calculated based on the period of a wheel mounted magnet passing a frame mounted Hall Effect switch.  It works as long as the bicycle is moving at a reasonable speed.  However, the program does not take into account what happens if the bicycle is not moving.  If the magnet does not pass the Hall Effect switch.  The program's period counter continues to count up.  Eventually the watch dog timer reset the program.  Over and over again.

Approaches to avoid lockup or to avoid using the watch dog timer:

Place all "non-blocking" polling in an infinite loop which also check the elapsed time.  Consider the amount of time allowed to make a successful reading.  If that time expires consider a good course for the program to follow.  For instance a warning to the user or a default value when the measured value is unavailable.
Use interrupts.  That is, use the above method, but relay on external signal changes to generate interrupts to set values and / or flags.  This is a good (however more complex) alternative if the external signal occurs too fast for "non-blocking" polling.


minimal code for multiple buttons de-bouncing i have 4 buttons attached to 4 pins configured as inputs with internal pull-up activated...

is this function sufficient to get a debounced state of the pressed button?

byte buttonPressed(){
  byte btn = 0;
  if (digitalRead(30)==LOW) btn = 1; else
  if (digitalRead(9)==LOW) btn = 2; else
  if (digitalRead(31)==LOW) btn = 3; else
  if (digitalRead(8)==LOW) btn = 4;
  delay(20);
  return btn;
}

any strictly necessary improvements are welcome...

Yes, your code should work as the most basic debouncing, although the
debouncing time may be a little bit short. Note however that, in many
instances, one would like to have a little more that the most basic. One
may also want:

deglitching: when the button is held down, your hand may make the
contacts move a little bit, making spikes in the reading that are not
associated with a real change in the button position; you don't want
those spikes to read as "released and pressed again"
edge detection: many times you are more interested in the button
press event than in knowing whether the button is down or up; this can
be handled by another function, but it can be convenient to integrate
it with the debouncing
non blocking operation: your program may have better things to do
than wasting CPU cycles inside delay().

Those are the reasons most debouncing codes are significantly more
complex. But it's often worth it.

Edit 1: In view of the comments, some clarification seems to be
needed. There are two kinds of glitches a mechanical button can
experience:

when the button is mechanically changing position, i.e. it is being
depressed or released; this is called a bounce
when the button is being held down, especially if the pressure on the
button is low and the finger applying that pressure is somewhat
shaky.

Most debouncing libraries you can find actually address both kinds of
glitches. Thus, they do more than just debouncing, they do what I
called “deglitching”. The previous answers implicitly assume that a
proper debouncing code must address both kinds.
The code posted in the question only addresses the first kind of
glitches, i.e. the bounces in the strict sense. That's why I wrote
that it does the “most basic debouncing”. It is however susceptible to
the second kind of glitches. So yes, with this code glitches can persist
even after debouncing.
Edit 2: As an example, consider the Bounce 2 library. It
provides edge detection, non blocking operation and, in the default
configuration, full deglitching. However, it can be configured to use
an alternative debounce algorithm called “Lock-out
interval”, which is more responsive but does not protect against the
“type 2” glitches mentioned above: it “does not cancel noise”, as the
documentation puts it.


Arduino IDE get stuck while uploading sketch I was trying to use my L293D motor driver module. But when I upload the following sketch to try and run my motor, but it would get stuck on "Uploading". This happens with this sketch only, and happens randomly, with odds of happening being 3 in 5 times. After a bit fiddling around I found an error

  Programmer is not responding.

When I try to reset the board or just reconnect it to my PC it might work.
Here's the sketch-

int RightMotorForward = 12;
int RightMotorReverse = 13;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

Can anybody point out where I am going wrong? I am using Arduino UNO. Is this just some problem in my code?

Is the motor driver connected to the Arduino while you program it?

When the Arduino is reset, the output pins on the Arduino are driven high. If too much current is drawn though any of these pins, then the voltage supply to the ATMega328 may drop, and the ATMega328 gets stuck in a brownout.


ESP8266 TCP/IP communication So I'm looking into having a TCP communication between 1 ESP8266 Chip (Station) and 2 ESP8266 (Clients) connected to that station. Every time I find a code including the TCP, they only include things like client.print(). But how can I write a message to a certain IP address in that network.

When I do client.print() it sends the message to ALL the clients. But I want to be able to do something like client1.print() and client2.print()

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side

WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}


Can I use the same Data Registry for both input and output pins? This is for a class in which we are not allowed to use the Arduino Library (Not my choice or preference). I know to use DDRB for the B pins. This is the code that I have so far:

//Global pointers
unsigned char *portDDRB = (unsigned char *) 0x24;
unsigned char *portDataB = (unsigned char *) 0x25;
unsigned char *portPinB = (unsigned char *) 0x23;

void setup () {
  //For the led output I know that I would do this
  *portDDRB |= 0x80;
}

void loop () {
   //And here the code would be like this to light up the light:
   if (condition to turn on light) {
     *portDataB |= 0x80;
   }
   // To Turn off the LED:
   if (condition to turn off the light) {
     *portDataB &= 0x7F
   }
}

I would like for the light to turn on when the input of PB4 is HIGH (from a button press). I just am not sure on what to put in the condition statements or the setup functions.

When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

I am using the Arduino Mega ATmega2560 btw.

From the comments I have this:

//Global pointers
unsigned char *portDDRB = (unsigned char *) 0x24;
unsigned char *portDataB = (unsigned char *) 0x25;
unsigned char *portPinB = (unsigned char *) 0x23;

void setup () {
  //For the led output I know that I would do this
  *portDDRB |= 0x80;
}

void loop () {
   //And here the code would be like this to light up the light:
   if (portPinB & 0x10) {
     *portDataB |= 0x80;
   }
   // To Turn off the LED:
   else {
     *portDataB &= 0x7F
   }
}

Assuming the button is connected between GND and pin 10, without any pull-ups or pull-downs.

void setup () {
    //For the led output I know that I would do this
    DDRB = 0;             // set all pins on port B to INPUT
    DDRB |= _BV(DDB7);   // set PB7 to OUTPUT
    PORTB = 0;            // set all pins on port B to LOW
    PORTB |= _BV(PORTB4); // enable the pull-up resistor on PB4
}

void loop () {
    if( PINB & _BV(PINB4) )
    {
        // if bit PINB4 is set, the button is not pressed
        PORTB &= ~_BV(PORTB7); // turn off led
    }
    else
    {
        PORTB |= _BV(PORTB7); // turn off led
    }
}


UART Software Serial - Syncing two sensors to make a tx and rx beacon Problem

I've been trying to a create a receiver and transmitter beacon for a following robot, but have not been able to sync my two SRF02s to one another.

Any advice?

Code

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd)
{
  mySerial.write(address);//set the address of SRF02(factory default is 0)
  mySerial.write(cmd);//send the command to SRF02
}
void setup(void)
{
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}
void loop(void)
{
  unsigned long t3;
  unsigned long t1=micros();//time tx command issued
  SendCmd(1, 0x5C);//send pulse with transmitter
  unsigned long t2=micros();//time rx command issued
  SendCmd(2, 0x5B);//listen for pulse returns results in microsconds

 while(mySerial.available() < 2)//if two bytes were received
  {}
    t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    t3 |= mySerial.read();// receive low byte as lower 8 bits
    unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
    unsigned long Dist = (Tm/29); //converting microseconds to cm
    Serial.print(t3); // print the reading
    Serial.println("cm");
    //Serial.print(tm);
    //Serial.println("ms");

  delay(250); // wait to read the output

}

Output#

theyre roughly 15 cm apart

15cm substantially less than the time it takes to send the second device its command at 9600 baud (2 bytes, probably 20 bits counting framing, around 72 cm)

As a result you are likely missing the pulse, and perhaps catching some timeout, or even a cached response string from a next-to previous command which measured the previous pulse, including the time between pulses.

To operate that close, you will need to either use dedicated trigger/detect wires, or start the receiver before you transmit and try to subtract the delay from the time you started the receiver until the time when you transmit.

Beware that usage of software serial, as well as buffering of serial in general may introduce variable latency in your timestamping of the serial communications.  Ideally for something like this you would use a non-buffered implementation - the timing of serial data itself is potentially precise to a fraction of the baud rate, though we don't know how it is implemented on the sensor end.


Using Arduino's hardware serial to control SIM900 I have a SIM900 board which has a serial interface. I'm trying to control it using Arduino Uno. I've tried using SoftwareSerial on pins 10 (RX) and 11 (TX) to talk to my board. It works OK with different baud rates (SIM900 has auto-bauding). I'm connecting pin 10 directly to my board, but pin 11 is connected through a voltage divider in order to lower voltage from 5 V to 2.8 V (SIM900 uses 2.8 V CMOS logic levels).

But now I want to use Arduino's hardware UART to talk to SIM900. I'm using pins 0 and 1 with similar design as above (also using voltage divider). I just can't get it to work. No matter what I do I can't see any communication. I've tried different baud rates, but it just doesn't work. Here is my code:

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

  delay(10000);
  Serial.write("AT\r");
  delay(1000);
  if (Serial.available())
  {
    digitalWrite(13, HIGH);
  }
}

void loop()
{
}

So I should see a LED light up but nothing happens (SIM900 responds with "\r\nOK\r\n" to "AT\r"). What am I doing wrong?

2.8V is not high enough to register as a high on an AVR input. You will need to use a level converter to raise the TX line of the SIM900 from 2.8V to 5V.


Missing bytes sended through serial from C# app I am trying to store values sended by C# app in EEPROM via Arduino UNO. Here is a C# code that reads bytes from file (I'm 100% sure that there are, and always will be 256 bytes) and sends the buffer via SerialPort

        SerialPort port = new SerialPort("COM3", 9600);
        const string fileName = @"filepath";
        port.Open();
        byte[] buffer = File.ReadAllBytes(fileName);
        port.Write("W");
        port.Write(buffer, 0, buffer.Length);

Here is Arduino Code

int flag;
int datasize = 256;
byte byteBuffer[256];

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

  //read_write();
}

void loop() {
  readEEPROM();
  writeEEPROM();
  delay(500);
}

void readEEPROM() {
  if (Serial.available()) {
    flag = Serial.read();
    if (flag == 'R') {
      for (int i = 0; i < datasize; i++) {
        byteBuffer[i] = ME.read(i);
      }
      flag = 'S';
      Serial.write(byteBuffer, datasize);
    }
  }
}
void writeEEPROM() {
  if (Serial.available()) {
    flag = Serial.read();
    if (flag = 'W') {
      int bytesRead = 0;
      digitalWrite(LED_BUILTIN, HIGH);
      delay(500);
      while (bytesRead < 256) {
        if (Serial.available() > 0) {
          byteBuffer[bytesRead] = Serial.read();
          bytesRead++;
        }
      }
  digitalWrite(LED_BUILTIN, LOW);

  for (int i = 0; i < datasize; i++) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    ME.writeEnable();
    ME.write(i, byteBuffer[i]);
    ME.writeDisable();
    digitalWrite(LED_BUILTIN, LOW);
    delay(50);
  }
  flag = 'S';
   }
  }
 }

As you can see in writeEEPROM function arduino turns on BUILTIN_LED before it starts reading serial, sadly the LED is never turning off, which makes me think like there are never 256 bytes in SerialPort, whats more, when i turn the c# program on again, the arduino successfully leaves the while loop, but the data is deformed, I mean the values are different.

There's two basic things wrong here.

First is your way of opening the serial port and immediately sending data.  The Arduino is reset when you open the serial port and the bootloader runs. This takes a second or so, and during that time any data that you send is lost.

Secondly you're not checking for a flag of "W" but instead you're assigning "W" to the flag, which always succeeds.

The line

if (flag = 'W') {

should read

if (flag == 'W') {

To get around the first problem you can either just put a delay (however you do that in C#) after opening the port and before sending the "W", or you could implement a "Are you there?" handshake to look for the Arduino.

One example would be to add an extra flag of (say) "?" to which the Arduino simply responds "Y".

The PC then sends "?" and, if it doesn't receive "Y" within a certain timeout it loops sending "?" again.

Once it receives "Y" then it knows the Arduino is there and ready to receive data, so you can send the "W" command and the data.


Custom atmega32u4 board crystal issue So I built an custom board based on the Atmega32u4. Schematics attached.

I managed to burn a bootloader for Pro Micro using Arduino Uno as an ISP.

The issue I have is that the board is dead when powered and to bring it to life I have to short pin1 of my crystal with VCC for a second. I discovered it by mistake..

The crystal I'm using is an Epson X1G004451000212.

Any idea why is this happening?

That's a Crystal Oscillator, not a crystal. Take the 22pF caps off to start.

Did you set the fuses to use an external clock source, vs a crystal with the internal oscillator driver (where the caps would be needed)?

Is the part oriented the correct way so it receives power and Gnd correctly?

Also, is it's performance any better than if you had just used a crytal?

https://support.epson.biz/td/api/doc_check.php?dl=brief_SG7050CAN&lang=en

vs these with +/- 10ppm stability (is that the same +/- 10 x 10 ^ -6 ?, which would b be better than 25 to 100 x 10 ^ -6)
https://www.digikey.com/products/en/crystals-oscillators-resonators/crystals/171?k=crystal&k=&pkeyword=crystal&pv1989=0&pv183=6185&pv2150=u16MHz&pv253=19&FV=ffe000ab&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25


How to measure CO2, Ammonia and Detect Smoke using MQ135? Setup Info:

MQ135 + Arduino+16x2LCD+ESP8266+ThinkSpeak.

Hi All, I have just bought a MQ135 . I started arduino basics with LED blinking , interfacing and then started with my real project.
e
I have seen in the data sheet of MQ135 that it can measure Ammonia, Sulfide,CO2 and Benze steam. It can also be used to detect smoke and alert.

But in the Arduino uno Serial monitor, I can see only one value 408.

Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

Also, my friend suggested to calibrate this sensor for which I found really good material and started with 24 Hours on test after dumping a code to read data from it.
Now I read 1836 which was 1795 , about half an hour back.

Kindly reply and let me know what info or input is required from My side.
This is my first of my many uno projects to come.

Regards,
Sillicon
https://forum.arduino.cc/index.php?topic=535401.msg3649205#msg3649205

Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

This sensor does not differentiate between the various gases that it is sensitive to.


Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding Before I tear all my hair and teeth out, can anyone please help. I have tried googling an answer and have not found anything.

My Setup:

Win7 64bit
Arduino 1.6.9 IDE freshly reinstalled
COM14 port in Arduino IDE checked
Under Device Manager COM14 shows as: "USB Serial Port (COM14)". Not as "Arduino...(COM14)" as some pages have shown
I am not sure if I have a real or copy of the Arduino. As far as I can figure out I have a real one, on the back I have the FT232RL chip
I have bought 2 Arduino Nanos and both show same error
Both Nanos came pre-soldered, (no noob soldering by me)
I have tried uploading sketches on my Win7 platform AND over a Raspberry Pi, both same error

Now perhaps most importantly I previously ordered an Arduino from the same retailer and that one worked. The two I have now dont work.

The problem:

When I try upload I get the same message every time: avrdude: stk500_recv(): programmer is not responding

a. it does this 10 times and then fails

b. Rx and Tx LED's are ON and do NOT blink at all at any point in time

c. Green power LED is always ON, no blinking

d. Pin13 LED blinks consistently

e. I have tried the extreemly annoying reset "trick" before uploading, after uploading, at the same time, during uploading, and nothing works

I am seriously at a loss here. I have had an Arduino Nano work on my pc.

Any help would be greatly appreciated please.

The Arduino.cc developers changed the bootloader on official Arduino Nanos to communicate at a different speed. Try setting Tools → Processor → ATmega328P (Old Bootloader)


How does Arduino determine whether the given condition provided to it is true or false? I want to understand how does the microcontroller determine that the conditions provided to it in the input are true or false. eg:

if (someVariable > 50)
{
  // do something here
}

Then how does Arduino determine if the value that I put in `somevariable' is larger than 50 (as apposed to less than or equal to 50)?

In general terms comparisons are usually performed, at the low level of assembly language, using subtraction.

In assembly language when you perform a subtraction there are flags in the status register that may or may not get set depending on what has happened. These include the Zero flag and the Carry flag.

If you are comparing A to B then you subtract B from A and see what happened by examining the flags.

For instance, if your variable contains 30 and you compare it to 50 you subtract 50 from 30. Because the result "passes through" zero the Carry flag is set. You can then do a "Jump if Carry Set" call.

If you should have 50 in your variable and you compare it to 50 the subtraction ends up with the Zero flag set since the result is exactly zero. It is then possible to do a "Jump if Zero Set" call.

If you have 60 in your variable and compare it to 50, the subtraction results in 10, which doesn't set either flag. That is actually slightly harder to work out (depending on architecture) since you are then wanting to compare two flags (Carry and Zero) and see if neither of them are set. So it is common for the compiler to optimize it so that the condition is reversed (a > b is the same as !(a <= b) for instance).

Of course, some architectures have actual comparison instructions (often CMP) which compares two registers and sets or clears the different flags for you. For instance, the ATMega328P has the instructions:

CPSE - Compare, Skip if Equal
CP - Compare
CPC - Compare with Carry
CPI - Compare Register with Immediate

CPI would be the most logical choice in the example you give - compare the contents of a register (variable) with an "immediate" value (an "immediate" value is a constant value):

CPI $r3, 50

According to the instruction set manual the comparison is, surprise surprise, performed as a subtraction, and what happened during the subtraction sets the different flags. To make life simpler the instruction set has a number of branch instructions which look at the different flag combinations and jump to another address if they match:

BRLT - Branch if the result of the previous comparison was A < B
BRLE - Branch if the result of the previous comparison was A <= B
BRGT - Branch if the result of the previous comparison was A > B
BRGE - Branch if the result of the previous comparison was A >= B
BREQ - Branch if the result of the previous comparison was A == B
BRNE - Branch if the result of the previous comparison was A != B

There are more as well for other special comparisons.  You can read up all about them in the AVR instruction set manual.


Arduino core structure and timer usage I needed to use TC1 for input capture, but also analogWrite() and an approximate 1 ms interrupt to poll the user interface (encoder, button).

The Arduino Nano's ATmega328p (datasheet, beware: a lot of bit symbol typos) has three timers:

TC0
TC1
TC2

It is not easy to find information on the "Arduino core" structure and it's use of peripherals. The Arduino Reference does not seem to refer to any information. Nor does Arduino Hacking.

Some info can be found on

https://arduino-info.wikispaces.com/Timers-Arduino

but I am not sure it's up to date. For instance, I find disabling TC2 also disables the analogWrite() PWM.
Trying to use TC0 results in an error, as TIMER0_OVF_vect is already being used ("multiple definition of `__vector_16'").

How can I use the timers (and their interrupts) that are already used for the core?

Here is a summary of all this. On an ATmega328P (Arduino Uno, Nano,
etc.), the Arduino core library uses the timers as follows:

Timer 0

timing and delay functions, using the TIMER0_OVF interrupt
“fast” PWM at 980 Hz on pins 5 and 6 (PD5 and PD6)

Timer 1

“phase-correct” PWM at 490 Hz on pins 9 and 10 (PB1 and PB2)

Timer 2

“phase-correct” PWM at 490 Hz on pins 3 and 11 (PD3 and PB3)

All three timers have their prescalers set to 64. TIMER0_OVF is the
only timer interrupt enabled by default.

Note that libraries can use the timers for their own purposes. Servo
for instance uses Timer 1 for doing interrupt-based PWM.


Can the nRF24L01+ CE and CSN pins be attached to Arduino pins A0 and A1? This documentation states that the CE and CSN pins can be specified.  Can I specify A0 and A1 as these pins?

Yes, you can. The mirf library is using the regular arduino functions pinMode and digitalWrite to manipulate the pins. So A0 and A1 should work as expected.

Please note that when you use SPI (which the NRF does), you have to use pin 10 (SS) as an OUTPUT (as to not put the AVR into SPI slave mode).


Program Arduino Uno as a digital clock I have an arduino Uno board with a screen attached on top (http://www.freetronics.com.au/pages/16x2-lcd-shield-quickstart-guide#.VUf0tMWN0iT This is the screen).

I'm trying to get it so that the screen displays the time in hours, minutes and seconds and counts on a 24 hours loop. Like a digital clock. I have it so that it can count but it just counts up to 99 then repeats.

I have this code which counts milliseconds but I need minutes and hours

    #include <Wire.h>
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

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

    void loop()
{
    lcd.setCursor ( 0, 1);
    lcd.print(millis());
}

Im with @arvid-jense on this one, if you are working on a serious Digital Clock, then you should get the Real Time Clock.

Now if you are learning Arduino and want to play with your LCD Minidisplay and build a clock, you must know some important limitations of the millis() function on this project:

The mills function will overflow, after approximately 50 days.
Your clock will be inexact because the cycles of the Arduino
loop, you will be checking how much mills has passed on each loop.
(it will be lagging ~ 10 seconds each day, so on day 7 you will be one minute late)
the parameter for millis is an unsigned long, errors may be generated
if a programmer tries to do math with other datatypes such as ints.

That being said

#include <Wire.h>
#include <LiquidCrystal.h>

/**
 * Clock Variables
 */
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds, minutes, hours;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

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

void loop()
{
    setClock();
    /**
     * After set clock now you have 3 int variables with the current time
     */
     //seconds
     //minutes
     //hours
     lcd.setCursor ( 0, 1);
     lcd.print(millis());
}

void setClock()
{
    currentMillis = millis();
    elapsedMillis += currentMillis - previousMillis;

    /**
     * If we use equals 1000 its possible that because of the mentioned loop limitation
     * you check the difference when its value is (999) and on the next loop its value is (1001)
     */
    if (elapsedMillis > 999){
        seconds++;
        elapsedMillis = elapsedMillis - 1000;
    }

    if (seconds == 60){
        minutes++;
        seconds = 0;
    }
    if (minutes == 60){
        hours++;
        minutes = 0;
    }
    if (hours == 24){
        hours = 0;
    }

    previousMillis = currentMillis;
}

Nice tutorial on building an Alarm Clock


Return mean of observations for a given sample time new to this StackExchange site. I have an experimental setup with three inputs - two from a laser distance sensor to measure planar distance and one digital input from a set of callipers.

All sensors readings fluctuate over a small range (which is acceptable for my use case). Is it possible to have the Arduino record all inputs for a given period of time and output only the mean value for each sensor?

I have this:

int readElSens() {
  long sum = 0;
  int n = 0;
  long start_time = millis();
  while(millis() - start_time < 400) {
    sum += analogRead(ELSENS_PIN);
    n++;
  }
  return sum / n;
}


How I can make alarm on off? I want to do is BEEP! to show that the program is running.

#define SPKR 4 //this is the digital pin that you plugged the red       wire into

void setup()
{
   pinMode(SPKR, OUTPUT); //set the speaker as output
}

void loop() //do this over and over
{
   digitalWrite(SPKR, HIGH); //turn the speaker on
   delay(500);                     //wait for half a second
   digitalWrite(SPKR, LOW); //turn the speaker off
   delay(500);                    //wait for half a second
}

With out this any other way
I mean without repeating the code HIGH / LOW
during this beep I want do same things else

The code you show will toggle the SPKR pin at a 1 Hz rate.  If you have an ordinary speaker attached, you will hear it click twice a second, but it won't generate an audible tone.

To generate a tone, use tone(pin, frequency) calls, or tone(pin, frequency, duration) calls.

For example:

void loop() {
   tone(SPKR, 400, 500); // 400 Hz tone for half second
   delay(500);           // no tone for half second
}

Note, ordinary speakers are low-impedance devices, eg 4 Ω, 8 Ω, etc.  You can use an audio transformer for impedance matching – this helps produce an adequate output volume – but lacking that, should put a resistor (eg 220 Ω) in series with the speaker to avoid over-current conditions.  AVR pins can deliver 25 mA without too much stress, and typically are rated at an absolute max of 40 mA.


Ethernet shield not have MAC address sticker Hi everyone I recently bought an Arduino Mega and Arduino Ethernet Shield. There are lots of forum posts that say the shield should have a MAC address that is written on the back side of shield, but I don't have any sticker which has the MAC address. Does anyone know how I can get my MAC address or configure it with a new MAC address? Thanks

According to this documentation, you can just provide your own.

  mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.


RDTSC alternative for Arduino To calculate an operation execution time, I was saving the millis() result before and after the operation to calculate the interval time. Is there an alternative on the Arduino Uno like the RDTSC found on x86 architectures?

There are several alternatives. The best choice for you depends on the
time resolution you need and the maximum duration you may want to
measure:

millis() is good for slow things. It has a resolution of 2 ms
(it increments by steps of 1 ms most of the time, but 2 ms
occasionally) and can measure durations as long as 49.7 days.
micros() is the easy choice for when you want more resolution for
faster things. It increments in steps of 4 µs and is limited to
about 71.6 minutes.
For very fast things, you can get single-cycle resolution if you
configure Timer 1 to count at the full CPU speed, assuming you
don't need the timer for something else. But beware the timer will
roll over roughly every 4.1 milliseconds.
You could also use Timer 1 with the prescaler set at ÷8 in order
to expand the measurable range to 32.8 ms, at the cost of a
degraded resolution.

Here is a table summing up the available methods, sorted by resolution:

method        data type  resolution  max. duration
--------------------------------------------------
millis()       uint32_t        2 ms     49.7 days
micros()       uint32_t        4 µs     71.6 min
Timer 1 (÷8)   uint16_t      0.5 µs     32.8 ms
Timer 1 (÷1)   uint16_t     62.5 ns      4.1 ms


Interfacing SPI (MCP3903) I'm trying to interface MCP3903. I haven't really don't any SPI interfacing before and I can't seem to find clear enough answer for newbs. Please bare with me.
I'm trying to use this library. http://www.kerrywong.com/2014/05/10/mcp3903-library/
On the website there is the following circuit diagram.

I can see SDI, SDO pins on the ESP module, how do I connect the SCK and CS pins? If they can be any pins how do I declare them on the test program on the website?
Thank you

SPI0 and SPI1 are used internally to access the ESP32’s attached flash memory. SPI2 and SPI3 are general purpose SPI controllers, sometimes referred to as HSPI and VSPI, respectively. They are open to users.
A quick google search shows:

So you can use IO5, IO18, IO19 and IO23.


Manually Declare Global Variable Is it possible to manually declare a global variable that is inside of a function. The only current way I know how to do so is to declare that variable within the setup() function or simply outside of any function, but I was hoping there was a way to manually declare a variable as global so that I may call one variable from within one function in another function.

You need to research 'Scope'.

Your variable has to be at the same level as all functions that will use it.  So at a simple level the answer has to be no.

int variableOne = 0;
void setup ()
{
  variableOne = 1;
}
void loop ()
{
  variableOne = 2;
}

The above code will work, but if you move int variableOne = 0; inside either function then it won't work, because the variable will not be in scope in the other function.

You can use parameters to functions.

void AFunction (const int& variable);

Will let you pass a single integer value to the function from the parent.  You can't change that value, because of the const qualifier.  If you remove the const then the & means pass the parameter by reference, which means you are passing in a reference (pointer) to the variable in the parent function and you can change it.  A better way to change the parent's value is to return a value from the call.

int AFunction (const int& variable);

So you could use this like this:

int AFunction (const int& variable)
{
  return (++variable);
}
void loop (void)
{
  int value = 0;
  value = AFunction(value);
  // value now == 1.
}

You could use a Singleton class, but this is hardcore and I'm not sure you would see any real benefit on an Arduino.  A class is a grouping of related function and variables that you see in libraries and a Singleton class means there will only ever be one during the lifetime of the program.  In this way you can declare an instance of the class (i.e. CSingleInstanceClass onlyOne;) and then retrieve/set data from the setup and loop function, i.e.

void setup ()
{
  CSingleInstanceClass onlyOne;  // Single instance class
  onlyOne.SetVariableOne (1);
}
void loop ()
{
  CSingleInstanceClass onlyOne;  // Single instance class
  Serial.println(onlyOne.GetVariableOne());// Prints 1
}

Hope that helps.


How do I change PGA gain in this Arduino program? Below is the link to three files I am using with a 32 bit ADC from TI, ADS1262, plus a link to it's datasheet. It works fine but I'm not getting any better voltage resolution than with a 16 bit ADC. I am using it for small voltage, from 0 to 0.070 volts. For example, for a known stable voltage of 0.01000 volts from a Fluke thermocouple calibrator I get 0.010000 to 0.010006. I get this same 0.000006 volt jitter if I short the ADS1262 input pins together. I suspect it may be a programmable gain amplifier issue. I can put 2.5 volts into it and not damage it. There is a line in the .ino file, #define PGA 1. On a guess, I changed this to #define PGA 32 but it had no effect on the results, it's like my attempted program change didn't take. I read in the ads1262 datasheet that the PGA Gain is in the MODE2 Register, address 05h. A gain of one is set with 000 and a gain of 32 is set with 101. But I do not know how to proceed. Perhaps somebody can help me out.

https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf

The symbol PGA appears in exapmle.ino (sic) twice, once each in lines 28 and 30:

 #define PGA 1                     // Programmable Gain = 1
 ...
 #define VFSR VREF/PGA

It is not used elsewhere in the example or the library code.  The only effect of changing its value from 1 to 32 is to change the value of VFSR, and asVFSR appears only in line 30, that effect is nil.

Looking at the ads1262.cpp file from github, it appears that ads1262::ads1262_Init() initializes register MODE2 to 0x6, via:

ads1262_Reg_Write(MODE2, 0x06);

which per the ADS1262 spec sheet, page 93, table 44, enables the PGA and sets its gain to 1 and sets the sample rate to 60 SPS.

Apparently, if you wish to use some other gain setting, you should define PGA appropriately and put a corresponding setting into MODE2.  For example, if you want to set up a gain of 16 and sample rate of 400 SPS, in setup() you could say

PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8); // 4=gain 16, 8=400 SPS

More generally, you could set up some constants for gain codes and SPS rates, and reference those constants when writing to MODE2.  For example, after

enum { GainCode1, GainCode2, GainCode4, GainCode8, GainCode16, GainCode32 };
enum { SPSCode2p5, SPSCode5, SPSCode10, SPSCode16p6, SPSCode20, SPSCode50,
       SPSCode60, SPSCode100, SPSCode400, SPSCode1200, SPSCode2400,
       SPSCode4800, SPSCode7200, SPSCode14400, SPSCode19200, SPSCode38400};

you would say

PC_ADS1262.ads1262_Reg_Write(MODE2, GainCode32<<4 | SPSCode2400);

to set the gain at 32 and the sample rate at 2400 SPS.

(Note, enum is a C language element used to define integer constants.  In an enum, each symbol mentioned without an explicit value has a value one more than the previous symbol, or zero if there's no preceding symbol.  So GainCode1 is 0, GainCode2 is 1, GainCode4 is 2, etc.)

Note, to get better ultimate resolution, you may need to combine multiple readings, or may need to set the ADS1262's filtering parameters.


Interrupting a servo sweep with a force sensor this is my first time dealing with arduinos and I have a school assignment. I have a servo and a force sensor. When "1" (a character, not an integer) is typed in the serial monitor, the servo needs to rotate 180 degrees but can be interrupted when the force sensor sends a value over let's say 300. And when "0" is typed in, the servo goes back to its initial position.
I have been trying really hard figuring this out.

I basically need to exit a loop when the analog value exceeds 300.

here's my code:

#include <Servo.h>
Servo myservo;

int initpos; //initial position of the servo before the sweep (this doesn't change)
int angle; //used to store the servo angle value (this changes)
char code; //the value entered in the serial monitor
int force; //value of the analog force sensor

void setup()
{
  initpos = 10;
  Serial.begin(9600);
  myservo.attach(4);

  myservo.write(170); // makes the servo sweep(absolutelly useless for my project but I left it there)
  delay(500);         //
  myservo.write(10);  //
  delay(500);         //

  code = Serial.read();

}

void loop()
{

  if(Serial.available())
  {

    angle = initpos;
    force = analogRead(A1);
    Serial.println(force);

    for(angle = 0; angle < 180; angle += 1)
    {
      if (code == "1" and force <= 300)
      {
        angle += 1;
        Serial.print(code);
        myservo.write(angle);
      }

      else if(code == "0")
      {
        myservo.write(initpos);
      }
    }

  }
}

any help is deeply appreciated and if there is already a topic on this please redirect me to it

I've written this code without access to a compiler,
so there might be errors. Use it as an idea how to solve the quest. Hopefully the comments are helpful. Don't hesitate to ask if you do not understand or correct me if you see an error.

#include <Servo.h>

Servo myservo;

// end positions of the servo
// declared as constant values
const int minPos = 10;
const int maxPos = 180;

int servoAngle;

int force;
char code;

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

  myservo.attach(4);
  // move the servo to minPos
  // or whatever you want/need
  servoAngle = minPos;
  myservo.write( servoAngle );

  // PPK: keep code as simple as possible -> sweep removed

  // PPK: removed - this makes no sense here
  // code = Serial.read();
}

void loop()
{
  // PPK: here you check if data is available (I added "> 0")
  if( Serial.available() > 0 )
  {
    // PPK: but you did not read the data
    // Let's do it
    char newCode = Serial.read();
    If ( newCode == '0' || newCode == '1' )
    {
      // only "0" and "1" are valid codes
      code = newCode;
    }
  }

  if ( code == '0' && servoAngle > minPos )
  {
    servoAngle--;
    myservo.write( servoAngle );
  }
  else if ( code == '1' && servoAngle < maxPos )
  {
    force = analogRead( A1 );
    Serial.println( force );
    if ( force > 300 )
    {
      servoAngle--;

      // PPK: the next line is only necessary if you want the
      // servo to go towards the min position
      // if a force > 300 is detected
      // remove the line if you wish to
      // hold the servo at the position where
      // the force exceeds 300
      code = '0':
    }
    else
    {
      servoAngle++;
    }
    myservo.write( servoAngle );
  }
  // a little delay to slow down the servo
  // remove it if you want
  delay( 10 );
}

EDIT

If you intend to stop the servo if force > 300, you can add a flag that indicates the exceptional state.

#include <Servo.h>

Servo myservo;

const int minPos = 10;
const int maxPos = 180;

int servoAngle;

int force;
char code;
int flagServoStopped = 0;

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

  myservo.attach(4);
  servoAngle = minPos;
  myservo.write( servoAngle );
}

void loop()
{
  if( Serial.available() > 0 )
  {
    char newCode = Serial.read();
    If ( newCode == '0' || newCode == '1' )
    {
      code = newCode;
    }
  }

  if ( flagServoStopped == 1 && code == '1' )
  {
    // The servo is frozen as long as the stop flag is set and
    // you have not entered a '0'.
    // leave the loop
    return;
  }

  // in case `code = '0'`, reset the flag if it is set.
  flagServoStopped = 0;

  if ( code == '0' && servoAngle > minPos )
  {
    servoAngle--;
    myservo.write( servoAngle );
  }
  else if ( code == '1' && servoAngle < maxPos )
  {
    force = analogRead( A1 );
    Serial.println( force );
    if ( force > 300 )
    {
      flagServoStopped = 1;
    }
    else
    {
      servoAngle++;
      myservo.write( servoAngle );
    }
  }
  delay( 10 );
}


DCMotorTest from the Adafruit site – got fatal error exit status 1 New to Arduino, I plugged in DCMotorTest from the Adafruit site and got this error message: a fatal error exit status 1

/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

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

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}

My error message was:

Arduino: 1.6.7 (Mac OS X), Board: "Arduino/Genuino Uno"

/Users/student/Downloads/Adafruit_Motor_Shield_V2_Library-master/examples/DCMotorTest/DCMotorTest.ino:11:34:
 fatal error: Adafruit_MotorShield.h: No such file or directory
 #include <Adafruit_MotorShield.h>
                                  ^
compilation terminated.
exit status 1
Error compiling.

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

Based on the error report it seems that you have just opened the example program from the downloaded folder. In order to add library files (which includes the header files, c++ source code, etc.) you have to move the Adafruit_Motor_Shield_V2_Library-master folder to the libraries folder.

  Documents > arduino > libraries

If no such folder exist, then create a new folder and name it libraries.

To check weather the libraries have been installed, open arduino IDE goto

  file > example and check weather the example programs are added (you will see "adafruit" in the list)

Now, restart the arduino IDE and things should get going.

Note:
Do not use "-" and do not include space while naming a folder, as the compiler may throw up error. Instead you are free to use "_","$". Name of a folder should always start with a letter.

For more detail visit https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use/how-to-install-a-library


Can I use this board to control multiple vibration motors? I am looking at this: https://learn.adafruit.com/16-channel-pwm-servo-driver

Although it’s meant for servos, I was wondering if I could use them to control vibration motors.

Motors like these: Diameter Flat Button Type 3V-4.5V Cellphone Micro Vibration Motor (Pack of 3) https://www.amazon.in/dp/B07CQXZBZD/ref=cm_sw_r_cp_tai_yzSvDb8V7JAF4

Any suggestions? I would like to control about 200 motors with minimal number of controllers.

Each motor should be controllable individually.

Not directly, no.  Those boards are designed to generate a low power PWM signal for passing to a servo with a built-in controller. To use that output directly with a motor you will need to add a transistor to each output to control the motor.

simulate this circuit – Schematic created using CircuitLab


which is the most efficient way to save power with battery using Arduino UNO? I am working with a ArduinoUNO - 2100 mA battery, and a solar Charger shield. I use a temperature reader that sends info every half hour with GPS-GSM shield called LONET (http://www.seeedstudio.com/wiki/LoNet_-_GSM/GPRS/GPS_Breakout for more info).

I want to save all the energy i can, i am trying to put Arduino UNO and LONET on Sleep mode.

LONE has its own mode via “AT+CSCLK=1”.

But for Arduino UNO i haven seen a library called Narcoleptic (https://code.google.com/p/narcoleptic/ for more info) wich can solve the problem.

My question is:

Is there any other method that can help me to save Battery with Arduino uno? is it a good approach to use Narcoleptic or there is another method to do it?

Thanks for your time/help and sorry for my English.

Any feedback could be welcome.

There is an even greater article on this topic: http://www.gammon.com.au/power

It shows how to reduce your power usage for the Uno from about 50mA to 350nA (0.000350mA) - at this point, you need to factor in the natural drain of batteries.

Also, I have had good success with a project that was activated by a pushbutton, by using a latch - the push button turned the power on; once the power is on, it latched. Then the Arduino can switch itself off, using one of it's pins. As far as I can tell from a simulator, there is no leakage (while it is off, to within the accuracy of the simulator, assuming a perfectly spherical transistor in a vacuum ;) ).

Just in case anyone is interested, my latch circuit can be seen at: http://i.imgur.com/sDvW4rd.png - the two resistors and the switch at the bottom represent the Arduino - +5V coming in the top, GND at the bottom, and one of the pin to switch it off is the switch - this pin should be INPUT to keep the power on; when you are ready to switch of, set it to output -> high. You should get switched off immediately. The switch at the top will switch it on. In the startup part of your sketch, set the pin to INPUT first.


Running an Arduino without the computer I am having trouble getting my Arduino uno to run my code when I disconnect it from my computer. I have a 9V battery to power it and it is turning on, however, it is not doing anything at all. What can I do to make it run the code when it is using the battery and not connected to the computer?

And Arduino should run the last program installed to it when you apply power to the barrel connector. IT powers up, does a reset, and begins executing the sketch that's installed.
As others have mentioned, the small rectangular 9V batteries have very low current output and total power storage. You will run a fresh 9V battery down to nothing in a short time with just an Arduino, and with other components also drawing power it will happen even faster. I suggest getting a ≥ 1 amp 7V - 9V DC transformer and plugging that into the barrel connector.
You need to tell us what components you are using in your project and their current requirements.
If you are just running a "bare" arduino and very little else then you should get like 24 hours out of a fresh 9V battery, as mentioned by @ocrdu


How to read Arduino voltage I am trying to do voltage measurement using Arduino. I am using a voltage divider circuit to reduce the voltage to less than 5V. I measured the voltage on the 5V pin of Arduino and found out that its 4.279 V (I am powering through USB).  So, I am doing following calculations for voltage measurement:

int data1   = analogRead(A0);
float data2 = data1 * (4.279/1023.0);
float volts = data2 * (10 + 2.2)/2.2;  //R1=10k , R2=2.2k
Serial.println(volts);

if(volts > 12.00)
{
  digitalWrite(6,HIGH);
}
if(volts < 12.00)
{
  digitalWrite(6,LOW);
}

So I am getting exact values of voltage. Now I have put a condition like if volt is greater than 12V, turn on an output, else turn off the output. For output, I have a transistor and mosfet connected. As soon as the voltage increases above 12V, output get on but the problem is that when the output is on, Arduino displays wrong values. Like if the voltage is 12.3, it shows 13.6.

I looked it into more and found out that the voltage at 5V pin of Arduino (4.279) gets reduced to 3.865 and due to which calculation goes wrong and it displays wrong values of voltage.

Is there anything which I am doing wrong? Is there any function or keyword in Arduino libraries which can tell us the voltage or is there any way through which we can measure it? I tried putting the 5V pin to analog pins to read it and convert it into volts but again for this we need a reference voltage.
I hope I have explained the question clearly.

Schematic

A0 is the analog pin and PIN6 is digital output of arduino

It would appear that the wrong A/D reading is due to the reduced +5V output. The A/D reference is powered by the input to the computer chip. The big question is what is causing the voltage drop. Are you powering something else
from the USB supply when the FET is turned on? Bottom line is that you cannot
expect the A/D to read the same voltage when the voltage input to the computer chip is changed.


How to recover from DHCP Renewal and Rebind failures? I'm using an Ethernet shield with the built-in Ethernet library. I obtain an IP address using DHCP, and call Ethernet.maintain() periodically to ensure that the DHCP lease is renewed as required. So far I've never seen this fail, but maintain() can return error codes for renew fail and rebind fail and I assume that I should be handling them. What conditions would cause these errors to occur, and what's the best practise for recovering from them? Is it enough to call Ethernet.maintain() repeatedly until it returns cleanly, should I call Ethernet.begin() to reinitialise the Ethernet shield, or would it be best to reset both the Arduino and Ethernet shield using the watchdog timer?

Possible causes:

The DHCP server might be down.
Or it might have lost its state (but I think they try really hard to preserve the list of leases).
Or some other cause which makes the server unavailable/unwilling to renew the lease.

Solutions:

If you can wait, you can retry, but otherwise I'd just say try to obtain a new lease, unless for some reason you really want to stick to the IP from the previous lease.
If you control the server and your network is kinda stable, you could assign a fixed IP to your device configure the server to associate it with the MAC address you gave to your device. In general, when the network setup is really stable, this might be preferable, since other entities on the network will probably cache the IP of your device and use it, should the DNS fail as well (ex: dnsmasquerade works both as dhcp server and dns). Similarly, your device doesn't have to worry anymore of the DHCP lease, because it's permanent.