strtoul behavior between C and Arduino I have this code C code that compiles OK on my laptop

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

unsigned int crc32(const void *m, size_t len) {
  const unsigned char *message = m;
  size_t i;
  int j;
  unsigned int byte, crc, mask;

  i = 0;
  crc = 0xFFFFFFFF;
  while (i < len) {
    byte = message[i];
    crc = crc ^ byte;
    for (j = 7; j >= 0; j--) {
      mask = -(crc & 1);
      crc = (crc >> 1) ^ (0xEDB88320 & mask);
    }
    i = i + 1;
  }
  return ~crc;
}

int main() {
  char str[] =
      "620004";
  size_t len = strlen(str);
  unsigned int crc = crc32(str, len);

  size_t len2 = (len + 1) / 2;
  unsigned char arr2[len2];
  for (size_t i = 0; i < len; i += 2) {
    arr2[i / 2] = strtoul((char[3]) {str[i], str[i + 1], '\0'}, 0, 16);
  }
  crc = crc32(arr2, len2);
  printf("CRC: 0x%X\n", crc);

  return 0;
}

And I'm trying to port it to Arduino

#include <CRC32.h>

void setup() {
  Serial.begin(115200);
  uint8_t byteBuffer[] = "620004";
  size_t numBytes = sizeof(byteBuffer) - 1;
  size_t len2 = (numBytes + 1) / 2;
  unsigned char arr2[len2];
  CRC32 crc;
  for (size_t i = 0; i < numBytes; i += 2) {
    arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
  }
  for (size_t i = 0; i < numBytes; i++){
    crc.update(byteBuffer[i]);
  }

  uint32_t checksum = crc.finalize();
  Serial.print("CRC: ");
  Serial

But I'm getting a

Arduino: 1.8.9 (Linux), Board: "Arduino/Genuino Uno"

/home/nico/Arduino/crc32/crc32.ino: In function 'void setup()':
/home/nico/Arduino/crc32/crc32.ino:11:50: warning: narrowing conversion of 'byteBuffer[i]' from 'uint8_t {aka unsigned char}' to 'char' inside { } [-Wnarrowing]
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                  ^
/home/nico/Arduino/crc32/crc32.ino:11:69: warning: narrowing conversion of 'byteBuffer[(i + 1u)]' from 'uint8_t {aka unsigned char}' to 'char' inside { } [-Wnarrowing]
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                                     ^
crc32:11:84: error: taking address of temporary array
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                                                ^
exit status 1
taking address of temporary array

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

And I'm not really understanding what's the issue here with the strtoul function and its different behavior on Arduino

In some architectures a "char" is an "unsigned byte". In others it's a "signed byte".  The AVR specification mandates a signed byte for char. Whatever you are compiling on probably mandates an unsigned char.

You cannot assume one or another. If you are working with an array of characters (a "string") you should be assigning it to a char data type. That way the signage of the data type and the "string" content will match.

By using uint8_t you are specifically telling it to use an unsigned byte.

strtoul() expects a char. Since on AVR char is signed, when you try and squeeze an 8-bit value into a 7-bit + sign space it warns you. Which is good. You potentially lose the 8th bit of your data.

The main error, though, is:

error: taking address of temporary array

This is caused by you creating a new temporary array within the parameter list of strtoul.

{byteBuffer[i], byteBuffer[i + 1], '\0'}

Then you take the address of that array and pass it to the function.  That is not good. Imagine the situation where the function returns something that is dependent on that address. For instance a function that returns a pointer to all but the first character of the string.  Once the function returns that returned pointer points to an area of memory that is no longer valid - the temporary array has already been disposed of.

I know that's not the case in your code, but it's a possibility you can conceive.

Yes, temporary arrays like that are perfectly valid in some versions of C++. But those are fairly recent versions, and the Arduino compiler isn't that recent (I don't know which version introduced them as valid off hand, but we're up to GCC version 8 now. Arduino is still down at version 5.something IIRC).

Suffice it to say, don't use temporary arrays like that (which is a shame, because it's damn useful).  Instead you have to assign it to a new array and pass the pointer to that array instead:

char tempArr[3] = {byteBuffer[i], byteBuffer[i + 1], '\0'};
 arr2[i / 2] = strtoul(tempArr, 0, 16);

That way the address you're passing to the function is one that is allocated on the stack and is guaranteed to exist past the lifetime of the function call (right up until the end of the current scope).


Can do I make an Arduino program that can decipher telephone touch tones? I have an old land line phone that I want to connect to my Arduino.  Then I would like to write a program that can decipher the touch-tone button presses (which are a combination of two tones) so that the Arduino can react to specific key presses and numeric sequences.  My final goal is to make the Arduino play specific messages when the user enters in codes.  I am really not sure even where to begin.

Thanks for the hardwares fixes for this problem, but if possible, I am looking for a softwares solution.

This will be used to make a telephone (with an attached Arduino) that will play a series of conversations when specific codes are dialed.

It is possible to decode DTMF tones with only a few common external components. The trick is to turn the analog audio into a digital signal, and then check the timing between the leading and trailing edges in order to figure out which tone is present.

First, create a 1.1V bias using a voltage divider. This bias will connect to both a capacitor that is coupling the audio, as well as one of the analog inputs. Note that phone lines have high voltages on them at times, and you must have both isolation and voltage clamping in place before connecting a device to one.

Second, enable the analog comparator in the MCU. See the "Analog Comparator" section of the MCU datasheet for details. Configure the non-inverting input to connect to the internal bandgap reference, the inverting input to connect to the analog input chosen earlier, and the output to connect to the input capture facility.

Third, configure the input capture facility in the MCU. See the "16-bit Timer/Counter1 with PWM" section of the datasheet, with particular emphasis on the "Input Capture Unit" subsection. Note that there is no way to trigger the input capture on "any" edge, therefore you will need to either flip the capture edge select bit each time, or you will need to detect the tone from only one set of edges. Also note that you will need to use the overflow interrupt to increment your explicit "high bytes" counter in case the edges to be detected appear on opposite sides of the overflow.

Now that all that is done, all that remains is to compare the timing detected by the input capture with your internal table of timings and select the appropriate tone from that. But that's the easy part.


How do I stop the slave from running the code until master sends a new value? I2C I'm a total noob when it comes to Arduino. I'm slowly learning stuff. I was trying this code which basically gets input in Arduino1(master) and displays the character in serial monitor of Arduino2(slave). The code words just find but I just need the slave to wait until the master sends the next character. Right now, the slave is continuously printing the character.

Master code:

    #include "Wire.h"
    char ch;

    void setup() {

      Serial.begin(9600);
      Wire.begin();

    }

     void loop() {
      while(Serial.available()==0)
      {}
      ch=Serial.read();
      delay(1000);
      Serial.print("The character that you entered is ");
      Serial.println(ch);

      Wire.beginTransmission(9);
      Wire.write(ch);
      Wire.endTransmission();

        }

Slave code:

#include "Wire.h"
char x;

void setup() {

  Serial.begin(9600);
  Wire.begin(9);
  Wire.onReceive(Event);

}
void Event(char bytes){
  x = Wire.read();
}

void loop() {

  Serial.print("The character that you entered in the other Arduino is ");
  Serial.println(x);
}

I know that this will be simple but I just can't quite figure out what to do. Please help me out

#include "Wire.h"
volatile char x;
volatile bool received;

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

void Event(char bytes){
  x = Wire.read();
  received = true;
}

void loop() {

  if (received) {
    received = false;
    Serial.print("The character that you entered in the other Arduino is ");
    Serial.println(x);
  }
}


Why we are using client.flush() in the program code ,when we connect Esp8266 with internet or web server? I am using Esp8266 Wifi modular (12-E) for controlling a led through the access of wifi/webserver.
I have written code in Arduino ide taking various references from the google.In the code, I didn't understand the client.flush(), why we are using this method? In google, I have searched about many explanations, I got common to explain which I don't understand till yet.
"Waits for the transmission of outgoing serial data to complete."
I didn't get till yet. can anyone explain to me in simple terms?
/
/ Wait until the client sends some data

  Serial.println("new client");

  while(!client.available()){

    delay(1);

  }

  // Read the first line of the request

  String request = client.readStringUntil('\r');

  Serial.println(request);

  client.flush();

This is most likely related to the old usage of .flush() from pre IDE version 1.0.0.
In those old versions .flush() would erase any pending data in the reception buffer. It was the equivalent of:
while (client.available()) {
    client.read();
}

Now though it's used to ensure that all data has been sent before doing anything else. In this situation it's completely meaningless.


Simple IR Receiver code Can I know a code for simple IR receiver. I using external trasmitter, and when the receiver (on arduino board) get the input (detect signal from transmitter), LED will be HIGH.

Here is a library that might be able to help you out: https://github.com/cyborg5/IRLib/. Also a specific example of controlling a server from a sony remote control. https://github.com/cyborg5/IRLib/blob/master/examples/IRservo/IRservo.ino

I am slightly confused on what you mean 'get input'. So I am assuming an input from a button. Here is some pseudo code compiled from the IRservo example that might point you in the right direction.

#include <IRLib.h>

#define MY_PROTOCOL SONY
#define BUTTON_0 0x90bca  //LED ON
#define BUTTON_1 0x00bca  //LED OFF

#define LED_PIN 13 //Pin to LED

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;

void setup() { //Code to run once
  My_Receiver.No_Output();//Turn off any unused IR LED output circuit
  My_Receiver.enableIRIn(); // Start the receiver

  pinMode(LED_PIN, OUTPUT); //Set LED 13 to out
  digitalWrite(LED_PIN, LOW); //Start off in the off position
}

void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
       My_Decoder.decode(); //Convert the values into types
       if(My_Decoder.decode_type==MY_PROTOCOL) { // Match the controller
          switch(My_Decoder.value) {
            case BUTTON_0:      digitalWrite(LED_PIN, HIGH); break; //Turn the LED on
            case BUTTON_1:      digitalWrite(LED_PIN, LOW); break; //Turn the LED off
          }
       }
     My_Receiver.resume(); //Wait for next input
    }
}

This should theoretically work, but has never been tested. Now if you are just wanting any result to turn on the LED you might be able to do this

void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
        My_Decoder.decode();
        digitalWrite(LED_PIN, HIGH); //Turn the LED on
    }
    My_Receiver.resume(); //Wait for next input
}

Edit:

A sample from getting text (Different library) from the receiver and printing it to the Serial Monitor. Link to library: https://github.com/z3t0/Arduino-IRremote

    #include <IRremote.h> //Link: https://github.com/z3t0/Arduino-IRremote

#define IR_PIN = 11; //The data pin to the IR recv
#define LED_DATA = 13; //Either the builtin LED or plug one in

IRrecv irrecv(IR_PIN); //Start recv obj
decode_results results;

void setup()
{
  Serial.begin(9600); //Start Serial at 9600 baud
  pinMode(LED_DATA, OUTPUT); //Set LED pin to out
  digitalWrite(LED_DATA, LOW); //Start recv data view pin in low
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    //We have recieved something... lets print it and turn on the LED
    digitalWrite(LED_DATA, HIGH);
    Serial.println(results.value, HEX); //Send line in ascii hex format
    delay(200); //Make the LED visible
    digitalWrite(LED_DATA, LOW); //Turn off data led
    irrecv.resume(); // Receive the next value
  }
}

Edit #2

Since an image has been provided I believe this is what you want. To turn the ir data into a visible light... To do that is a little more tricky in just doing code. Here's an example that doesn't require any external libraries and will do what you want.

    #include <avr/interrupt.h>
#include <avr/io.h>

#define TIMER_RESET  TCNT1 = 0
#define SAMPLE_SIZE  64
#defome LED_PIN 13

int IRpin = 2;
unsigned int TimerValue[SAMPLE_SIZE];
char direction[SAMPLE_SIZE];
byte change_count;
long time;

void setup() {
  Serial.begin(115200);
  Serial.println("Analyze IR Remote");
  TCCR1A = 0x00;          // COM1A1=0, COM1A0=0 => Disconnect Pin OC1 from Timer/Counter 1 -- PWM11=0,PWM10=0 => PWM Operation disabled
  // ICNC1=0 => Capture Noise Canceler disabled -- ICES1=0 => Input Capture Edge Select (not used) -- CTC1=0 => Clear Timer/Counter 1 on Compare/Match
  // CS12=0 CS11=1 CS10=1 => Set prescaler to clock/64
  TCCR1B = 0x03;          // 16MHz clock with prescaler means TCNT1 increments every 4uS
  // ICIE1=0 => Timer/Counter 1, Input Capture Interrupt Enable -- OCIE1A=0 => Output Compare A Match Interrupt Enable -- OCIE1B=0 => Output Compare B Match Interrupt Enable
  // TOIE1=0 => Timer 1 Overflow Interrupt Enable
  TIMSK1 = 0x00;
  pinMode(IRpin, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

void loop()
{
  Serial.println("Waiting...");
  change_count = 0;
  while(digitalRead(IRpin) == HIGH) {}
  TIMER_RESET;
  TimerValue[change_count] = TCNT1;
  direction[change_count++] = '0';
  while (change_count < SAMPLE_SIZE) {
    if (direction[change_count-1] == '0') {
      while(digitalRead(IRpin) == LOW) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '1';
      digitalWrite(LED_PIN, LOW);
    } else {
      while(digitalRead(IRpin) == HIGH) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '0';
      digitalWrite(LED_PIN, HIGH);
    }
  }
  Serial.println("Bit stream detected!");
  change_count = 0;
  time = (long) TimerValue[change_count] * 4;
  digitalWrite(LED_PIN, LOW)
  Serial.print(time);
  Serial.print("\t");
  Serial.println(direction[change_count++]);
  while (change_count < SAMPLE_SIZE) {
    time = (long) TimerValue[change_count] * 4;
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count-1]);
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count++]);
  }
  Serial.println("Bit stream end!");
  delay(2000);
}

If you want a non code example check out the answer below. It is a great solution. Without needing any arduino.

best regards, David


Can I specify that analog pins be used for digital output? http://arduino.cc/en/Reference/pinMode notes that

  The analog input pins can be used as digital pins, referred to as A0, A1, etc.

Is it possible to configure these pins as digital output pins as well?

Yes.

http://arduino.cc/en/Tutorial/AnalogInputPins states

  The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc. For example, the code would look like this to set analog pin 0 to an output, and to set it HIGH:

pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH)

There are several caveats on that page regarding this.


Arduino Mega PWM doesn't work in C Code Why such horrible Arduino's Mega PWM doesn't work??

Below is my code.

I try to set Fast PWM 8-bit to dim and light up a LED connected to OCR1A Pin. I try to do it in C language, completelly without Arduino's lbraries and it doesn't work at all.

I'm working with documentation and the code seems me to be correct. Almost the same code worked on ATmega8 and ATmega16 (obviously, with special setting for those special ATmegas) but this one doesn't.

The comments in this code point out, that I tried to use few other flags to  check if it work with some of another settings.

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

//Anode of LED connected to OCR1A (digital pin 11)
#define LED (1<<PB5)

int main()
{
  DDRB |= (1 << LED);

  //FAST PWM 8-bit, set OCR1A at the Bottom
  TCCR1A = (1 << COM1A1) | (1 << WGM10);    // | (1<<WGM11) | (1<<COM1A0)
  //Prescaler :1024
  TCCR1B = (1 << CS12) | (1 << WGM12);     //| (1<<WGM13); //Presc :1024  (1<<CS10) |
  //Enable to interrupt Compare Match A
  TIMSK1 = (1 << OCIE1A);

  uint8_t i;

  sei();

  while (1)
  {
    for (i = 0; i < 255; i++)
    {
      OCR1A = i;
      // _delay_ms(5);
    }

    for (i = 255; i > 0; i--)
    {
      OCR1A = i;
      //_delay_ms(5);
    }
  }
}

}

Majenko showed you one of your mistakes.

Then you wrote:

//Enable to interrupt Compare Match A
TIMSK1 = (1<<OCIE1A);

And this is your other mistake. You should not enable an interrupt
unless you have defined an ISR for it. Otherwise your program will
restart every time the interrupt fires.


Current Sensor ACS712 not changing its value even when connected bulb is lit My task is to find the amount of current a light bulb uses, with that motive I used ACS712 current sensor of 30A connected all the connections properly as shown in the circuit diagram below

I tried all different codes available to calculate current...
Arduino Code :
void setup(){
    Serial.begin(9600);
}

void loop(){
  int rVal = 0;
  int sampleDuration = 100;       // 100ms
  int sampleCount = 0;
  unsigned long rSquaredSum = 0;
  int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

  uint32_t startTime = millis();  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0) - rZero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
  double ampsRMS = voltRMS * 10.0;
  Serial.println(ampsRMS);
  Serial.println(analogRead(A0));
}

Output

The output remains the same, even when the bulb is still lighting up.
Thank You in advance :)

In a comment about rZero = 511;, you wrote:

For illustrative purposes only - should be measured to calibrate
sensor.

This may well be the cause of your problem. If, instead of 511, the
“zero” of your measurement is around 445, then you end up measuring a
non-existing DC current of about 3.23 A. When you turn on the light
bulb, you add roughly 435 mA (100 W / 230 V) of AC
current. The total RMS current you see is then:
√(3.232 + 0.4352) ≈ 3.26 A
Barely visible at the resolution at which you are printing the result.
And this is assuming you are using a 100 W bulb, as shown in the
diagram. These bulbs are getting hard to come by. If you are using
anything less powerful, you may not see any change in the displayed
value.
As a quick and dirty fix, you may replace 511 by 445. A better
solution would be to compute the quadratic average of the AC part of the
signal alone. In other words, compute:
√(average(current2) − average(current)2)


Servo Control using Pushbutton I was trying to build a system that when the user pushes the button, the servo rotates 45 degrees and than returns back to zero. This system is going to be duplicated as there will be two servos and pushbuttons.

Here's my code:

#include <Servo.h>
Servo solservo;  // create servo object to control a servo
Servo sagservo;
// twelve servo objects can be created on most boards

int possol = 0;    // variable to store the servo position
int possag = 0;
int degsol=0;
int degsag=0;

int ledPin = 13; // choose the pin for the LED
int solPin = 7;   // Pushbutton
int sagPin = 8;     // variable for reading the pin status
int valsag = 0;
int valsol = 0;

void setup() {
  solservo.attach(9);  // attaches the servo on pin 9 to the servo object
  sagservo.attach(10);
  pinMode(solPin, INPUT);
  pinMode(sagPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  digitalWrite(ledPin, HIGH);    //Arka İsik
  valsag = digitalRead(sagPin);  // read input value
  valsol = digitalRead(solPin);
//Sag Servo

  if (valsag == HIGH) {
    sagservo.write(45);              // tell servo to go to position in variable 'pos'
    delay(100);                       // waits 15ms for the servo to reach the position
    sagservo.write(-45);

  }
//Sol Servo
  if (valsol == HIGH){
    solservo.write(45);
    delay(15);
    solservo.write(0);
  }

}

There'll probably be lots of small errors in this code, like unnecessary ints and such, but when I upload this program and push the button, it just rotates 45 deg, and doesn't come back. Is there a way that I can solve it?

Thanks in advance

Change sagservo.write(-45); to sagservo.write(0);.


Read RFID Card Number in Processing over Serial I have successfully setup up a RFID reader with Arduino Uno and EM-18 Card Reader Module.

Its program for Arduino is below:

int count = 0; // count = 0

char input[12];                                         // character array of size 12

boolean flag = 0;                                       // flag =0

void setup()
{
   Serial.begin(9600);                                  // begin serial port with baud rate 9600bps
}

void loop()
{
   if(Serial.available())

{

count = 0;

while(Serial.available() && count < 12)          // Read 12 characters and store them in input array

{
input[count] = Serial.read();
count++;
delay(5);
}

//Serial.print("Card ID - ");

Serial.print(input);      // Print RFID tag number

}

}

But when try to read the code over serial in the program for locking/unlocking mouse in Processing the values of strings don't match.
Hence the mouse doesn't get unlocked.

The program for processing is as below:

import processing.serial.*;
import java.awt.AWTException;
import java.awt.Robot;

Robot robot;
boolean locked = false;
Serial port;
void setup()
{
  println(Serial.list()); //Prints available ports

  port = new Serial(this, Serial.list()[36], 9600); //Chooses the first available port
  try
  {
    robot = new Robot(); //Creates robot
  }
  catch (AWTException e)
  {
    e.printStackTrace();
  }
}

void draw()
{
  if (locked == true) robot.mouseMove(0, 0); //If locked, moves mouse to top left corner
  while (port.available() > 0)
  {
    String input = port.readString();
    //println(input);
    if (input.equals("11006F26DC84") == true) locked = false; //If it read my card it will unloack.
  }
}

void keyPressed ()
{
  if (key == 'l')
  {
    locked = true; //Locks it
  }

  if (key == 'u')
  {
    locked = false; //Unlocks it
  }

  if (key == ESC)
  {
    key = 0; //Disables escape as quit
  }
}

Please point the incorrect syntax and suggest correct one.

input has to be 13 characters in size; you forgot to include a byte for the null-terminator. Then right before Serial.print(input), you write input[12] = 0. Also the argument to string.equals() should be a String as well; you must write the statement like this: input.equals(String("11006F26DC84"));


trying to connect to WiFi on ESP32 using credentials from SD card Am trying to connect to Wi-Fi on an ESP32 using credentials i stored on an sd card, am able to read and parse the credential and printing it to the serial monitor shows that the ssid and password is correct but not connecting to Wi-Fi, when i hardcode the Wi-Fi credentials it works what could i be doing wrong

I use the NVS partition to store NON VOLATILE information.
I use this library: NVS library
You can save like string and restore after reset/off.
Example:
#include <Arduino.h>
#include "ArduinoNvs.h"

void setup() {
    NVS.begin();
    Serial.begin(115200);
    // write to flash
    String set_SSID = "WIFI_name";
    NVS.setString("nvs_wifi_name", set_SSID ); //upload 1 time. after comment this line and upload again **
    // read from flash
    String get_SSID = NVS.getString("nvs_wifi_name");
    Serial.printf("Wifi name stored %s\n", get_SSID);
}

void loop() {}


Arduino expected ')' before '{' token for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    Serial.print(mfrc522.uid.uidByte{i} < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte{i}, HEX);
    content.concat(String(mfrc522.uid.uidByte{i} < 0x10 ? " 0" : " "));
    content.concat(String(mfrc522.uid.uidByte{i}, HEX));
  }

I use this code to get UID of an RFID card, but the error "expected ')' before '{' token" comes out. Does anybody know how to solve this problem?

Welcome to this site, next time use ctrl-k to align your code.
The problem is in:
Serial.print(mfrc522.uid.uidByte{i} < 0x10 ? " 0" : " ");

To get the value of an array, use [i], not {i}, thus
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");

(similar to other lines).
To give some additional hints:

Try to prevent duplicated code by storing the byte into a variable. Now you can use uidValue in the subsequent lines.
uint8_t uidValue = mfrc522.uid.uidByte[i];

Store 0x10 inside a constant.

So you get:
const uint8_t MAX_HEX_SINGLE_DIGIT_VALUE 0x0F;

for (byte i = 0; i < mfrc522.uid.size; i++)
{
    uint8_t uid_byte = mfrc522.uid.uidByte[i];
    Serial.print(uid_byte < LOW_VALUE <= MAX_HEX_SINGLE_DIGIT_VALUE ? " 0" : " ");
    Serial.print(uid_byte, HEX);
    content.concat(String(uid_byte < MAX_HEX_SINGLE_DIGIT_VALUE ? " 0" : " "));
    content.concat(String((uid_byte, HEX));
  }

I assume the Serial lines are only for debugging, otherwise you can combine them too.


How to detect Genuino 101 from inside the code? I am using a custom library for Arduino Mega which uses AES library for AES-128 encryption.

However, when I try to use that library in Intel Genuino 101 development board, it shows compilation error which is because the assembly language written in AES library was compatible with Atmel devices only.

And my question is whether there is a way, my code can automatically detect the GENUINO board by writing some sort of signature verification of this board and hence I can exclude the encryption part if it can successfully detect GENUINO 101.

For any queries, feel free to bug me, thanks.

Arduino defines some macros so you can use conditional compilation. For example these are from boards.txt:

use ARDUINO_AVR_PROMICRO if it's specific for board variant
use ARDUINO_ARCH_AVR if it's specific for Arduino with AVR

Also avr-gcc defines macros according to cpu settings (this should be similar for other platforms too):

use __AVR_ATmega32U4__ if it's specific for only one MCU
use __AVR__ if it's compatible with all AVR based MCUs

And code examples:

#if defined(__AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__)
// something for ATmegaXX8 family...
#else
// ...
#endif

#ifdef __AVR__
// Code related to AVR
#else
// Code for other architectures
#endif

More about predefined macros in avr-gcc.


Why doesn't this work on a Mega2560 although it works on an Arduino Uno So, This is your code slightly altered. I am using it to read the readings of the roll and pitch of a quadcopter. I have tried using this code for a mega 2560 but it does not work in ports A0 and A1. I think it might in A5 and A6 but I am unsure how to alter this code.
THank you,
Rohan Paleja

/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */

#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[2]; // times of prev. rising edges
volatile unsigned long rcTimes[2]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter
int Roll, Pitch;
// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(9600);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[2]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    Roll = rcTimes[0];
    Pitch = rcTimes[1];

    sei();          // reenable interrupts

    Serial <<  " " << Roll << " " << Pitch
       << " "  << rcN << endl;

  }
  sei();            // reenable interrupts
  delay(1000);
}

You are trying to do an Pin Change Interrupt on Port F (A0-A7). On the arduino Uno, this port does support PCINT but not on the Arduino Mega.

An option is to use the Port K for the PCINT. Instead of A0 and A1 you then use A8 and A9. A few little changes in the code should do the job:

void setup_rcTiming() {
rcOld = 0;
pinMode(A8, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
pinMode(A9, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

PCMSK2 |= 0x0F;       // Four-bit mask for four channels
PCIFR  |= 0x04;       // clear pin-change interrupts if any
PCICR  |= 0x04;       // enable pin-change interrupts
}

and

ISR(PCINT2_vect) {
byte rcNew = PINK & 15;
...
}


Is my Arduino skipping a statement? So, I made this code (I'm rather new to this). The only thing that the Arduino should do, is when I press the button on pin 2, turn on the LED on pin 4 and emulate CTRL + R on the keyboard for the computer. Then, if the LED is on and I hit the button again, turn it off and hit the spacebar on my computer. But as soon as I hit the button for the first time, it does indeed press CTRL + R and the LED turns on, but after the delay, it immediately skips checking if I am pressing the button and assumes that I am pressing the button. Thereby it only sees that the LED is on and it turns it off while hitting the spacebar. Any suggestions?

#include <Keyboard.h>

int buttonPin = 2;
int ledPin    = 4;
int val = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  val = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if ((val == LOW) && (digitalRead(ledPin) == LOW)) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press('r');
    delay(100);
    Keyboard.release(KEY_LEFT_CTRL);
    Keyboard.release('r');
    delay(500);
  }
  if ((val == LOW) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, LOW);
    Keyboard.write(32);
  }
  if ((val == HIGH) && (digitalRead(ledPin) == LOW)) {
    digitalWrite(ledPin, LOW);
  }
  if ((val == HIGH) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, HIGH);
  }
}

Your code isn't checking for a button.  It's checking the value in val.  That only gets updated once per loop.  Let's say the code enters the first if statement because the val is LOW and the LED is also LOW.  This sets the LED to HIGH.  Now the next if statement, val is still LOW and now LED is HIGH so that one is true as well.

I think what you want is to use "else if" so it will skip the rest once it finds a true one.

void loop() {
  val = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if ((val == LOW) && (digitalRead(ledPin) == LOW)) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press('r');
    delay(100);
    Keyboard.release(KEY_LEFT_CTRL);
    Keyboard.release('r');
    delay(500);
  }
  else if ((val == LOW) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, LOW);
    Keyboard.write(32);
  }
  else if ((val == HIGH) && (digitalRead(ledPin) == LOW)) {
    digitalWrite(ledPin, LOW);
  }
  else if ((val == HIGH) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, HIGH);
  }
}


I'm using an Arduino and DS1307 for creating RTC but my code has some issue I'm not getting any errors but the values that are supposed be displayed in the RTC_read are not being displayed for some reason.Initially i thought this was maybe due to the code being caught somewhere in the loop but that's not the case. Strangely when i'm using Serial.print() of some value the entire value is not being displayed

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

void i2c_init()
{
  TWSR=0x00;
  TWBR=0x47;
  TWCR=(1<<TWEN);
}

void i2c_start()
{
  TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while(!(TWCR&(1<<TWINT)));
}

void i2c_end()
{
  TWCR=(1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
  while(!(TWCR&(1<<TWSTO)));
}

void i2c_write(uint8_t data)
{
  TWDR=data;
  TWCR=(1<<TWINT)|(1<<TWEN);
  while(!(TWCR&(1<<TWINT)));
}

uint8_t i2c_read(int ack_val)
{
  TWCR=(1<<TWINT)|(1<<TWEN)|(ack_val<<TWEA);
  while(!(TWCR&(1<<TWINT)));
  return TWDR;
}

void RTC_init()
{
  i2c_init();
  i2c_start();
  i2c_write(11010000);
  i2c_write(00000111);
  i2c_write(00000000);
  i2c_end();
}

void RTC_set_time_date(uint8_t second,uint8_t minute,uint8_t hour,uint8_t day,uint8_t month,uint8_t year)
{
  i2c_start();
  i2c_write(11010000);
  i2c_write(00000000);
  i2c_write(second);
  i2c_write(minute);
  i2c_write(hour);
  i2c_write(day);
  i2c_write(month);
  i2c_write(year);
  i2c_end();
}

void RTC_read()
{
  char second,minute,hour,day,month,year;
  i2c_start();
  i2c_write(11010000);
  i2c_write(00000000);
  i2c_end();

  i2c_start();
  i2c_write(11010001);
  second=i2c_read(1);
  minute=i2c_read(1);
  hour=i2c_read(1);
  day=i2c_read(1);
  month=i2c_read(1);
  year=i2c_read(0);
  i2c_end();
  Serial.println(second);
  Serial.println(minute);
  Serial.println(hour);
  Serial.println(day);
  Serial.println(month);
  Serial.println(year);
  Serial.println("Recieving data");
}

int main()
{
  Serial.begin(9600);
  uint8_t second,minute,hour,day,month,year;
  second=00000000;
  minute=01000000;
  hour=00100011;
  day=00000011;
  month=00000111;
  year=00011001;
  Serial.write("abcd");
  RTC_init();
  RTC_set_time_date(second,minute,hour,day,month,year);
  RTC_read();
  return 0;
}

Lets start with the order of the registers:

seconds  -- bit 7 is clock start/stop bit, 0 = enabled
minutes
hours    -- bit 6 is selector 12/24 hour,
         -- when in 12 hour, bit 5 is am/pm, 1=pm
         -- When in 24 hour, bit 5 indicates in hour 20...23
day      -- week day 1...7
date     -- day of month 1...31
         -- where the most significant nibble can contain the values
         -- 0, 1, 2, 3
         -- where the least significant nibble can contain the values
         -- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
month    -- 0x1x indicates in upper 10 months
year
control
<other ram>

When writing these registers, the prior time is transferred to a background/image of the main registers.

Of key importance is the 'ack' bit, which is 'echoed' at the end of each byte transferred.  Here are the details:

DS13077 of 12Acknowledge: Each  receiving  device,  when  addressed,  is  obliged  to  generate  an  acknowledge  after  the reception  of  each  byte.    The  master  device  must  generate  an  extra  clock  pulse  which  is  associated  with this acknowledge bit.A device that acknowledges must pull down the SDA line during the acknowledge clock pulse in such away that the SDA line is stable LOW during the HIGH period of the acknowledge related clock pulse.  Of course, setup and hold times must be taken into account.  A master must signal an end of data to the slave by not generating an acknowledge bit on the last byte that has been clocked out of the slave.  In this case,the slave must leave the data line HIGH to enable the master to generate the STOP condition

so the first problem I see is the code sequence does not match the register sequence.  This is an error.

the second problem I see is the ACK bit is being set to the wrong value


read state from button to check if clicked I"m kinda new here and new to the arduino framework.

I want to build a "menu" using LCD 20*4, so I want to detect "button clicked" event.

I've connected button to pin 8 and to ground, like this(please ignore the other wiring):

int leftButton = 8;

void setup() {
  pinMode(leftButton, INPUT);
  digitalWrite(leftButton, HIGH);
  Serial.begin(9600);

}
bool leftButtonClicked(){
  return digitalRead(leftButton);
}
void loop(){
  delay(20);
  Serial.println(digitalRead(leftButton));
}

I am receiveing on the serial 1 while the button is not clicked, and when its clicked I receive 0.

What is the problem? Thank you guys.

As you are a beginner, you seem to have some misconceptions:

Reading button state with digitalRead(): You thought something is wrong, because you thought that digitalRead() returns, if the button was pressed (thus 1 would mean pressed). But that is not directly the case. digitalRead() returns the electrical state of the corresponding pin (if the pin voltage is at ground level (0) or Vcc (supply voltage) level) (1)). This corresponds with the button depending on your wiring. I guess you copied the wiring somewhere in the internet. It shows the most common way of connecting a button. The button consists only of two contacts, which get pressed together, when you press the button. So the button can connect the pin to either ground or Vcc, but not to both. When the button is not pressed, the pin is connected to nothing, thus it is floating and the value changes erratically. This is solved with a pullup or pulldown resistor (a rather big resistor from the pin to either Vcc or ground), which sets the value of the pin, when the button is not pressed. That means, that you need 1 resistor for each button, that you want to use. The good news is: The Arduino already has internal pullup resistors, that you can activate via pinMode(pin, INPUT_PULLUP). That way you can save 1 extra component. Since it is a pullup resistor, which connects the pin with Vcc, you need to connect the button with ground.

That also gives you the inverted logic. In the end it is determined by you, what the digitalRead() value means. Think electrically about it.
Events: In Arduino programming there are not events. You are programming very much directly the hardware. There is no OS or GUI system, that would handle events for you. The program, that you write, runs command after command with a specific speed (determined by the Arduinos clock frequency; 16MHz for the Uno), pretty much linearly. Though there is one exception for that: interrupts. Microcontrollers have some peripherals build into them (ADC, communication interfaces, Timers, ...) and many of them work parallel to the main program (since their function does not need code, but is implemented in hardware). These peripherals can generate interrupts (for example to service the peripheral), which pauses the normal run of the program, runs an ISR (Interrupt Service Routine) and then returns to the main program. That is somewhat like an event, but very hardware specific and not nearly as generically usable as events on a PC.
Reading a button click: In your code you don't read the "button click", but only the state of the button. Thus you get multiple times 0 for one long enough button press. For the real click action you need to look for the transition from 1 to 0, which ideally only happens one time per button press. I write "ideally", because real life buttons bounce. In the moment of contact the value changes rapidly multiple times, until the button contacts have settled. So you need to debounce the button. You have already done basic debouncing by using delay(20) (because the button may need about that time to stabilize). You can see more sophisticated debouncing in the Bounce2 library, which is also easy to use for reading button clicks and presses.


How do I start a task and have it run for a set amount of time? I have a project where I need to turn a 24V solenoid on for a set amount of time, then have it turn off. I am rather new to Arduino and not certain how to do this or really where to start. Ideally the time would be displayed on a LCD screen as well but this is purely aesthetic. Any advice, help, examples ect would be appreciated. Thanks!

Use millis();

Record millis() in a long variable like below when the solenoid starts
StartTime = millis();

to switch off solenoid after 60 seconds you may do

if ( (millis() - StartTime)/1000 ) >  60
{
   // switch off solenoid
}

enjoy coding.

There are other ways as well to achieve this... but this is being easiest  and you don't have to wait caused by using delay();


How can I connect more sensors when my lcd is blocking pin access? So, I have a lcd that takes up the whole board of an arduino mega. I want to connect a temperature sensor and make a really lame weather station, but the lcd screen is totally in the road. It's a shield so this is to be expected.

I've come up with wacky ideas, like soldering to the rear of the board but I think that's a bad idea. Surely there must be a better way? The lcd shield exposes no pins.

What you need is a shield that can go between the Arduino and the LCD shield and break out whatever connections you like.

They are generally available as "screw terminal" shields, such as this one from iTead:

http://www.itead.cc/mega-proto-screw-shield.html


Problem with code for IR remote controlled robot I recently wrote the code for this project but it's weird because when I press button on the remote nothing shows up on the Serial Monitor and consequently the robot doesn't respond. I know it's not a hardware issue because when I used the IRrecv Demo sketch values were displayed on the serial monitor

Please tell me what's wrong! I'm sure there are a lot of talented programmers out there!!

#include <IRremote.h>
#include <AFMotor.h>
AF_DCMotor rightMotor(1); // Right motor connected to port 1
AF_DCMotor leftMotor(2); // Left motor connected to port 2
IRrecv irrecv(A2);// IR receiver connected to pin A2(ANALOG PINS ON MOTOR             SHIELD USED AS DIGITAL INS!)
decode_results results;
#define Straight 0xC1CC42BD
#define Right 0xC1CCA25D
#define Left 0xC1CC22DD
#define Back 0xC1CCC23D

void setup(){
  Serial.begin(9600); // Establishing Serial Communication, THIS IS     IMPORTANT!!
  irrecv.enableIRIn(); // Start the receiver
}
void loop() {
  if (irrecv.decode(&results))
  {
      Serial.println(results.value, HEX);

      if((results.value)== Straight)
      {
      moveForward();
      }
      if((results.value)== Right)
      {
        turnRight();
       }
      if((results.value)== Left)
      {
        turnLeft();
      }
      if((results.value)== Back)
      {
        moveBackward();
      }
      else
      {
        Stop();
      }
      irrecv.resume();
  }
  delay(100);
}

void moveForward() {

    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
}

void turnRight(){

  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(FORWARD);
  rightMotor.run(BACKWARD);
  delay(400);

  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void turnLeft() {

  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(BACKWARD);
  rightMotor.run(FORWARD);
  delay(400);

  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}
void moveBackward() {

    leftMotor.setSpeed(200);
    rightMotor.setSpeed(200);
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
}

void Stop(){
    leftMotor.setSpeed(0);
    rightMotor.setSpeed(0);

}

Try replacing you loop function with this one.  It won't fix it.

void loop()
{
    if (irrecv.decode(&results))
    {
        Serial.println(results.value, HEX);

        switch (results.value)
        {
        case Straight:
            moveForward();
            break;
        case Right:
            turnRight();
            break;
        case Left:
            turnLeft();
            break;
        case Back:
            moveBackward();
            break;
        default:
            Stop();
        }
        irrecv.resume();
    }
    else
    {
        Serial.println ("Nothing received");    // This message will annoy you so comment it out as soon as you are happy with what is happening.
    delay(100);
}

The switch statement is just a neater way of doing your ifs.  The Nothing received message will show you if decode is ever returning.  If it is returning you need to work out why it is returning false, by looking in the library code.  If it isn't returning then you need to look in the library code and see why.  If it is returning, but not giving you an expected value, you need to look in the library code and see why.

Sorry but from what you describe it seems to be an issue with the library or your use of it, could be anything, but when you can get some more info post it back here.


Oil Pressure / Water Pressure / Boost Pressure ( Turbo Engine ) I'm an automotive enthusiast and I want to build some gauges by myself using Arduino.

I was taking a look at this pressure transducer or sender, 100 psi, stainless steel, for oil, fuel, air, water and I was thinking if I can use this sensor to do all of the these tasks: Water, Boost and Oil Pressure.

Look at the Signal output vs read PSI chart of the sensor

I came out with this equation for the PSI calculation:

Since it is a Y = bx + a, where:

a = 0.5
b = y2 - y1 / x2 - x1 = (4.5 - 0.5 ) / (100 - 0) = 4/100 = 0.04
x = PSI
y = Signal's Voltage

This means that

Voltage Reading = 0.04PSI + 0.5

So we have :

PSI = (Voltage Reading - 0.5 ) / 0.04

Am I correct? Can I use this sensor?

You math checks you to me.

When you code it, You will probably read a voltage using an analog pin (or external ADC) that will return an integer between 0 being 0 volts, and 1024 = vin volts. vin will be 5 if you don't wire up the vin pin, and 1024 could be different if you use an external ADC.

Anyway you should be aware that the raw readings will probably not be 0-5, and they dont have decimal points. You will need to first convert the reading into the voltage with something like this:

float voltage = ((float)reading)/1024.f;

notice that the datatype float is used (enables decimal points) and that the constant being divided by is also a float so that the calculations will definitly happen between floating point numbers.


How to power Arduino pro mini and DFPlayer mini togather with 3.7 V LiPo battery? I made a small box containing Arduino Pro Mini , DFPlayer Mini player and a 3.7V LiPo battery. Is it possible to power two devices with 3.7 V Battery?
What is the best way to save power for longer time performance?

Use a buck/boost voltage regulator. Those are high efficiency switching regulators, and can either increase or decrease the input voltage. Feed the output of the regulator directly into the Arudino's 5V (or 3.3V) line, bypassing the on-board voltage regulator.
What input voltages do the 2 devices need? Both 5V? If so, you can use a single voltage regulator to power both devices. If one needs 3.3V and the other needs 5V you may have to have 2 different voltage regulators.
By using a switching regulator you can bypass the fairly inefficient linear regulator in your Arduino supply 3.3V or 5V to it directly (depending on the type of board you have.)
Edit:
Ok, I looked it up and a DFPlayer Mini player appears to be a shield designed to plug directly into an Arduino. It looks like it can be powered from 3.2 to 5V, so you should be able to use it with either a 3.3V or 5V Arduino Pro Mini. Once you've decided if you're going to use a 3.3V or 5V Arduino, pick a buck/boost voltage regulator with the desired output voltage (or get an adjustable one and set it appropriately.)


Converting uint8_t to String - unexpected result I'm working on a remote control code for ESP controller. Using ESPwebserver and Fastled. When I try to return a value of an uint8_t, as a POST response, i got strange result here is the relevant code:

uint8_t PaletteBrightness = 255;

server.on("/Sync", HTTP_POST, []() {
String Sync = "PaletteBrightness:" + PaletteBrightness;
    Sync += ":end";
    Serial.println(Sync);
    server.send(200, "text/plain", Sync);
  });

The code complies, and runs fine but the result of 'Sync' in both serial, and POST response is:

Phase:end

Why? What does even Phase mean?
What I want is:

PaletteBrightness:255:end

Where the 255 is the value of 'uint8_t PaletteBrightness' Also, there will be more values, to add the 'Sync' string. Just trying to get one right.

You should convert your number uint8_t into it's ASCII representation before appending it to your string, otherwise you are appending just one character using it's byte representation.

To do so you can use a standard function itoa() which has a decent documentation available here.

So change line

 String Sync = "PaletteBrightness:" + PaletteBrightness;

into

 char buffer [4];
 String Sync = "PaletteBrightness:" + itoa(PaletteBrightness, buffer, 10);


How to reset an arduino while being able to know which button has been pressed? Context

I keep the board in sleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot.

In the following schematic, SW-R is actually used to reset the board.

If I hold SW-D5 or SW-D6 while pushing SW-R, the code can detect which button I pushed.

Problem

I don't want to have to push 2 buttons at the same time and, being new to electronic, I don't know how to wires things up so it reset and set a pin to HIGH simultaneously.

Question

How can I reset the board and trigger a HIGH on an IO corresponding to a button while it boot?

Considering the HIGH only need to be hold for less than a second, can it be simply achieved with capacitors and/or transistors? If so, how? Or any other suggestion?

simulate this circuit – Schematic created using CircuitLab

The actual code example only contain 1 button but I'll have many.

#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);

  int buttonValueAtBoot = digitalRead(buttonPin);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == HIGH) {
    // I want to trigger this code pushing only 1 button
    // should also work with many buttons
    Serial.println("button was pressed");
  }

  digitalWrite(BUILTIN_LED, HIGH);
}

void loop() {
  delay(5000);
  ESP.deepSleep(0);
}

Just found that I can change pins behavior. Inverting things a little bit, I can get my pins to work as LOW instead of as HIGH.

That way, I only need 1 button to trigger a reset and change pin status. Plus, grounding the reset is done temporarily because of the capacitor, which is what I need.

Here is the new schema

simulate this circuit – Schematic created using CircuitLab

New code

#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(BUILTIN_LED, OUTPUT);

  int buttonValueAtBoot = digitalRead(buttonPin);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == LOW) {
    Serial.println("button was pressed");
    digitalWrite(BUILTIN_LED, HIGH);
  }

  // Avoid problem when the button is hold
  while (digitalRead(buttonPin) == LOW) {
    // wait before going to deepsleep
    // or the capacitor will be drained
    delay(1);
  }

  Serial.println("going to sleep");
  ESP.deepSleep(0);
}

void loop() {
}


what the benefit uploading hex file merely to arduino board? What the benefit of uploading merely hex file to avr based board like arduino uno Since the arduino ide it self will send intel hex file to the board after compile .ino file to hex file by the avrdude compiler (https://github.com/arduino/Arduino/wiki/Build-Process)?

If you want to upload the same sketch to many  Arduinos compiling it again and again would take much longer. Or if you create a firmware ànd don't want to disclose the source code, you can distribute it in compiled form.


Assuring an unsigned long int? Basic question: How far do I have to go to assure that integer math is done correctly? For example, this is probably overdone:

unsigned long burnTime = 0UL;
unsigned long curBurnTime = 0UL;
// Do some stuff that sets the above variables to millis() at various times
// Later on...
unsigned long adjustedBurnTime = (unsigned long) ((burnTime + curBurnTime) / 1000UL);

Would the math be done correctly if I went to a more minimal last statement (since all the elements of the equation are unsigned longs)? Like this:

unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000UL);

Or even:

unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000);

Any good C manual will tell you the result type for each basic math operation on given types. But briefly, the basic math operators return a result as wide as the widest operand, with the narrower operand being widened to match the wider one, if they differ. The same with assignment: assigning a result of a given type to a variable of the same type will not involve any conversion.

tl;dr: No, you're not missing anything. You don't need any casts in your example.

PS: One thing you do need to be aware of is whether any of your intermediate results will overflow the arithmetic type you're using. For example, the final result may be not exceed an unsigned long but the expressions (burnTime + curBurnTime) must also not exceed it. This is a greater concern with smaller data-types, of course.

PPS: Good on you for tackling fixed point arithmetic rather than just reaching for the floating-point library!


Addressable RGB LED Strip I am looking to create an addressable RGB LED strip circuit with my NodeMCU v3 Wi-Fi. I am looking at a strip of 150 RGB LEDs, 5 meters long, so 30 LED/m. But I am only going to use about 50 LEDs for the backlight on my desk. My understanding is that if each RGB LED pulls 60 mA on full white, and I'm running 50 LEDs, then I will need at least 60 mA x 50 LEDs = 3000 ms (3 A) of power to sufficiently light all of them. I am thinking about upgrading this in the future, and so I am thinking about going with a 5V 10A power supply. Am I okay to go with a 5 V 10 A power supply? Or will this be too much current for the system.

Each will only draw as much current as they normally would from a 5 volt supply. If you had a 5 volt 100 amp supply they still would not draw any more.

The amount of excess current a power supply can deliver doesn't change what the load will take from that supply.

For example, if you had a 5 volt supply with a 1 ohm resistor as a load the current would be 5 amps. 5 volts / 1 ohm = 5 amps. And if you had a 5 volt 10 amp supply the current would still be 5 amps. Same with a 20 amp supply. As long as the voltage is the same, going up in current capacity is safe.

(LEDs are not resistors but with this application it is much the same)

When you do wire up the LED strips make sure you are using thick enough wires.


Updating MAX7456 library to work with Arduino 1.6.6 I've got this library for communicating with the MAX7456 chip.

The library is abandoned and the only one I found that actually works, so I'd really like to use it.

It compiles fine with Arduino IDE 1.0.5, but not with Arduino IDE 1.6.6 .

This happens with 1.6.6, I tried to fix it but I only made it worse.

Arduino: 1.6.6 Hourly Build 2015/07/03 10:26 (Linux), Board: "Arduino Nano, ATmega328"

Using library SPI at version 1.0.0 in folder: /home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI
Using library max7456 in folder: /home/t/Dropbox/Arduino/libraries/max7456 (legacy)

/home/t/Dropbox/Arduino-IDE/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/cores/arduino -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/variants/eightanaloginputs -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI -I/home/t/Dropbox/Arduino/libraries/max7456 /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp -o /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp.o
In file included from HelloWorld.ino:2:0:
/home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:40: error: 'prog_uchar' does not name a type
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
                                    ^
/home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:52: error: ISO C++ forbids declaration of 'table' with no type [-fpermissive]
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
                                                ^
Error compiling.

How would one make the library compatible with 1.6.6?

In the file max7456.h at line 228 change it from:

static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);

to:

static void getCARACFromProgMem(const char *table, byte i,charact c);

In the file max7456.cpp at line 484 change it from:

void Max7456::getCARACFromProgMem(const prog_uchar *table, byte i, charact car)

to:

void Max7456::getCARACFromProgMem(const char *table, byte i, charact car)

Then it compiles OK (under 1.6.4 at least).


Programmer only uploading with its own power source Can anyone explain to me why the following occurs (See image below)?

When I connect the pins according to situation 1, everything works fine and I am able to upload my project. However when I connect the pins according to situation 2 it gives me the following error:

  wrong direction/command: 0x00 0x08, expected 0x01 0x08 esp8266

Both supply the same constant 3.3V and after the project is uploaded it runs with the pins connected as in both scenarios.

(All the other factors are constant in both scenarios. Think of pulling down IO0 etc.)

There's no problem with supplying a separate power supply to the ESP8266 but you always need to connect the grounds between the "programmer" and the ESP8266.


"void does not name a type" Hi I'm new at this and can't figure out why I get this error "void does not name a type" on lines 3,5,8,26

// _2-5 set Debounce Button
const int BUTTON=2;
const int LED=9;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

Void setup()
{
  pinMode (LED, OUTPUT);
  pinMode (BUTTON, INPUT);
}

boolean debounce(boolean last)

{
  boolean current = digitalRead(BUTTON);
  if (last != current)
  {
    delay(5);
    current = digitalRead(BUTTON);
  }
  return current;
}

Void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledOn = !ledOn;
  }

  lastButton = currentButton;
  digitalWrite(LED, ledOn);

}

I thing the problem is not "void does not name a type", but "Void does not name a type".  Subtle difference:

Void setup()

should read:

void setup()

The same on

Void loop()

should be

void loop()

Watch those caps - C is case sensitive.


Problems powering standalone arduino with USB powerbank I've successfully migrated and ATMEL328P-UP microcontroller from the Arduino Uno Board to a breaboard, following these instructions: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard. Everything is OK, the bootloader worked and code is already uploaded an running.

The ATMEL is connected to a pair of sensors, and all the system works using 3.3V. And here comes the problem: I'm using a 5V USB power bank to power up everything. When I make this connection:

USB Power Bank @ 5V -> Arduino Uno board (without the microcontroller) -> 3.3 V Output from the board -> ATMEL/Sensors on the breadboard

everything works just fine! Now I decided to replace the Arduino uno board with an LM317 voltage regulator which gives me the 3.3V needed. The connection is this:

USB Power Bank @ 5V -> LM317 with 3.3 V output -> ATMEL/Sensors on the breadboard

and nothing happens! Is as if there wasn't enough current to feed the ATMEL nor the sensors. I've checked the Vcc/GND pins of the sensors and the ATMEL and they're all getting the required 3.3 V, but for some reason the system seems to be OFF.

What could be happening? I'm sure the USB power bank is at full charge, so it should be able to supply enough current. Any suggestions?

Thanks guys!

According to the datasheet, the LM317 needs an input voltage 3v higher than the output. Since 6.3<5, there's not enough margin for the LM317.

You can use an AMS117 LDO @3.3, which only needs an input of 3.9v to operate. I find these modules very handy. If the MCU has some tolerances, you can likely get away with using a diode or two in series with the 5v rail to drop it down; the actual forward voltage fluctuates slightly on load, but it will likely stay in the acceptable range for your MCU.

you can also use a switch-mode regulator, commonly sold as "buck converters" on ebay, to more efficiently reduce the voltage. This is the way to go over linear regulator like the 317 if you power your project from batteries or have concerns about heat. I go through a lot of these style converters, and they seem to work very well.


How do I install the firmware on an Arduino Mega clone? I have a brand new board which is a clone of the Mega2560.  I need to install the USB firmware on the 16U2 and the bootloader on the 2650 chip.  I have Atmel Studio and a JTAGICE-3. Using those, I can download HEX files compiled with the Arduino  IDE, and they run successfully.

But I'm having trouble finding Mega-specific instructions for getting the firmware installed so that I can use the Arduino ISP protocol for downloading new sketches. I can find much more information about the Uno than the Mega. And much of the information I do find seems to be dated.

1) Which are the right files to download?
   I've tried to install the 'MEGA-dfu_and_usbserial_combined.hex' to the 16U2 and the 'stk500boot_v2_mega2560.hex' to the 2560.

But the IDE won't connect via AVR ISP, and I get no serial communications from a serial sample sketch downloaded with the ICE.

2) What are the correct Fuse settings after I flash those files?

3) Is there a good way to confirm that the 16U2  USB converter is working correctly in isolation from the 2560 chip?

Let focus on one thing at a time, that is flashing the 16u2. You can see if you've successfully done that when you can see the Arduino in your device-manager.

First of, MEGA-dfu_and_usbserial_combined.hex is, as stated on the github page, for the 8u2, not the 16u2. Since you already have a ISP programmer you don't need the dfu functionality.  You can just flash the precompiled Arduino-usbserial-atmega16u2-Mega2560-Rev3.hex file.

The fuses can also be found in the readme.txt on github: -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m. I don't see any difference in the fuses between the 8u2 and 16u2, so they should work for the 16u2 too.

Hope this helps.


Arduino Uno, BLE Bluetooth Shield and Braccio Arm Shield I'm running the Uno board and want to connect the BLE Bluetooth shield (http://redbearlab.com/bleshield/) to control the Braccio Arm I have.

When I sit the Braccio Arm Shield on the Uno everything works - I can control the Arm.

When I sit the Bluetooth Shield on the Uno, everything works I can find the device and connect to it using the IOS App.

When I sit all 3 together, I can still control the arm but can no longer find the Bluetooth device.

Any ideas as to why this is?

Be aware that the BLE Shield is using  a SPI interface therefore on Arduino Uno the SPI bus uses pins 10 (SS), 11 (MOSI), 12 (MISO), and 13 (SCK) and the Nordic’s ACI requires two hand-shake signals, RDYN and REQN, two additional pins will be used (pins 8 & 9 in the default settings), from BLEshield
Therefore the BLE shield uses 6 pins e the Braccio uses almost all Arduino Uno pins.
Conclusion, you probably can't have both shields together as the Arduino Uno hasn't enough pins.

You can try an Arduino MEGA and adapt the shields connections wiring them together using different pins for the Braccio interface for example


SD Initialization Failing I am using a SEEED SD Card Shield. Everytime I attempt to write the card, I get

When Using File> Examples> SD > CardInfo:

initialization failed. Things to check:
* is a card is inserted?
* Is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

Or when using File>Examples> SD> Files:

Initializing SD card...initialization failed!

I even tried SdFat (IDE couldn't find anything), the "SD Library" by Adafruit (No change), and other things.

I'm using a Funduino MEGA 2560. Could that be the problem?!

I also use a Seeed Studio SD Shield, and used to have the same problem. To rectify this I have to insert the SD card into my PC and Format it. This almost always helped. If you have a card that has too large of storage, the Arduino will take too much time to check the full memory for information stored on it (initialize). Some SD card readers require a card of 2 gigabytes or less to work. Check the Data Sheet for this limit (if there is one). That should do it for you.


How to call multiple delayed functions using a single millis() I am working in a project where I need to call more than 1 functions actually 4 functions using a single millis()
Here is the code below.
 unsigned long then = 0;

 void loop(){

     unsigned long now = millis();

     if(now-then >=0){

         Serial.println("Function 1 called");

     }else if(now-then>=2000){

         Serial.println("Function 2 called");

     }else if(now-then>=4000){

         Serial.println("Function 3 called");

     }else if(now-then>=6000){

        Serial.println("Function 4 called");

         Serial.println("The end");

         then = now;
     }
 }

All the functions above gets run successfully but not in a proper sequence.
The running sequence of the functions seem to be very improper and random.
The 'function 1' gets executed in a proper sequence and timing but rest of the others are making a messy output.
How can I fix it please?
Thanks.

The current structure with multiple if statements and on timestamp variable does only work, if you also check for millis()-then being smaller than the next interval. Otherwise the first if statement will always be executed.
I think it gets easier, when you use only one if statement, but put the intervals in an array. In that if statement you can either use a switch statement to execute the code for the corresponding interval, or use a function pointer. Somewhat like this (untested):
unsigned long then = 0;
unsigned long intervals[4] = {0, 2000, 4000, 6000};
int current_interval_index = 0;

...

void loop(){
    unsigned long now = millis();
    if(now-then >= intervals[current_interval_index]){
        switch(current_interval_index){
            case 0:
                Serial.println("Function 1");
                break;
            case 1:
                Serial.println("Function 2");
                break;
            case 2:
                Serial.println("Function 3");
                break;
            case 3:
                Serial.println("Function 4");
                break;
        }
    then = now;
    current_interval_index = (current_interval_index + 1) % 4; // increment index and wrap it back to zero, if it goes to 4
    }
}

That way you can easily extent for more functions and the intervals are conveniently managed in an array. Note, that the intervals add up here. So function 4 executes after 2s+3s+6s = 11s.


Button debounce using millis() in this example I have been trying to find a way to use millis() instead of delay(), in order to press 2 buttons to turn on and off a blue led.

EDITED:

const int right_button = 8, left_button = 9, yellow_led = 7, blue_led = 6, green_led = 5, red_led = 4;
int previous_left_button_status = LOW, previous_right_button_status = LOW, blue_status = LOW, green_status = LOW;
unsigned long time_setup = millis();
const int delay_task = 250;

void setup()
{
  pinMode(right_button, INPUT_PULLUP);
  pinMode(left_button, INPUT_PULLUP);
  pinMode(blue_led, OUTPUT);
  pinMode(green_led, OUTPUT);
  pinMode(red_led, OUTPUT);
  pinMode(yellow_led, OUTPUT);
  Display.clear();
}

void loop()
{
  int right_button_status = digitalRead(right_button);
  int left_button_status = digitalRead(left_button);
  unsigned long time_passes = millis();
  if (time_passes - time_setup >= delay_task)
  {
    time_setup = time_passes;
    if (right_button_status == previous_right_button_status)
    {
      green_status = !green_status;
      digitalWrite(green_led, green_status);
    }
  }
}

You've declared the variable for the millis function inside your loop correct and you've declared the delay duration you want to use. Two things you've missed are you've declared 2 variables with the millis function and to use it to control the program flow based on some condition to execute some code, in your case, to press 2 buttons to turn on and off an LED.

The way to to this is to use an if-else statement inside the loop function with one variable declared with the millis function, delay_duration as your reference, and 1 variable declared with a zero value.

unsigned long storeMillis = 0;
const int delay_duration = 500;

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

void loop() {
unsigned long currentMillis = millis();
if (currentMillis - storeMillis > 500) {
storeMillis = currentMillis; //update and store the value of storeMillis for the next iteration
//code you want to do
}


Variables displayed incorrectly I am making a keypad and when I try to save the buttons that were pushed they reset back to zero.

int tmp = 1;
int digit = 1;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int code = 0;

void setup() {
  Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  if (digit > 4) {
    digit = 1;
  }
  for (int i = 2; i <= 7; i++) {
    int tmp = digitalRead(i);
    if (tmp == HIGH) {
      if (digit == 1) {
        int a = i - 1;
      }
      if (digit == 2) {
        int b = i - 1;
      }
      if (digit == 3) {
        int c = i - 1;
      }
      if (digit == 4) {
        int d = i - 1;
        Serial.print(a);
        Serial.print(b);
        Serial.print(c);
        Serial.print(d);
        digitalWrite(8, HIGH);
      }
      digitalWrite(9, HIGH);
      delay(100);
      digitalWrite(9, LOW);
      delay(100);
      Serial.print(i);
      digit++;
    }
  }
}

Do you know what int a; does?

For example you have a global variable a and then you have local a. Local one hides global one.

In all cases you're changing local variables. Then you're printing global a,b,c and local d.


How can I see the mySerial.print( ) through the serialmonitor on IDE? I made an object named "mySerial" like this.

SoftwareSerial mySerial(2,3) //pin 2 = RX, pin 3 = TX

also I made pin 13 periodically(0.5 seconds) blink(HIGH/LOW),
then the signal from pin 13 goes directly to pin 2 and pin 0(basic RX pin of UNO). I connected pin 0,2,13 directly with jumper wire.

and in the setup(), I wrote

Serial.begin(9600);

mySerial.begin(9600);

and in the loop(), I wrote

digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);

if(mySerial.available()){
    mySerial.println("mySerial!");
}
if(Serial.available()){
    Serial.println("Serial!");
}

when I compile this code and operate arduino,
I can only see the "Serial!" on the serialmonitor.
I think this means that the pin 0 can recognize the signal but the pin 2 cant'
How can I solve this problem?

I can't find what I've missed. Please help me guys!

Not the most scientific of approaches, and fundamentally flawed at any rate.

You've toggled the input twice over the period of one second, hardly an emulation of any serial port transmission and so one is letting you know there's been a change of state, the other is letting you know that it hasn't received any valid data.

In any case, when you attempt to read the port both will/should correctly give you nothing as a result because there was never anything there to begin with, nor is there anything coming in at the time.

If you want to test serial port comms like this, you are going to have to make a sketch for each scenario and use a real device to test it (like your actual serial port thru the Arduino IDE). Run some test, print the results and upload your second sketch and do it again.

You could even get a bit fancy and have a bit of fun with this and send a command to the arduino to turn off one serial port and turn the other one on, but that's got nothing to do with what you asked, so I won't be writing the code for that here ;)


Arduino nano / uno analog pin I'm working on a project where I need 7 analog pins.
I read the datasheet of Ardnuino Uno : 6 analog pins available.
So I decided to use an arduino mega with 16 analog pin available.
Then I saw the arduino nano had 8 analog pins.
But when I read the datasheet, both arduino uno and nano use Atmega328
In my final project, I will not use the board but only the pdip chip (analog pins are from pin number 23 to 28).
Is it possible to "convert" another pin of the pdip to be an analog pin ?

Thank you

No, this is not possible. The datasheet of the ATmega328P
states it has:

  8-channel 10-bit ADC in TQFP and QFN/MLF package
  6-channel 10-bit ADC in PDIP Package

If you want to use a bare chip, it won't be possible with a PDIP
package.


Setup of Arduino Uno as ArduinoISP for programming attiny45 I have an Arduino Uno SMD and an attiny45, which I want to use as a sensor communicating via i2c. For a first step in finding out how to work with the attiny45 I just want to use the attiny as controller for a blinking led.
When first setting up the Arduino as "Arduino as ISP" some questions came up:

I found a lot of different information about wheter or not to use a capacitor between RESET and GND on the Arduino. Also the capacity differs between 0.1uF and 10uF. Unfornately, I found not a single comment on why this capacitor is needed (or not) and which capacities are suitable. All tutorials used electrolytic capacitors (which I only have in 100uF at hand). I have 10nF and 0.1uF at hand but only the film capacitor type. It would be brilliant if some could help me with deciding if I should use a capacitor, which one is suitable and what's the reason for using it.

My second question is about the clock rate I should set in the Arduino IDE. I added the board package from https://github.com/SpenceKonde/ATTinyCore to my Arduino IDE, which offers a large variety of clock rates in the tools dropdown menu. In some tutorials they mentioned that it's crucial to pick the correct clock speed to avoid wrecking the attiny. But, unfortunately, the mentioned clock speeds vary between "1 MHz (internal)" and "8 MHz (internal)". In the attiny45 datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf) I found the "Calibrated Internal Oscillator" to be the clock set up in freshly shipped chips, which I understand to operate at 8 MHz. But, the datasheet also says, that the CKDIV8 fuse is set on shipment, which leads to a clock prescale value of 8 and to a clock rate of 1 MHz. I'm highly confused... Maybe someone here can help me to find the correct clock rate to set.

I hope I didn't forget any important information. If so, please let me know.
Kind regards and thank you in advance,
Matthias

The capacitor is meant to prevent the programming Arduino from being reset. Normally, when you open the serial connection, the Arduino gets reset and first starts into the bootloader (which would be used to program it). But when using the Arduino as ISP programmer, you don't want to run the bootloader of the programmer. You want to let the programmer sketch work as intended. Thus you want to prevent the programmer from resetting on serial connection. The capacitor between Reset and ground holds the 5V level of the reset pin for the time, that the reset pulse from the USB Serial chip is trying to pull the pin to low. So it prevents the reset from happening.
The value and type of the capacitor is not critical here. I always use a 47uF bipolar electrolyte capacitor, because I have a bunch of them just laying around. The value just shouldn't be unreasonable small or big. The mentioned range of yours is just giving you a hint in which order the value should be. Also you can simply test, if the reset happens with your capacitor. You cannot break things with a wrong value here.

Which clock frequency to use is up to your exact requirements. There is no "this is the best for all occasions"-frequency. Also you are not wrecking the Attiny with any of the clock speeds. Though you should note, that choosing an external clock source means, that you actually need to provide that clock source for the ATTiny to work. The fuses can be reprogrammed, if you have chosen a wrong frequency by accident.
The datasheet states just as you wrote. The interal oscillator is by default set to 8MHz, while the prescaler divides that down to 1MHz as the main CPU clock. So by default the ATTiny runs on 1MHz. You can change that, if you like.
For my Attiny85s I always used internal 8MHz as the setting (the option, that appears in the IDE menu). That is the easiest way (internal means you need no external components for the clock), while being the fastest speed you can get with the internal clock, I think.


Is it possible for Arduino firmware to recognise only one computer? Is it possible to adjust the Arduino firmware to recognise only one PC computer? On other computers it would show driver not recognised or driver not found.

E.g.: My computer should see the Arduino normally, and it should not work if I connect the same arduino to other computers.

No.

However, it is possible to place unusual and/or secret requirements on the computer's drivers or application software - however those software components could be present on multiple computers unless you also take measures to node lock them.

You could customize the USB VID/PID and descriptors, causing the device not to be recognized by a usual driver
You could alter the behavior of the USB interface (or bootloader and sketch) to require unusual operations - either obscure, or even secret to the level of unique-per-unit cryptography
Or most simply, you could just use a board without a USB interface and bring your own.  Especially if you lock the flash, there's not a whole lot others can do except entirely erase your work and be left with an unusually expensive ATmega evaluation board.

Do note also that most operating systems make it possible to easily intercept the raw USB traffic going to/from devices, so someone who can see it in operation can learn a lot about how it is working.

If you want to play games with odd USB implementations, you'll probably do better with a direct USB board like a Leonardo - and you will certainly want to have an ISP setup to recover it, as your efforts will no doubt break it many times before you get something on there which works as intended.


Arduino IDE - Ubuntu Mono Font Name? I know that you go to preferences.txt and there is editor.font= line setting, but I can't get what font name to type in there to use Ubuntu Mono. I would like to use that font please. I've tried:

Ubuntu_Mono
Ubuntu-Mono
Ubuntu Mono
Ubuntu+Mono
Ubuntu.Mono
UbuntuMono
Ubuntumono
ubuntumono
'Ubuntu Mono'
"Ubuntu Mono"
'UbuntuMono'
"UbuntuMono"
'Ubuntu-Mono'
"Ubuntu-Mono"
'Ubuntu_Mono'
"Ubuntu_Mono"

Thanks for answer :]

PS: Yes, I've restarted the studio every time, but some non-monotype/default font showed up.

You need to specify the font, style and size.  I think you want

editor.font=Ubuntu Mono,plain,12

I don't know the exact name you should use for the font but you must have all three fields separated by commas.

The second field can be "plain", "bold" or "italic".

The third field is the font size, I'm not sure the units.


How can program/arduino restarted by IDE? I wrote my custom sketch, where I am printing some greeting text inside setup() method.

I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. setup() method running again.

How can this happen? I was thinking setup() method run once, when Arduino is powered up by connecting to the USB socket?

If it is possible to restart it already connected, then how this can be done?

UPDATE

Code is follows:

#include <Wire.h>
#include <Adafruit_BMP085.h>

Adafruit_BMP085 bmp;

String command;

String awaitingMessage = "Temperature and pressure sensor awaiting commands\r\nCommand \'help\' is for help";

void awaiting() {
  Serial.println(awaitingMessage);
}

void help() {
  Serial.println("Temperature and pressure sensor commands:");
  Serial.println("temp\t- output temperature in degrees Celsius");
  Serial.println("press\t- output pressure in Pascals");
  Serial.println("wait\t- print awaiting message");
  Serial.println("help\t- output this text");
}

void temperature() {
  Serial.println(bmp.readTemperature());
}

void pressure() {
  Serial.println(bmp.readPressure());
}

void unknown() {
  if( command.length() > 0 ) {
      Serial.println("Unknown command was \'" + command + "'");
    }
}

void setup() {
   Serial.setTimeout(50000);
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  else {
    awaiting();
  }
}

void loop() {
  command = Serial.readStringUntil('\n');

  if( command.startsWith("temp") ) {
    temperature();
  }

  else if( command.startsWith("press") ) {
    pressure();
  }

  else if( command.startsWith("wait") ) {
    awaiting();
  }

  else if( command.startsWith("help") ) {
    help();
  }

  else {
    unknown();
    //awaiting();
  }

}

Video is here: https://youtu.be/-QBleGVxaus

When you open the serial monitor (or even just go to the serial port menu) the serial port is opened. When the serial port is opened the DTR line is asserted.  This is the method that the Arduino uses to reset so that you can access the bootloader and upload a new sketch.

Every time you open the serial port - through whatever means you choose - you reset the board, whether you like it or not.

There are a number of "fixes" for this - the simplest is to add a large (say 10µF) capacitor between the RESET and GND pins of the Arduino to filter out the reset pulse that would otherwise reboot the board.

There are also ways of disabling the reset within Windows, but that requires you to write your own software to interface with the board instead of using the serial monitor.

Some boards also come with a method of completely detaching the reset signal from the USB interface, but modifying the board itself isn't for beginners.

Just remember that once you have disabled reset through whatever means you will have to re-enable it (resolder the track you cut, remove the capacitor, whatever) before you can upload a new sketch.


Home devices control system using gsm and arduino mega2560 Hi dears I'm trying to do project to control app base gsm control by arduino mega 2560 gsm module SIM900A

To send SMS to open Led than reply SMS to give as the status I mean send SMS then I received SMS from GSM module  by this code same time work but same time not work also same time send SMS1111 received SMS2222 status.
I hope it is clear.

#include <SoftwareSerial.h>
#include <string.h>
#include "SIM900.h"
#include <TinyGPS.h>
#include "sms.h"
SoftwareSerial GSMSerial(12, 13);
byte buffer[128];
int count = 0;
const int Led4 = 43;
const int Led1 = 44;
const int Led2 = 45;
const int Led3 = 50;
void SIM900power()
{
}
void setup() {
    pinMode(Led1, OUTPUT);
  pinMode(Led2, OUTPUT);
  pinMode(Led3, OUTPUT);
  pinMode(Led4, OUTPUT);
  GSMSerial.begin(19200); // the SIM900 baud rate
  Serial.begin(9600); // the Serial port of Arduino baud rate.
  Sim900_Inti();
}
void loop() {
  GSMSerial.listen();
  if (GSMSerial.available()) // If date is comming from from GSM shield)
  {
    while (GSMSerial.available()) // reading data into char array
    {
      buffer[count++] = GSMSerial.read(); // writing data into array
      if (count == 128)break;
    }
    Serial.write(buffer, count); // if no data transmission ends, write         buffer to hardware serial port
Cmd_Read_Act(); //Read the 'COMMAND' sent to SIM900 through SMS
clearBufferArray(); // call clearBufferArray function to clear the storaged data from the array
count = 0; // set counter of while loop to zero
  }
  if (Serial.available()) // if data is available on hardwareserial port ==>     data is comming from PC or notebook
    GSMSerial.println(Serial.read()); // write it to the GPRS shield
}
void clearBufferArray() // function to clear buffer array
{
  delay(1000);
  for (int i = 0; i < count; i++)
  {
    buffer[i] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int n = 0; n < count; n++)
  {
    buffer[n] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int m = 0; m < count; m++)
  {
    buffer[m] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int p = 0; p < count; p++)
  {
    buffer[p] = NULL; // clear all index of array with command NULL
    delay(100);
  }
}
void Sim900_Inti(void)
    {
     GSMSerial.println("AT+CMGF=1"); // Set GSM shield to sms mode
  Serial.println("AT+CMGF=1");
  delay(500);
  GSMSerial.println("AT+CNMI=2,2");
  Serial.println("AT CMGF=1");
  delay(500);
}
void Cmd_Read_Act(void) //Function reads the SMS sent to SIM900 shield.
{
  char buffer_i[128];
  for (int i = 0; i < count; i++)
  {
    buffer_i[i] = char(buffer[i]);
  }
  if (strstr(buffer_i, "1111")) //Comparing password entered with password     stored in program
  {
          digitalWrite(Led1, HIGH);
   SMS_1111();
  }
  char buffer_n[128];
  for (int n = 0; n < count; n++)
  {
    buffer_n[n] = char(buffer[n]);
  }

  if (strstr(buffer_n, "2222")) //Comparing password entered with password     stored in program
  {
          digitalWrite(Led2, HIGH);
   SMS_2222();
  }
      char buffer_m[128];
  for (int m = 0; m < count; m++)
  {
    buffer[m] = char(buffer[m]);
  }
  if (strstr(buffer_m, "3333")) //Comparing password entered with password     stored in program
  {
   digitalWrite(Led3, HIGH);
   SMS_3333();
  }
  char buffer_p[128];
  for (int p = 0; p < count; p++)
  {
    buffer[p] = char(buffer[p]);
  }
  if (strstr(buffer_p, "4444")) //Comparing password entered with password stored in program
      {
    digitalWrite(Led4, HIGH);

   SMS_4444();
  }
}
  void SMS_1111() // complet liter Replay SMS TO Know Led1 Is ON
 {
 }
 void SMS_2222()// complet liter
{
}
void SMS_3333()// complet liter
{
}
void SMS_4444()// complet liter
{
}>

For the 3333 and 4444 you are doing

buffer[m] = char(buffer[m]);

and

buffer[p] = char(buffer[p]);

which does nothing.

You probably meant

buffer_m[m] = char(buffer[m]);

and

buffer_p[p] = char(buffer[p]);


Which tft works on both Arduino Uno and Raspberry pi Ideally I'd like a 2.8 inch and it to be touch screen.
But most of all I'd rather it work on both boards without much hassle.

Well any display can work on both of the boards if you can adjust the voltage levels right there is a display which was made for old Nokia phones and it is called nokia-5110-3310 and  is dirt cheap display and it can be used with both Arduino or raspberry pi or any other board which support the protocol here is a link for quick reference.

Adafruit link to the library


Sending Data between two boards using SoftwareSerial I'm attempting to connect two Arduino boards to eachother using SotwareSerial as the title suggests!

The two boards are 1) Arduino UNO and 2)MultiWii Controller (MWC) FLIP 1.5 (Uses ATMega328 chip).

The idea, is to get Serial TX on the "MWC" FLIP 1.5 to Serial RX on the UNO.

These are my connections thus far:

MWC Pin ------->UNO Pin

Digital 3 (TX)--->Digital 6 (RX)

Digital 9 (RX)--->Digital 9 (TX)

This is the code on the MWC Chip -- the TX chip. (NOTE: These functions are called to run in a header file)

#include "attout.h"
#include "SoftwareSerial.h"

SoftwareSerial altSerial(9,3); // RX=9 TX=3

void startaltserial(){

  altSerial.begin(9600);

}

void attout(){

pinMode(3,HIGH);
pinMode(9,HIGH);

  altSerial.print('1');

}

NOTE: I also tried altSerial.write('1'). Same result (or lack of one).

Then, the RX Code on the UNO Board:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); // RX=6 TX=9

void setup()
{
  // Open serial communications:
  Serial.begin(9600);

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

}

void loop()
{
  while (mySerial.available()>0) {
    Serial.println(mySerial.read());
  }
}

When I open Serial Monitor for the UNO board, I get nothing but zeroes streaming down. Curiously, if I disconnect the TX OUT wire from MWC, the Serial stream stops!

This means, as far as I can tell, that the UNO is doing its job of receiving, and the MWC is doing it's job of transmitting, but something is wrong with the formatting inbetween, so that I end up with zeroes.

Additionally, if I change the baud rate, the Serial Monitor output changes. When I go to 1200 baud, I get nothing but '4' followed quickly by '1' and then carriage return, so it looks like '41'.

Hope we can find a solution to these quandaries. My next course of action is trying I2C, but I'm not sure about it yet...

Your problem here is that you are streaming out serial data non-stop.

See my answer in this thread: What is Serial.begin(9600)?

Without having a pause, the receiver just latches onto somewhere in the middle of the data stream and tries to make sense of it, often unsuccessfully.

If you add one "character time" delay to the sender, the receiver works fine:

  altSerial.print('1');
  delay (2);

It might get the first one wrong, but now the receiver has 2 ms to resynchronize on the data stream. At 9600 baud the delay should be 1/960 (second) at least, I used twice that to be sure.


Serial debug output looking messy I've got this quite basic code running on an Arduino Mega 2560, and the output is looking like I have the serial settings wrong, though I can't work out what to change.

void setup()
{
  Serial.begin(9600);
  Serial.println("test123");
}

void loop()
{
  Serial.println("test" + millis());
}

The output looks like this:

ð¦·Z©÷
×ï¾üÿ7ß^|ïüûÿVÏuØëo~ìÿÓûzëýÿ{ßþ©×xñ×¤¿ïßûÏûýoÏ¿îãõI
õfwi÷`p¬½Ïª»QáÀª»¦·ð¦·Z©÷
test123
D

4ñjü¯÷~µÞMz¹Ý~¼
Ûþ}iû}ÒÖ¦Ç¿÷ÿÂï½Õ¾;îö

I'm using the inbuilt "Serial Monitor" in the Arduino suite with settings 9600 baud and no line endings.

I see that the first println in setup() is sending the data as expected but all other comms are coming through as nonsense.

Any suggestions of what to do?

This is unfortunately not valid in C++:

"test" + millis()

Rather than concatenating two strings, it's actually doing pointer arithmetic. It's taking the memory address where "test" is stored, and offsetting by the value retrieved from millis(). The result is a totally arbitrary memory location which gets treated like a string.

Generally speaking, it's arguably best to avoid string concatenation on Arduino anyway unless absolutely necessary. The reason is that it can use more memory than you might expect.

A simpler approach would simply be to do the serial output as a sequence of individual operations, e.g.:

Serial.print( "test" );
Serial.println( millis() );

Note the difference between print() and println(). The first one doesn't add a line break at the end, but the second one does.


Last element of a struct disappearing on write/read I'm building a weather station with two UNOs, using NRF24l01+ radios. Communications are fine. I'm sending a struct from one to the other. The struct has three elements:

    struct weather {
      float tempData;
      float humData;
      float pressData;
    };
    weather wData = {0, 0, 0};

I then populate the struct with values from my DHT22 Temperature Sensor and my BMP085 pressure sensor.

    float c = dht.readTemperature();
    wData.tempData = (c * 9/5) + 32;
    wData.humData = dht.readHumidity();

    sensors_event_t event;
    bmp.getEvent(&event);
    wData.pressData = (0.0295 * event.pressure);

Now I send it via the NRF24L01+.

    radio.write(&wData, sizeof(wData);

On the receiving Uno I have this.

    struct weather {
      float tempData;
      float humData;
      float pressData;
    };

    weather wData = {0, 0, 0};

    radio.read( &wData, sizeof(wData) );
    Serial.println(wData.tempData);
    Serial.println(wData.humData);
    Serial.println(wData.pressData);

I get results similar to this:

    Temp = 75.43
    Hum = 35.76
    Press = 0.00

The first two are correct. The final one is not. I can change the order and the first two will always be correct, but the last element is always 0.00. For example:

   Hum = 35.76
   Press = 30.14
   Temp = 0.00

I know I'm missing something here with my code but I can't find it. Anyone have some suggestions?

Modified my struct by changing the first two elements from float to int.

struct weather {
  int tempData;
  int humData;
  float pressData;
}
weather wData;

Everything transmits fine now. I don't really need the precision of a float for temperature and humidity. However, I would still like to find the problem. Could there be some problem with the size of three floats versus two ints and a float? Serial.print(sizeof(wData)) is 12 when all elements are floats and 8 when using two int and a float. My understanding is the NRF24L01+ has a transmit and receive buffer of 32 bytes.


Using MCP23017 to control Servos Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question
" how can I do this with a MCP23017 ? ".
I have searched the web a fair bit but no luck.
Is there a modified Servo library out there??
It's such an obvious solution i figure it must have been done before.
Any suggestions..Thanks.

Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question " how can I do this with a MCP23017?

The Servo library could be modified to allow toggling of GPIO pins on a MCP23017 but there are some issues with timing.

The library uses Timers and Interrupt Service Routines (ISR) to handle the pulse width. The servo pin is toggled in the ISR.

At 100 KHz (100 Kbps) I2C at least 3 bytes need to be transmitted to the MCP230017 to toggle a pin. That is approx. 300 us and not possible to do from the Servo ISR. Another execution pattern is required.

Cheers!