<issue_start>username_0: I've written a program for Arduino UNO and 3 LED lights. The program is supposed to turn an inputted number into binary and then display it on the LEDs, on being 1 and off being 0 I have looked it over quite a few times and don't understand why it is not working as it should. I'm a beginner at working with Arduino so I probably just need a more experienced eye to show me where I have messed up. I have a link to a picture of the Arduino setup below. Thanks!
<https://drive.google.com/file/d/0B8k_WNZ3eFOkZHkwNUllTEp4WGM/view?usp=sharing>

```
//setting up lights
const int lightOne = 13;
const int lightTwo = 12;
const int lightThree = 11;

//array of the lights for when printing the binary
int lights[] = {lightOne, lightTwo, lightThree};

void setup() {
  //setting pin modes and starting up the serial monitor
  pinMode(lightOne, OUTPUT);
  pinMode(lightTwo, OUTPUT);
  pinMode(lightThree, OUTPUT);
  Serial.begin(9600);
}

//converts a given number into binary
String binary(int number) {
  String r;
  while(number!=0) {
    r = (number % 2 == 0 ? "0" : "1")+r;
    number /= 2;
  }
  return r;
}

//outputs the binary string to the lights (not expecting numbers larger than     9)
void printBinary(String binaryNumber) {
  for (int i = 0; i < sizeof(binaryNumber); i++) {
    digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));
    delay(2000);
  }
}

void loop() {
  int input = Serial.read();                //get the number
  String binaryNumber = binary(input);      //convert number to binary
  Serial.println(binaryNumber);             //print binary to serial monitor
  printBinary(binaryNumber);                //display number in binary on     LEDs

}

```<issue_comment>username_1: You need to check that there are characters available before reading. Please see documentation of [Serial.read](https://www.arduino.cc/en/Serial/Read)() (and [Serial.available()](https://www.arduino.cc/en/Serial/Available)).

Cheers!
Upvotes: 1 <issue_comment>username_2: Welcome to SE Arduino!
======================

Long Version
------------

You have a couple of things to look at:

1. Don't use `String` class it has too much overhead for Arduino.
2. Your conversion function is not really necessary because you can convert it on your `Serial.println()` by specifying `binary` as output. eg: [`Serial.println(number, BIN)`](https://www.arduino.cc/en/Serial/Println);
3. The `Serial.read` returns an integer, but that `int` only contains a [`byte`](https://www.arduino.cc/en/Reference/Byte) (unsigned) value anyway (unless there's nothing to be read, in which case it returns `-1`). Because you're taking a number (not really relevant) and you want it to be a number on the return, just use `int` or `byte` (unsigned: `0 <-> 255`) or [`char`](https://www.arduino.cc/en/Reference/Char) (signed: `-127 <-> +128`).
4. You could/should/doesn't matter if you use `Serial.available()` or not, it is a matter for yourself, I usually do, but it's non blocking anyway and if there's nothing there to be read, it'll just continue on anyway. Although if you're not going to use it, you should test for that `-1` as what you're doing at the moment is taking that and converting it to binary (which is `0xFF` which is everything on). **This is one of your major problems in the code** (the other is in the **Short Version** section.
5. You're using `"0"` and `"1"` which are `ASCII` values, and you haven't indicated how you're getting the number. So it may be `ASCII` (`byte`) or actually a `byte` value. ie, `"0"` is `48 (dec)` or `30 (hex)`. Whereas a `0` is just `zero`. Funnily enough, because you're using modulo (`%`) it doesn't really matter because you're only interested in the lowest nibble, which for the sake of your code, doesn't matter what's encoded at the higher end. ie: `1` (`0b00000001`) is the same as `"1" = 49 (dec) = 0x31 = 0b00110001` when used with `%2`.
6. Ditch your `delay(2000)`. Delays are evil\* :) You could write the values to the pins all day, you're not going to cause any problems, if you want to output less to your serial port (which you should do), you could do timed outputs back to Serial. ie, do your `Serial.println()` once a second, or record the values into backup/old variables and compare them, and only print the output if the value changes
7. The big one is in the next section

Short Version
-------------

This is your *main* problem, on this line:

```
digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));

```

I think you need:

```
digitalWrite(lights[i], (binaryNumber[i] == '0' ? LOW : HIGH));

```

You already have the pin value encoded in the array, you don't want to add 11 to the index, that's going to throw you above your three light values :)

**\* Delays are evil**: It's a matter of opinion, and that's just how I feel, I actually googled it and this is just a random response. But it contains the crux of what I'd say anyway: <http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/>
Upvotes: 3 [selected_answer]


<issue_start>username_0: It's my understanding that when a Timer is used on an Arduino (in my case the Arduino Mega), it can disable analog write on some PWM pins, which pins depends on the Timer being used. For instance on the Mega, pins 44,45,46 are controlled by Timer 5. If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.<issue_comment>username_1: >
> If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.
>
>
>

You can view the connection between the Timer and the pins as programmable. The connection is enabled by, for instance, analogWrite(). The Timer control registers have a setting for both the connection and control logic of the pin (clean, set or toggle on timer value match).

You can use the Timer to generate interrupts without connecting a pin. This is the case with micros() and millis() which get their values from a counter which is updated by an ISR on Timer 0 (overflow). analogWrite() on pin 5 and 6 connects to Timer 0 value match logic.

analogWrite() uses the Timer value match and connects the pins. Enabling only the Timer (as you suggest) will allow you to use the pins with digitalWrite(). You can also use the Timer ISR for overflow. The Timer prescale is set for analogWrite().

Cheers!
Upvotes: 3 [selected_answer]<issue_comment>username_2: When using an timer (other than by PWM) you can choose to enable it's output to a pin (which basically is what PWM does). So you can still use them as a digital pin (if you choose not to).

You could set up an PWM signal and enable timer interrupts afaik. But changing PWM, would also change the timer.

There is a difference in only using Arduino functions, or changing the registers directly.
Try to read the "timers" part of the datasheet and find some tutorials about avr/atmel/atmega register changing or/and setting up timers.
Upvotes: 2


<issue_start>username_0: Why is my machine suddenly turns ON when I unplugged the USB on my computer? Does it have connection on the auto reset feature of my arduino board?

[![enter image description here](https://i.stack.imgur.com/AG4aC.jpg)](https://i.stack.imgur.com/AG4aC.jpg)

```
String input = "";

void setup(){

  Serial.begin(9600);   // Sets up communication with the serial port

  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);

  digitalWrite(11,LOW);

}

void loop(){

  int recipe;
  //Serial.print("Enter recipe number: ");

  while(Serial.available()==0){    // Waits for data from serial port
  }

  while(Serial.available() > 0){
    int data = Serial.read();
      // convert the incoming byte to a char
      // and add it to the string
    input += (char)data;

    recipe = input.toInt()+'0';    //recipe=0 if not a digit
    if(recipe == '0')
      recipe = data;

    if(data == '\n'){
      //Serial.print("Recipe: ");
      //Serial.println(recipe);
      //Serial.print("String: ");
      //Serial.println(input);
      input = "";
    }
  }

  if(recipe == 's'){
    digitalWrite(11,HIGH);
    delay(1000);
    digitalWrite(11,LOW);

    digitalWrite(6,LOW);
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
  }

  else if(recipe>'0' && recipe<'32'){

    recipe = recipe-'0';
    char binary[7] = {0};   // This is where the binary representation will be stored
    recipe += 32; // Adding 32 so that there will always be 6 digits in the string
    itoa(recipe,binary,2);  // Convert recipe to a string of base 2 and save it in array 'binary'
    char* signals = binary + 1; // Get rid of the most significant digit to get the 5 bits

  //Serial.print(signals);  // Print out the signals in binary

    int i;
    for(i=0; i<5; i++){
      if(signals[i] == '0')
        signals[i] = '1';
      else
        signals[i] = '0';
      digitalWrite(i+6, signals[i]-'0');    // write to pin; converts the bit of the string to HIGH or LOW
      //Serial.print(signals[i]);
    }

  }
  else
    loop();

}

```<issue_comment>username_1: Do not call `loop` from `loop`. You will quickly run out of RAM and the sketch will crash:

```C++
void loop(){

  int recipe;
  //Serial.print("Enter recipe number: ");

  while(Serial.available()==0){    // Waits for data from serial port
  }

  while(Serial.available() > 0){
...

  }
  else
    loop();

}

```

---

For the pins that are supposed to be high, I suggest pull-up resistors:

```C++
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);

```

When the Arduino powers up it enters the bootloader for a second or so. Those pins won't be set high yet. A pull-up resistor would make sure they are high until such time as you want to drive them low.

---

If you are saying that the machine powers up when you **disconnect** the power to the Arduino, that is still a good reason for using pull-up resistors, to make sure that it does not operated until commanded to do so.

---

>
> where will i connect the pull up resistors and how?
>
>
>

Typically pull-up resistors will be around 10k, and are connected from the pin to +5V. Of course, if the Arduino is not powered, then you need another source of the +5V.

---

>
> please to clarify the "do not call from loop to loop"
>
>
>

Remove these two lines:

```C++
else
    loop();

```

When `loop` exits, is it immediately re-called. You don't need to do it that way, in fact it is a Bad Idea.
Upvotes: 1 <issue_comment>username_2: It looks like the this line in your setup:

```
  digitalWrite(11,LOW);

```

... would trigger contact input 211, and do "Start of Program Operation when D11 switches from off to on" every time the sketch starts.

If the arduino resets, it will pull this line low. Autoreset would initiate this.

By changing the line to the following, the code will wait until it gets an 's' before pulling the line low.

```
  digitalWrite(11,HIGH);

```

I don't have an Arduino, but perhaps <http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection> may help in managing the Auto-Reset issue.
Upvotes: 0


<issue_start>username_0: When I run FullExample program from TinyGPS++, I get following types of entries,

```
Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum
          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail
---------------------------------------------------------------------------------------------------------------------------------------

0    9999 ********** *********** **** 07/01/2016 07:32:50 689  ****** ****** ***** ***   ******** ****** ***   75128 0         0
0    9999 ********** *********** **** 07/01/2016 07:32:51 857  ****** ****** ***** ***   ******** ****** ***   75389 0         0
0    9999 ********** *********** **** 07/01/2016 07:32:52 864  ****** ****** ***** ***   ******** ****** ***   75642 0         0
0    9999 ********** *********** **** 07/01/2016 07:32:53 870  ****** ****** ***** ***   ******** ****** ***   75895 0         0
0    9999 ********** *********** **** 07/01/2016 07:32:54 878  ****** ****** ***** ***   ******** ****** ***   76148 0         0

```

Other details:

GPSBaud = 9600;

RXPin = 11;

TXPin = 10

Module: GY-NEO6MV2<issue_comment>username_1: That is a ***perfect*** printout of a GPS system that can see **zero** satellites.

The fact that the timestamps are one second apart shows that you have correctly interfaced with the GPS device. Now, the GPS device has to 'interface' with the satellites!

Many people don't realise two things:

1. The GPS antenna really does need a clear view of the sky. A tiny view through a window may show one or two satellites, but you need a minimum of three, and preferaby four or more at a number of points around the sky to get a fix.
2. If the GPS unit has been completely powered off (called 'cold'), when it first powers on it has NO idea where anything is. It simply listens for any signal anywhere until it "hears" the current time. It can then guess where satellites might be, and listens for updates on satellite positions.

All of this listening, guessing and waiting takes time before it can start to actually lock on to satellites and start to get a fix. This time could easily be 90 seconds or more - you need to be patient. Check your GPS device specifications for "cold start" times.

### Edit

I'm impressed! The GY-NEO6MV2 that you list has a cold-start of 27 seconds - but that assumes it has a clear view of the sky.
Upvotes: 3 [selected_answer]<issue_comment>username_2: The GPS actually seems to be getting some data: the date and time.
Which means it can be used to set the time (and date) in a clock if the timezone is known without needing a fix (useful inside).
Upvotes: 1


<issue_start>username_0: I am writing a software that runs on the PC that has a Arduino 2560 connected to it via USB. This PC needs to communicate with multiple devices through RS232.

Is it possible to use the Arduino's 4 UARTs to communicate with 4 different hardware that uses RS232 serial communication, using just 1 USB connection between the PC and the Arduino 2560?

The Arduino 2560 will basically act as an interface for 1 USB to talk to 4 RS232 devices.<issue_comment>username_1: I did not experience the problem because I usually use a Makefile instead of
the Arduino IDE. I now tried with the IDE version 1.0.5 and I had the same
problem as you. The fix is to explicitly declare the function before
defining it:

```c++
void Move(Dir direction, int distance);
void Move(Dir direction, int distance)
{
     direction = forward;
}

```
Upvotes: 2 <issue_comment>username_2: The Arduino 1.7.x series from Arduino.org uses the old build system that is severely broken when you try and do anything more complex than simple types.

It adds prototypes to your functions to the top of the program so you don't have to get the order right, but it puts them in completely the wrong place. The result is a C++ file that looks like this:

```
#include
void Move ( Dir direction , int distance );
void setup();
void loop();

enum Dir
{
 forward = 1,
 backward = 2,
 left = 3,
 right = 4
};

void Move ( Dir direction , int distance )
{
 direction = forward;
}

void setup() {
 // put your setup code here, to run once:
}

void loop() {
 // put your main code here, to run repeatedly:
}

```

As you can see the prototype involving `Dir` has been placed before the definition of `Dir`, and so it fails miserably.

There are some hacks you can do to force it to place the prototypes after your definition, but I can't recall what they are off hand.

The simple answer is to ditch Arduino 1.7.10 and switch to Arduino 1.6.10 from Arduino.cc instead. This uses the Arduino Builder system which does things much better, including placing the prototypes in the right place.

Despite the numbering 1.7.10 is not a newer version than 1.6.10 - it is an older version renumbered. It's all part of the schism between the two halves of Arduino.

Even better is to ditch the awful Arduino IDE entirely and use one of the many far better IDEs that exist.
Upvotes: 3 [selected_answer]<issue_comment>username_3: You have to define a new enum type:

```
typedef enum
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
} Dir;

void Move ( Dir direction , int distance )
{
     direction = forward;
}

```

without `typedef` your Dir is just static enum variable, it can't be used to define other vars.
Upvotes: 0 <issue_comment>username_4: As username_2 points out, this seems to be a problem with the parsing of the preprocessor.

You have two options:

- Use username_1s solution and declare the function before defining it

- Create a separate header file for your enum in a new tab and import it with #include "[myEnumsHeaderFilename].h"

```
#include "myEnums.h"

void Move(Dir direction, int distance)
{
   direction = forward;
}

void setup() {}

void loop() {}

```
Upvotes: 2


<issue_start>username_0: I want to make some precise measurements with Arduino Due. Although I'm using very good external voltage reference (LTC6655) measured data is still jumping around, especially significant when I'm trying to measure low voltages (0.1-0.05V). Can I improve ADC accuracy by changing it's settings?

The default Arduino Due ADC settings are:

```
// Initialize Analog Controller
pmc_enable_periph_clk(ID_ADC);
adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1);
adc_configure_trigger(ADC, ADC_TRIG_SW, 0); // Disable hardware trigger.
adc_disable_interrupt(ADC, 0xFFFFFFFF); // Disable all ADC interrupts.
adc_disable_all_channel(ADC);

```

So, with `adc_init` we can configure frequency and startup time. And with `adc_configure_timing` we configure tracking time, settling time and transfer time. But how to select those values? Does increasing of that times improves precision?

Useful links:

[Datasheet](http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf) - ADC description starts on page 1317.

[Atmel Software Framework](http://www.atmel.com/tools/avrsoftwareframework.aspx) - see adc.h and adc.c.<issue_comment>username_1: Default resolution is 10b because of backward compatibility, so you can start with setting `analogReadResolution(12);` as stated on [Arduino analogReadResolution Refference page](https://www.arduino.cc/en/Reference/AnalogReadResolution).

If it's still not enough you can use GAIN setting for used ADC channel. For single ended input GAIN can be set up to 4. But it means you can mesaure voltages up to 1/4 of Uref
Upvotes: 0 <issue_comment>username_2: >
> measured data is still jumping around
>
>
>

it will always jump around -> that's why adc modules are such a great random number generators (using its lsb). jumping around 8 - 9 lsb isn't that rare. anything beyond that should be investigated.

a few things to watch for:

1. use a good reference;
	2. allow sufficient time;
	3. pay attention to layout;
	4. make sure that the source impedance isn't too great;
	5. put a signal conditioning circuit on the input. a 1k/.1uf filter can do wonders;
	6. pick the right oscillator for the adc module - see some c8051f350 code for example;
	7. write the right code;
	8. oversampling.
Upvotes: 0 <issue_comment>username_3: Generally speaking the input BandWidth of the analog signal is a major cause of noise in a ADC circuit as well as improper ground and reference generation and layout techniques. Be very careful that ALL of the analog paths do not have any digital current return paths. Remember that at 12 bit for a 1.25V reference an LSB is ~300uV. I have not ever measured the SNR of the SAM ADC but I doubt that it is the specified ~60db (i.e. 10bit) unless absolute care is taken during the layout/routing.
Recommend:
1) Limit input BW to the correct channel ground. (well below Nyquist BW if possible to avoid alliasing)
2) Oversample if possible.
3) Insure low digital I/O of peripherals during sample period.
Upvotes: 2


<issue_start>username_0: I'm trying to see when an echo is received by my HR-S04 sensor. I have a Serial.println within my while loop to read the signal and see once a change happens to break the loop.

The issue is my serial just prints out the pin my echo to linked to. How can I set it so that the serial output is LOW and then HIGH once an echo is received?

```
int trig1 = 3; //Trig 1
int echo1 = 4; //echo1
int ECHO1;
double pingTime1;

void setup()
{
  Serial.begin(9600);
   pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
   pinMode(echo1, INPUT);  //sets the digital pin 5 as input
}

void loop()
{
  ECHO1 = digitalRead(echo1); //assume echo1 is LOW and HIGH once echo is received

  while (ECHO1 == 0) //continuous loop until echo is HIGH
  {
    digitalWrite(trig1,LOW);
    delay(100);
    digitalWrite(trig1,HIGH);
    Serial.println(echo1); //Troubleshooting to see when pulse is read by sensor
   ECHO1 = digitalRead(echo1);
  }
  pingTime1 = pulseIn(echo1, HIGH); //Measure ping travel time in microseconds
  pingTime1 = pingTime1*1000; //convert microseconds to seconds

}

```<issue_comment>username_1: A couple things:

1) I believe your code for the trigger pin is wrong. An example I found sets it up as LOW for 2 microseconds, then HIGH for 10 microseconds, then LOW. (Note that the units are MICROseconds so you must use delayMicroseconds()

2) digitalRead(echo1) does nothing. Use the pingTime1 instead. You will always be receiving an 'echo' so it's not a HIGH or LOW but rather a changing variable stored as pingTime1.

3) echo1 is the variable for the pin. That's why Serial.println(echo1) prints the pin number. You could try Serial.println(ECHO1) but I don't think it will work because of what I said above.

4) If you want a HIGH or LOW to print to screen you must set a cutoff value for pingTime1 then use an if statement to print the appropriate value.

I'm not sure what exactly you're trying to do, but given the points above I do not believe a while loop is necessary.

Try this code. You can keep the first Serial.println() to see the duration of the pulse and/or you can keep the if statement if you want a HIGH or LOW to print to screen.

```
// Send a pulse out through trig pin
digitalWrite(trig1,LOW);
delayMicroseconds(2);
digitalWrite(trig1,HIGH);
delayMicroseconds(10);

//Receive pulse through echo pin
pingTime1=pulseIn(echo1, HIGH);
pingTime1=pingTime1*1000;

// Serial print
Serial.println(pingTime1);

//Serial print (for HIGH or LOW)
if (pingTime1 > cutoff) {
    Serial.println('HIGH');
}
else {
    Serial.println('LOW');

```
Upvotes: 0 <issue_comment>username_2: To start with, you code isn't suppose to work. Here is a working code to start with (code below). You have a lot of mistakes so I suggest comparing your code to this one. Also, don't try to debug by adding a `Serial.print(/*something*/);` in your code.

For the time the echo is received is way too fast (under 0,001 seconds). I doupt you can use that for something useful. There is a way to calculate that using the `millis()` function, but it is quite complex for your project.

Here is a working code for the HC-SR04:

```
const int trigPin = 2;
const int echoPin = 3;

long duration, distance;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.begin(9600);
}

void loop() {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 150) {
    Serial.print(distance);
    Serial.println("  cm");
  }
  if (distance > 150) {
    Serial.println("OUT OF RANGE");
  }
  delay(20);
}

```
Upvotes: 1


<issue_start>username_0: I would like to timer for how long a button is not pressed. So actually if(buttonState == LOW 'for two seconds') than execute the code that comes after it. But the problem is while the user is still pressing the button the timer already starts.

Code:

```
int ledPin[] = {7,8,9,10};
int ledPin11 = 11;
long randNumber;
const int buttonPin = 2;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
unsigned long previousMillis = 0;
const long interval = 2000;

void setup() {
 Serial.begin(9600);
 pinMode(LED_BUILTIN, OUTPUT);
 randomSeed(analogRead(0));
 randNumber = random(1, 16);
 Serial.println(randNumber);
 for (int i = 0; i < 4; i++) {
   pinMode(ledPin[i], OUTPUT);
 }
  pinMode(buttonPin, INPUT);
 }

 void loop() {
  displayBinary(randNumber); //functie 'display binary'
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    previousMillis = currentMillis;
    if(buttonState == LOW){
    antwoord(buttonPushCounter,randNumber);
    delay(5000);
    displayBinary(randNumber);
  }
 }
 buttonState = digitalRead(buttonPin);
 if (buttonState != lastButtonState) { // als de button word ingedrukt krijgt buttonPushCounter + 1
 if (buttonState == HIGH) {
  buttonPushCounter++;
  Serial.print("Nummer hoe vaak is gedrukt");
  Serial.println(buttonPushCounter);
 } else {
  Serial.println("off");
}
delay(250);
 }
}

void antwoord(int teller, int antwoord) {
 if (teller == antwoord) {
  for (int i = 0; i < 4; i++) {
  pinMode(ledPin[i], LOW);
 }
 digitalWrite(LED_BUILTIN, HIGH);
 delay(250);
 digitalWrite(LED_BUILTIN, LOW);
 delay(250);
 digitalWrite(LED_BUILTIN, HIGH);
 delay(250);
 } else if (teller > antwoord || teller < antwoord) {
   for (int i = 0; i < 4; i++) {
    pinMode(ledPin[i], LOW);
  }
    digitalWrite(LED_BUILTIN, HIGH);
  }
}

void displayBinary(byte numToShow) //van byte naar decimaal
  {
   for (int i = 0; i < 4; i++) {
    if (bitRead(numToShow, i) == 1) {
    digitalWrite(ledPin[i], HIGH);
    } else {
      digitalWrite(ledPin[i], LOW);
    }
   }
  }

```<issue_comment>username_1: Your question is not clear enough.

I hope I get what you want.

Do while loop about the pressing...

```
if (button == LOW)
     while(!digitalread(button)){};

```
Upvotes: 0 <issue_comment>username_2: I would start a timer when the button changes state. Then you timeout if
the button is released **and** it hasn't changed state for too long:

```
void loop()
{
    static int lastButtonState;
    static unsigned long buttonChangeTime;
    int buttonState = digitalRead(buttonPin);
    unsigned long now = millis();

    // Record time when button changes state.
    if (buttonState != lastButtonState)
        buttonChangeTime = now;

    // Timeout if button is not pushed for too long.
    if (buttonState == LOW && now - buttonChangeTime >= interval)
        Serial.println("Timeout.");

    lastButtonState = buttonState;
}

```

Don't forget to update `lastButtonState` on each iteration.
Upvotes: 2


<issue_start>username_0: This might be a very simple question but I don't know which key represents KEY\_LEFT\_GUI on my keyboard. I thought it was the windows key but when I program Arduino Micro to execute it. Run does not open and it prints powershell on the "Search Programs and Files" section in Windows7 VM.

```
  Keyboard.press(KEY_LEFT_GUI);
  delay(1000);
  Keyboard.press('r');
  delay(1000);
  Keyboard.releaseAll();

  delay(500);

  Keyboard.print("powershell");
  typeKey(KEY_RETURN);

```<issue_comment>username_1: KEY\_LEFT\_GUI is the left Windows key. I think the problem may be that your code is only holding those keys down for microseconds. You need to give the computer a little bit of time to recognize the keypresses because it's expecting a human using a keyboard, not a microcontroller running at 16MHz. Try adding a delay before `Keyboard.releaseAll();`.
Upvotes: 1 [selected_answer]<issue_comment>username_2: I know it's a late answer, but you can use to open the run window:

Keyboard.press(KEY\_LEFT\_GUI);
 Keyboard.press(114);
 Keyboard.releaseAll();

And yes, as username_1 says, KEY\_LEFT\_GUI is the left windows key
Upvotes: 1


<issue_start>username_0: I want my Arduino to drive a LED strip.

The LED strip in particular is the 3528 non-waterproof type.

To power this up, I need a 12V power supply.

My LED strip is going to be 5 meters.

Now my questions are:

1. Is it important on how many amps, my powers supply will feed? One guy did it with 12V, 5A power supply. Considering the length (5m), is a particular amperage value necessary?
2. Can I power up the Arduino Nano with the power from the power supply? Voltage wise, I am clear, since the nano can handle 12 volts... What I am scared of is the amperage... Considering that I need a particular value of amps to power up my LED strip, can the nano handle this many amps? Is there a limit to how many amps the power supply line that I will feed my Arduino has to be?<issue_comment>username_1: >
> 1) Is it important on how many amps, my powers supply will feed?
>
>
>

Yes. You need the PSU to be able to supply as much current as you will need for everything you are powering form it.

You don't say how many LEDs will be on this strip (only the length of the strip) and I am not sure how much current/power a single one consumes, but **for illustration** let's imagine there are 100 LEDs on your strip and each one takes 0.8W.

100 LEDs x 0.8W per LED = 80W.

P = VI, where P=Power, V=voltage, I=current.

So I = P/V = 80 / 12 = 6.66A -- call it 7A.

The amount taken by the Nano will be small in comparison - if you said 0.5A you'd be safe.

So with these figures you'd need a 7.5A PSU.

>
> Considering that i need a particular value of amps to power up my LED strip, can the nano handle this many amps?
>
>
>

You can power the Arduino from the same power supply, yes. The Arduino will *draw* whatever current it needs. (Think of it this way: mains sockets are 13A - a desk lamp won't draw 13A.) What matters is that the supply can supply at least enough current, and that the voltage is correct.

As mentioned in the comments, you can't drive 3528s directly from the Nano - but you don't ask about that so presume you either know how to do it, or will ask another question.
Upvotes: 2 <issue_comment>username_2: Usually strips have not individual LEDs, but are composed of a lot of "pieces" in parallel, and each piece is composed by three leds in series along with a resistor.

Usually the strips are composed by 60 leds/m (i.e. pieces of 5cm), but sometimes also 120 leds/m or 30 leds/m. Let's assume it is the 60 leds/m version (you can check the length of the piece you can cut - which should be 5 cm - and that it contains 3 leds).

This means that in 5m there are 100 pieces. Now, usually the 3528 leds absorb 20mA of current for each segment (the 5050 version should be rated at 60). This means that the whole led strip should absorb 2A @ 12V.

Now the power supply. 2A is the nominal current the whole strips should absorb. Add about 200mA for the nano, and increase a bit the current requirement not to stress the power supply: you get a 12V 3A power supply at least (note that, while 12V should remain the same, you can take any current greater than this value - if for instance you have a 12V 5A power supply it is perfectly fine).

Now, the nano. It surely can't handle the 2A current. This means that you can power the arduino nano from the 12V. BUT beware: you should connect the 12V power to the VIN input (so the onboard regulator lowers it to 5V). Then you can't power the LEDs directly from the nano, but you need a transistor to decouple them. You can take any nMOS with a drain current greater than 3A or an NPN with collector current >3A and build the appropriate curcuit to drive them, then connect the + terminal of the strip to the +12V wire, the transistor source (or emitter) to the ground wire and the gate (base) should be driven by the nano.
Upvotes: 4 [selected_answer]<issue_comment>username_3: Because there are three LEDs in series, you cannot drive these LEDs from a 5V supply. The LED strips say "+12V" on them to mark the anode and that's the maximum voltage we suggest. We've found that if you're ok with them being a little dimmer, even 9VDC works very well.

Each segment of 3 LEDs draws approximately 20 milliAmperes from a 12V supply, per string of LEDs. So for each segment, there is a maximum 20mA draw from the red LEDs, 20mA draw from the green and 20mA from the blue. If you have the LED strip on full white (all LEDs lit) that would be 60mA per segment.

To find the total maximum current draw per meter, we would multiply 60mA x 10 (ten segments per meter for the 30/LED per meter strip) = 0.6 Amps per meter OR 60mA x 20 (twenty segments per meter for the 60/LED per meter strip) = 1.2 Amps per meter. Again, that's assuming you would have all the LEDs on at once and that you are powering it from 12V. If you're going to be PWM-fading between colors, maybe 1/2 of that is what you'll be drawing. Still, you do need to have a fairly decent power supply to run this strip, all those LEDs add up!
Upvotes: 1


<issue_start>username_0: Recently I have unsoldered most connector pins there are on the arduino uno board.
However, when I now attempt to upload a new sketch (works when I upload it to another model) it gives me the following error:

```
> avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xfa

```

I would like you take a look at my arduino board to see whether I have unsoldered important pins which might have to be connected.

Also when I try to upload a new sketch the 'L'-LED doesn't flash but the RX one.

(BTW: Yes I've set the settings to the correct board, port etc...)

[![enter image description here](https://i.stack.imgur.com/8Ajo5.jpg)](https://i.stack.imgur.com/8Ajo5.jpg)

Thanks for any solution attempts!<issue_comment>username_1: Pin 0(RX) and 1(TX) and the RESET pins are important to upload a sketch. Can you check those carefully with a magnifier ? Perhaps there is some solder that shortcuts to something else, or perhaps you damaged a copper trace.
Upvotes: 0 <issue_comment>username_2: Checking the schematic, the TX/RX leds are driven directly by the atmega16u and are not connected to the TX/RX lines of the 328p. That would seem to indicate the 16u has a problem so it's a good place to double check. The lines that run to the TX/RX of the 328p run from pins 8 - 9 of the 16u. I assume that this ran previous to the fatal 'surgery'? I don't suppose you loaded something simple, like the led flash program before surgery? Just curious, are you hard wiring it to something?
Upvotes: 0 <issue_comment>username_3: Removing there pin headers should not cause any sketch upload issue. I have done it many times.

You did try uploading BEFORE unsoldering the headers right ?

However looking at the desoldering job you did, my guess is that you applied too much heat or cut a trace on the PCB while doing it.

Can you upload a high resolution of the back side of the board?

What I would try is to take a known good 328p chip and replace the one on this board with it and try uploading again.
Upvotes: 1 <issue_comment>username_4: Try to unplug the IC and the plug it again.

I think that you have removed the IC off of the board. If it doesn't work then buy a new ATmega328P IC and replace it with the old one and then try again.
Upvotes: 0


<issue_start>username_0: Buttons on separate interrupt pins work fine (triggered on *FALLING*), bouncing is handling by forcing a 80ms lockout period during which further presses are ignored. I like that solution for being lightweight.

My goal is to have 1 interrupt handle all events (buttons and other digital inputs). I don't want to depend on *loop()*, I wish to be free to use *delay* often rather than timer interrupts.

Most buttons execute an action when pressed, some, while pressed.

What I have now (just 2 buttons for now):

![schematic](https://i.stack.imgur.com/lW4oK.png)

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2flW4oK.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)

```c++
void setup() {
  pinMode(17, INPUT_PULLUP);
  pinMode(16, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(3), wotHappnd, CHANGE);
}

boolean isDebouncing(){
  unsigned int now = millis();
  if(now - time_lastPressed > time_debounceLockout){
    time_lastPressed = now;
    return false;
  }
  return true;
}

void wotHappnd(){
  boolean interruptFalling = digitalRead(3) == LOW;
  if(interruptFalling && isDebouncing()) return;
  // digitalRead the pins; do stuff
}

```

Internal pullups on all used pins.

My problem is that often (~4%), on interrupt, the interrupt pin is *LOW* all button pins are *HIGH* ("not pressed" - likely bouncing just as I read it). How to fix that?

Can't use *delay* during an interrupt; *delayMicroseconds* to wait for stable readout still feels inappropriate; a cap-based delay on the interrupt pin induces a period of floating.
Prefer solutions in software or with no more than 1 extra component per input.

**[edit]** [here](https://electronics.stackexchange.com/a/236692/65089)'s a claim that pin interrupts do some filtering already, which, if true, may make some solutions unreliable.<issue_comment>username_1: In the Isr, read the two pins and maintain their current status (UN debounced), and reset a counter.

In the main loop, increment that counter. If it is more than a certain number, it means that the current state of the key has been stable for a while - bounce no more.

Or Google Kuhn debounced. I wrote a blog page about that. If you want, I can post it later. The basic idea is the same.
Upvotes: 2 [selected_answer]<issue_comment>username_2: As ever I am the voice of dissent: never write software to solve a hardware problem.

For a double-throw switch the classic solution is an SR latch.

Single throw is actually harder. On the face of it, debounce is a trivial matter done with a capacitor and a pull-down (or pull-up) resistor. This will certainly stop floating and false positives from induced current from spikes. However, microprocessors switch pretty fast and will recognise the edges of microsecond oscillations around the switching voltage as changes of switch state. To prevent this you need the hysteresis of a [Schmitt Trigger](http://www.ti.com/lit/an/scea046/scea046.pdf) such as an [LM7414](https://www.onsemi.com/pub/Collateral/MC74HC14A-D.PDF) (TTL) or [LM7417](http://www.ti.com/lit/ds/symlink/sn74aup1t17.pdf) (suitable for 3V3).

Here is the debounce circuit suggested in [Understanding Schmitt Triggers](http://www.ti.com/lit/an/scea046/scea046.pdf). Unfortunately, it doesn't behave correctly under all conditions, for reasons explained on the Ganssle page referenced later.

[![Almost, but misbehaves under out of spec conditions](https://i.stack.imgur.com/pULTP.png)](https://i.stack.imgur.com/pULTP.png)

You can fix the problem with a diode. For TTL, R1 = 82kΩ, R2 = 18kΩ, C = 1µF

[![robust](https://i.stack.imgur.com/Mdiua.png)](https://i.stack.imgur.com/Mdiua.png)

Larger values of C will absorb slower bounces. One of my projects has a relay that bounces for so long I needed 470µF.

[Here's what I regard as the last word on the subject — the Ganssle page.](http://www.ganssle.com/debouncing-pt2.htm) There's even a solution for multiple buttons on a single input. This is not quite the same as multiple buttons on a single interrupt but I think the approach may be applicable.

Note that on the Ganssle page a software solution is touted as cheaper than hardware. That's irrelevant for a one-off, true for mid sized runs and potentially false for mass produced items. Debugging software has its own costs and so does product recall. Make your decision in context. Arduino projects are usually one-off.

One objection to a hardware solution is cost, in assembly time, component count and board size. For hobby work that's a personal choice, and for commercial work it's a trade-off between simplicity and reliability. Reliability of *software* hinges on deterministic behaviour and the management of complexity. The Atmel chip doesn't have a *lot* of DRAM or program space, and moving this problem out of the software will make it smaller, simpler and more predictable.

That's not to say there aren't *other* ways to deal with the problem.

If you really want to do it in software you need to measure the pulse width and compare it to a threshold. Since you need both falling and rising edges for this, bind to CHANGE and test for state. The primary difference between this and the Kuhn method mentioned by others is it uses the clock instead of a counter allowing you to specify millisecond duration rather than iterations.

In the excerpt below, the `listen` flag is a simple alternative to noInterrupt() or unbinding the handler. My loop code evaluates a state machine transition function for current state and inputs, and not all states want input.

```
void isr_change()
{
    if (listen)
    {
        unsigned long now = millis();
        int d2 = digitalRead(2);
        if (d2 == LOW || fall_time == 0)
        { // FALLING
            fall_time = now;
        }
        if (d2 == HIGH)
        { // RISING
            command_pending = now - fall_time > MIN_PULSE_MS;
        }
    }
}

```

The state machine doesn't look at digital inputs, it looks at the `command_pending` flag, which is reset after the transition function finishes.

This is one of those things that looks simple, isn't, but does have a stock solution. It beats me why there isn't a mass produced debouncer component the way you can get op-amps.

Thank you to kaay in comments for referring me to the MC14490 which is a DIP16 or SOIC16 with six diode protected debouncers. Kaay thinks it's expensive but consider the cost of the time to code and debug debounce of six inputs. What about the cost when the program doesn't quite fit and you have to rewrite it to shrink it? And then regression test *everything*. Would you pay someone $5 for an instant guaranteed result that doesn't complicate or bloat your software? The economics change with production scale of course, but in very small runs I think it's well worthwhile.

I found the MC14490 DIP16 for 5USD and the SOIC for 9AUD online. Local shops didn't carry it.
Upvotes: 2


<issue_start>username_0: I want to have a switch, that when on, will grab an analog number and essentially "freeze" it. Similarly to how STO> works on a TI83. What should I be using? Excuse my lack of technical terms, I'm not sure what to search and therefore do not know what to use. Thank you :)<issue_comment>username_1: You could use [EEPROM](https://www.arduino.cc/en/Tutorial/EEPROMWrite) on the Arduino. For example:

```
#include

int valAddr = 0;

#define analogPin 0
#define buttPin 3
void setup() {
 pinMode(buttPin,INPUT);
}

void loop() {
 /\*\*\*
 Need to divide by 4 because analog inputs range from
 0 to 1023 and each byte of the EEPROM can only hold a
 value from 0 to 255.
 \*\*\*/
 if(digitalRead(buttPin)){
 int val = analogRead(analogPin) / 4;
 EEPROM.write(valAddr, val);
 //access this value again by using int newvalue = EEPROM.read(valAddr)\*4;

 }
}

```

By using EEPROM your value will be stored in non-volatile memory, meaning it will stay in memory even after a power cycle which is similar to how `STO>` works.
Upvotes: 0 <issue_comment>username_2: Only read the analogue pin if the button is pressed.

```
#define analogPin 0
#define buttPin 3

int analogVal = 0;

void setup() {
  pinMode(buttPin,INPUT);
}

void loop() {
    // You can do stuff here

    // If the button is pressed...
    if (digitalRead(buttPin)
    {
        // ..read the analogue pin
        analogVal = analogRead(analogPin) / 4;
    }

    // You can do stuff here
}

```
Upvotes: 0 <issue_comment>username_3: My recommendation:

1. Configure an external interrupt on the raising edges of the input where the button/switch is wired. Note that only pins 2 and 3 of Uno are capable of external interrupts.
2. Write a very simple ISR that just sets to `True` a global `volatile` variable (a flag to signal that the button/switch has been actuated) and does nothing else.
3. In the `loop()` check if the flag variable has been changed by the interrupt. If that's the case, then:

	* Debounce/deglitch the button/switch (optional, but highly recommended).
	* Read the analog input of your choice and store its value or do whatever you want to do with it.
	* Reset the flag variable to `False` so it can be changed the next time the interrupt is fired.
Upvotes: 1 <issue_comment>username_4: Here's a simple way of tracking the switch and managing the bit of state you need to manage:

```
int analogPin = 0;
int switchPin = 3;
int switched = 0; // the last-known state of the switch
int lastRead = 0; // the last-desired analog sample

void setup() {
  pinMode(switchPin, INPUT_PULLUP); // connect switch to switchPin+GND w/o resistors
}

void loop() {

  if(digitalRead(switchPin)){ // switch on:
    if(!switched){ // switch on, but was unknown
      lastRead = analogRead(analogPin); // the wanted leading-edge value
      switched = 1; // seen it on
    }//end if switch changed?
  }else{ // switch off:
    if(switched) switched = 0;      //  remember that switch is off
    lastRead = analogRead(analogPin); // the latest value
  }

  Serial.println("Value is " + String(lastRead));
  delay(500);
}

```
Upvotes: 0 <issue_comment>username_5: Read the analog input and store it, continuously. If the switch is off, also write the value to the "freeze" value:

```
void loop(){
   int value, freeze;

   value = analogRead(ANALOGPIN);
   if( !digitalRead(SWITCHPIN) ){
      freeze = value;   // sw is off, upd freeze value
   }
}

```

This doesn't take into account possible bouncing of the switch. That may or may not matter depending on the actual rate of sampling the analog input and what you intend to do with the frozen output, as the switch bouncing will be shorter than human perception but long enough (10s of msec, perhaps) for the MCU to notice and react to changes.
Upvotes: 0 <issue_comment>username_6: >
> it will continuously read my analog input.
>
>
>

easy:

1. have the adc in free running mode and in the isr writes the adc value to a buffer.
2. watch the state of the button in an isr. if it changes, save the buffer value to something else.

there are simpler ways of doing it but less real time than that. need to watch out for atomicity if a multi-byte value is involved.
Upvotes: 0


<issue_start>username_0: I tried to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data. While posting the data I'm getting the error response while initializing the server using the command:

```
{("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path")}

```

I don't know what the error is and how to fix it. Please help me to fix this.

```
#include

SoftwareSerial client(2,3);

String testReading="{ \"testID\" : 1, \"testLevel\" : 1, }";

void setup() {
 Serial.begin(9600);
 client.begin(9600);
 delay(1000);
 if(client.available()) {
 Serial.print("Connected");
 } else {
 Serial.print("Not Connected");
 }
 checkSignal();
 connectGPRS();
 postData();
 delay(1000);
}

void loop() {
 if(client.available()) {
 checkSignal();
 connectGPRS();
 postData();
 delay(1000);
 }
}

void connectGPRS() {
 client.println("AT+CGATT?");
 delay(1000);
 ShowSerialData();
 client.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
 delay(1000);
 ShowSerialData();
 client.println("AT+SAPBR=3,1,\"APN\",\"www\"");
 //Using Indian Standard Vodafone Sim and so APN is www
 delay(1000);
 ShowSerialData();

 client.println("AT+SAPBR=1,1");
 delay(1000);
 ShowSerialData();

 client.println("AT+SAPBR=2,1");
 delay(1000);
 ShowSerialData();
}

void checkSignal() {
 client.println("AT+CSQ");
 delay(1000);
 ShowSerialData();
}

void ShowSerialData() {
 while(client.available()!=0)
 Serial.write(client.read());
}

void postData() {
 client.println("AT+HTTPINIT");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPPARA=\"CID\",1");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPPARA=\"CONTENT\",\"application/json");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPDATA=99,10000");
 delay(1000);
 ShowSerialData;

 client.println(testReading);
 delay(1000);
 ShowSerialData;

 client.println("AT+HTTPACTION=1");
 delay(10000);
 while(!client.available());
 ShowSerialData();
}

```<issue_comment>username_1: Hi all use this code below for establishing HTTP connection with the server. And to neglect the 601 or 504 error use proper posting format. Here I'm using JSON format. I just gave manual data. Ignore those errors in HTTPINIT, AT+SAPBR=2,1. The data will be posted to the server

```
 #include

SoftwareSerial client(2,3);

String reading="{ \" : 1, \"latitude\" : 12.983027, \"longitude\" : 80.2594, \"timestamp\" : 100, }";

void setup()
{
 Serial.begin(9600);
 client.begin(9600);
 delay(500);

 if(client.available())
 {
 Serial.print("Connected");
 }
 else
 {
 Serial.print("NotConnected");
 }

 //initSIM();
 connectGPRS();
 connectHTTP();
}

void loop()
{

}

void connectGPRS()
{
 client.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
 delay(1000);
 ShowSerialData();

 client.println("AT+SAPBR=3,1,\"APN\",\"www\"");//APN
 delay(1000);
 ShowSerialData();

 client.println("AT+SAPBR=1,1");
 delay(1000);
 ShowSerialData();

 client.println("AT+SAPBR=2,1");
 delay(1000);
 ShowSerialData();
}

void connectHTTP()
{
 client.println("AT+HTTPINIT");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPPARA=\"CID\",1");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPPARA=\"URL\",\"http://xxx.xxx.xx/Listener/\"");//Public server IP address
 client.println("AT+HTTPPARA=\"URL\",\"http://testServer/Listener/\"");//Public server address
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
 delay(1000);
 ShowSerialData();

 client.println(reading);
 delay(1000);
 ShowSerialData;

 client.println("AT+HTTPACTION=1");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPREAD");
 delay(1000);
 ShowSerialData();

 client.println("AT+HTTPTERM");
 delay(1000);
 ShowSerialData;
}

void ShowSerialData()
{
 while(client.available()!=0)
 {
 Serial.write(client.read());
 delay(100);
 }
}

```
Upvotes: 2 <issue_comment>username_2: ```
client.println(reading);
delay(1000);
ShowSerialData;

```

The above line of code would result in an error.
Upvotes: 1


<issue_start>username_0: I have an arduino mega 2560 and I'm trying to program it using Arduino IDE 1.8.1. The problem is that I also need to keep open another program that will communicate with the Arduino using the COM port. I usually have to make very small changes to the code with the IDE and then check the results in the program.

However, when the IDE has finished uploading the program it will not release the COM port, and the program I'm using will give me an error message saying "access denied". This is a problem because I want to keep both programs open at the same time.

In fact I could just: make my correction to the code, close the IDE when it has finished, open the program I need, check whether the correction I made was right, otherwise close it again and open the IDE again, but that would take an insane amount of time and it would be quite annoying.

Is there a way to force the Arduino IDE to release the COM port so that other programs could communicate with the Aduino?<issue_comment>username_1: This type of problem happens many time with me. Try to disconnect your ARDUINO MEGA from your PC / LAPTOP and then connect it again. It must be solve your problem. If this will not work then restart your PC / LAPTOP and try it out again.
Upvotes: 0 <issue_comment>username_2: To force the Arduino IDE to disconnect from the COM port, simply go into the Tools menu, go to Ports and select another COM port.

Alternatively, you can open and then close the serial port monitor (Ctrl+Shift+M then Alt+F4).
Upvotes: 1


<issue_start>username_0: I'm trying out computer to computer serial communication using 2 Arduino Unos (both connected to different computers).
Right now, I use the Software Serial library, which redirects data from the SoftwareSerial ports to the hardware Serial (over USB to the PC).

Is there any way to bypass the 328p chip, and only use the 16U2, which works as a USB to Serial converter?
Will the circuit in the diagram work? By connecting the GND to RST on both the Unos, the 328p gets disabled, which in theory should all me to directly tap into the serial line of the 16U2.

[![Circuit](https://i.stack.imgur.com/yTuir.png)](https://i.stack.imgur.com/yTuir.png)<issue_comment>username_1: As per your diagram, ground the reset pin on both Arduinos and connect TX to RX on the one to RX to TX on the other. Alternatively, if your Unos have a socketed 328P, you can remove it.

(This answer summarized from the comments above in order to take it off the "unanswered" list.)
Upvotes: 1 <issue_comment>username_2: The circuit you have drawn will work for PC to PC coms. Essentially your connection diagram looks like this:

`PC1` -(USB)- `Arduino1` -(TTL serial)- `Arduino2` -(USB)- `PC2`

To answer your second question, you can bypass the 328p chip by removing them both as they are not needed. The 16U2 converts the USB to TTL serial which it provides to the Arduino on pins 0 and 1. Since the ATmega328p microcontrollers aren't being used (ie in reset state) then you may as well remove them and use them on another project.
Upvotes: 0


<issue_start>username_0: I need to know the times when an LED strip turns on and turns off. The LED switch is driven by light dependent resistor. When the sun goes down the LED strip turns on. This is all happening on a circuit that I did not create nor is it Arduino driven. I need to know the times (in local time) that the LED turns on and off. I have another light dependent resistor near the LED strip and I am using the Arduino Uno to print to the serial monitor its state every second.
I can listen to the serial port via Python and record the seconds via Python. No worries
What I would like to do is have the Arduino code print to the serial monitor only if the state of the LED changes. For example, when the LDR turns on the LED strip, Arduino prints to the serial monitor once, then in the morning when the LED goes off, print to the serial monitor once. I am having trouble figuring out the code to do that. The LDR is not like a button since it is always reporting back analog data. Any help is appreciated.<issue_comment>username_1: If you have already set the resistor to print to `Serial` every second, then it is simple to modify. Your code is probably like this:

```
void loop() {
// something something
Serial.println(analogRead(resistorPin));
// other other
}

```

and you want something like this:

```
int lastValue,newValue;
int treshold=200; // or some other empirical value,
// analogRead() returns 0..1024, so it should be safely inside
void loop() {
// something something
newValue=analogRead(resistorPin);
if (newValue-lastValue > treshold) {
    Serial.print("Value increased to ");
    Serial.println(newValue);
    lastValue=newValue;
    };
if (lastValue-newValue > treshold) {
    Serial.print("Value decreased to ");
    Serial.println(newValue);
    lastValue=newValue;
    };
// other other
}

```

the `treshold` value should be set so the event is triggered if substantial change in value happend (so probably those LEDs went on/of) but not trigger when there is a smal change (like cloud going on sky).

Eventually you can also print the time, at which the event happened, using something like <http://playground.arduino.cc/Code/DateTime> or <http://playground.arduino.cc/Code/Time> or any other library suiting your needs. You may also consider to use some real time module like <https://www.pololu.com/product/2770> or <https://www.adafruit.com/product/264> or <https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/overview> or any other RTC module you like/have.
Upvotes: 0 <issue_comment>username_2: You wrote: “*I am using the Arduino Uno to print to the serial monitor
its state every second.*” This is exactly the right thing to do. Make a
record of the analog readings for a few days, then plot the readings as
a function of time.

Once you have a nice plot, take a close look at it. You should be able,
by reading the plot, to decide on a threshold value that you can use to
tell whether the LEDs are on or off. Or, better yet, two thresholds in
order to have some hysteresis.

Then you can write something like this:

```
const uint8_t LDR_PIN = ...;
const uint16_t THRESHOLD_LOW = ...;
const uint16_t THRESHOLD_HIGH = ...;

uint8_t state = LOW;

void loop()
{
    uint16_t reading = analogRead(LDR_PIN);
    if (state == LOW && reading >= THRESHOLD_HIGH) {
        Serial.println("Reading is now HIGH.");
        state = HIGH;
    } else if (state == HIGH && reading < THRESHOLD_LOW) {
        Serial.println("Reading is now LOW.");
        state = LOW;
    }
}

```
Upvotes: 2 <issue_comment>username_3: An LDR doesn't have a "state", being a resistor that varies continuously, and inversely with the light intensity. The LED strip has distinct states: lit and not lit. It sounds like you want your code to deduce the LED state from the sensor value. You'll need to define lighting states based on the the LDR readings, and those readings won't be consistent; they'll vary from measurement to measurement of the same lighting conditions and they'll be affected by changes in the ambient lighting. If you can exclude ambient light falling on the LDR, the job will be easier. @Edgar\_Bonet described a way to ranges of LDR readings corresponding to 'lit' and 'not lit'

When a moving average of LDR readings, or some number of consecutive LDR readings falls within the range contrary to the state your code been keeping for the LED lighting, it should change the state and print.

If ambient lighting changes are unavoidably affecting the LDR, you'll definitely need to keep some sort of moving average and watch for a large difference between a small number of averaged readings and the longer-term moving average used to correct for ambient. This is a kind of auto-zeroing and it can lead to its own errors: sensing the room lights being turned on or off, cloud shadows, or a person or animal passage throwing a shadow, can all cause false change-of-state detection.

Update:

I'd add that you might compare the LDR output to 3 ranges: [0 - MAXDARK], [MINLIGHT - 1023], and "neither" - the gray zone in between. This is analogous to how the digital input-pin receivers in the MUC decide whether a digital signal (which is inherently analog) is HIGH or LOW. You'll have to experiment with the values of MAXDARK and MINLIGHT to find the right values for your environment.

Then you you'd print, once, whenever the LDR signal solidly enters either the MAXDARK or MINLIGHT zones, and not again until after the signal has solidly exited that zone, or equivalently, solidly entered the gray zone.

"Solidly" is probably something like NCONSECUTIVE averaged samples. Again, you'll have to find a value for NCONSECUTIVE that is both reliable and responsive. Too low a value may give you several time-stamps for the same event; too high a value will delay how quickly you detect the event (which might be totally irrelevant for a twice-a-day event).
Upvotes: 0 <issue_comment>username_4: >
> I need to know the times (in local time) that the LED turns on and off. .. I am having trouble figuring out the code to do that.
>
>
>

simple.

1. attach a pin to the circuit's output that turn on / off the led.
2. set up your arduino to read the state or state changes of that pin. this can be done via interrupts or polling.
3. based on the state of the pin, determine if the led is on or off, and record the current time.

step #1 can be done with light sensors (on the led's light output). but that can be slightly trickier.

>
> The LDR is not like a button since it is always reporting back analog data.
>
>
>

you can set up the ldr to read it like a button.
Upvotes: 0


<issue_start>username_0: Actually I am facing a big problem while programming my atmega328p using an arduino uno as ISP.
I followed a video on youtube "Arduino as ISP" by Notes and Volts. Which look doing the same steps that the majority followed. For the blinking LED sketch the µC worked very well and it did not show any troubles.
So I decided to carry on , and at this point I needed to upload a new program but this i wanted to upload my program using "avrdude" command line because my code was written with MikroC pro for avr, and here is the command line :

`"avrdude -p atmega328p -b 19200 -C arduino -P COM7 -U lfuse:w:0xf7:m -U
 hfuse:w:0xc9:m -U efuse:w:0xff:m -U flash:w:LED.hex:i "`

But unfortunately it did not work well and I have got the following error :

`avrdude : invalid byte value  specified for immediate mode
 avrdude : write to file 'ff' failed
 avrdude : safemode : Fuses OK`

Seeing that error paniced me , that's why I decided to retry the programmation with an arduino sketch and then happened the big issue when the arduino generate an error message about finding a bad microcontroller [error about the device signature] [![PIC](https://i.stack.imgur.com/0LFor.png)][2](https://i.stack.imgur.com/0LFor.png).
My last try to find out if I ruined my µC is with switching the µCs; the arduino original and the one that I had to program and unfortunately It was not a good result :
"avrdude : stk500\_recv() : programmer is not responding
 avrdude : stk500\_getsync() attempt 1 of 10 : not in sync : resp=0x85" [![PIC](https://i.stack.imgur.com/bdXCI.png)](https://i.stack.imgur.com/bdXCI.png)
Looking for more than day on the internet and I could not find a valid solution , except the possibility that I really BURNT my µC and I have to buy another one. And this is specifically why I am asking for your help; I need to know if SO could figure this trouble out.Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .
Thank you
Regards<issue_comment>username_1: >
> What if I have burnt my atmega328p?
>
>
>

get a new one.

>
> Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .
>
>
>

based on the information you have provided, no one can tell definitively. you could have changed the fuse settings, or your 2nd chip didn't have the bootloader, or bad connection, ....

a better approach is to get a separate programmer - usbasp for low prices, or dragon (older debugger with hv programming capability) and go from there.
Upvotes: 1 <issue_comment>username_2: Trying your fuse settings on an
[AVR fuse calculator](http://www.engbedded.com/fusecalc/) shows that you
have selected an “external full-swing crystal” as the clock source.
Now your ATmega won't work unless you connect it to an external crystal.
Or you could try just sending a square wave into the XTAL1 pin. *Then*
you can try to reprogram it.
Upvotes: 2 <issue_comment>username_3: after two days of searching on internet, I decided to just reburn the bootloader again on my target µC to discover if it's really burned or not.
SO, I guess it was not damaged because I was able to burn the bootloader and upload the blink led sketch successfully.
Upvotes: 2


<issue_start>username_0: I want to control flow level on 12V water pump with PWM pin, I'm using IRF520N MOSFET for that (and dedicated 12V power supply).

I'm assuming, that setting PWM to full byte should give me about 100% or 12V. But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%? Is it some logharitmic equation?<issue_comment>username_1: >
> But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%?
>
>
>

1. look at the pump's datasheet; and
2. experiment.
Upvotes: 1 <issue_comment>username_2: Expanding on username_1's answer, if the pump datasheet does not feature a graph, then you will have to experiment. If a flowmeter is not readily available, an excellent approximation can be calculated by pumping water into a large, known receptacle (e.g. 10 litre bucket) and timing how long it takes. Do this for 20%, 40%, 60%, 80% and 100% Pulse Width Modulation modes, and you will have a plot of flow rate vs PWM that will help you interpolate the PWM required for a desired flow rate (e.g. 50% flow rate).

Below is an example of Rotations Per Minute of a 12V computer CPU cooler water pump for a given PWM input. It is assumed that this would be under load (of pumping water), but not stated explicitly.

Note that it may not be physically possible for the motor to operate with 10% or less PWM duty cycle. At this point I imagine that the internal friction of the motor and forces required to push the water along are greater than the force provided by a "10%" duty cycle.

[![enter image description here](https://i.stack.imgur.com/9z6nn.jpg)](https://i.stack.imgur.com/9z6nn.jpg)

Source: [ekwb](https://www.ekwb.com/shop/ek-d5-pwm-motor-12v-dc-pwm-pump-motor)
Upvotes: 2 <issue_comment>username_3: You'll need to tun the pump at some number of intermediate PWM values and measure its output at each one. The more intermediate values you measure, the more precise your control can be. Then you build a table of flow-rates vs. PWM level in flow-rate order, something like:

```
struct {
  float flow;  // measured flow rate
  float pwm;   // pwm value that gave that rate
} FlowTable[FLOWTESTS] = {
 // flow  PWM
  {   0.,    0. },
  { 218.,  256. },
  { 480.,  512. },
  { 732.,  768. },
  { 885., 1023. }
}

```

For a particular flow-rate, step through the table until you find a flow in the table that is >= to the flow you want (if it's ==, just use that PWM and you're done.)

We'll interpolate between the two table values that span the desired flow-rate. The idea is, if your desired flow is say, 17% (0.17) of the way between those two flows, you want a PWM value that's about 17% of the way between the two PWM values.

Let's say you want a flow of 600 (in whatever units your measurements are in - cc/minute, for example. Index 3 in the table (remember, our arrays are 0-based) has the first measured flow greater than 600, the desired flow, so we know the required PWM will be between 512 and 768. To find it, find the desired flow as a fraction of the interval [480, 732]:

`frac = (600-480)/(732-480) = 120 / 252 = 0.476`,

or letting 'i' be the index of the first table entry whose flow exceeds the desired flow:

`frac = (flow_des-FlowTable[i-1].flow) / (FlowTable[i].flow-FlowTable[i-1].flow);`

. We need the PWM that is 47.6% of the interval [512, 768]:

`pwm_req = 512 + ((768-512) * 0.476)) = 634`
or

' pwm\_req = FlowTable[i-1].pwm + ((FlowTable[i].pwm-FlowTable[i-1].pwm) \* frac);`
Upvotes: 1


<issue_start>username_0: I've a little problem, I'm trying to create a library with processor variables for tune it.

So in `.ino` I declared my preprocessor var, but preprocessor variables appear not defined in my library. (Notice that I've create a folder `test/test.h` in `libraries` directory of Arduino IDE)

Some code to reproduce the problem :

**test.ino** :

```
#define TEST

#include "test.h"

void setup() {}
void loop() {}

```

**test.h** (edited, reverse error message, this is solution)

```
#if defined(TEST)
  #error "DEFINED"
#else
  #error "NOT DEFINED"
#endif

```

If I compile it, I fall on `#error "NOT DEFINED"`.

Somebody with an idea ?

Have a good day<issue_comment>username_1: It may be the way you are initializing the motor shield object.
Try doing:

```
RobotBase::RobotBase() : AFMS() {
     myMotorM1 = AFMS.getMotor(1);
     myMotorM2 = AFMS.getMotor(2);
     myMotorM3 = AFMS.getMotor(3);
     myMotorM4 = AFMS.getMotor(4);
}

```
Upvotes: 1 <issue_comment>username_2: Hey Guy's As I suspected it was actually an easy fix after leaving it alone for a couple of days came back with fresh eyes and saw the problem straight away. I had failed to start the MotorController board. So all that was needed was the begin function call `base->AFMS.begin();` in the setup of robot.ino, all working fine now.
Thanks again for your help.
Upvotes: 1 [selected_answer]


<issue_start>username_0: So I'm trying to connect the chip with an 8-bit data bus. All works good, but...

Arduino Uno uses D0 and D1 for serial TX/RX (USB connection with PC). When I try to open a serial connection (on serial.begin stage) ports D0 and D1 blocks and the chip stops working. This is a problem.

I think I should relocate pins D0 and D1 to another port. But the chip uses 8 pins (8bit chip). So I need to relocate the first pin (D0) and the second pin (D1) to port b. Maybe I can use B4 and B3?

But I don't know how to use PORTD[PD2, PD3, PD4, PD5, PD6, PD7] and PORTB[PB4, PB3] in one time like:

```
var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
portX = data;

```

My code:

```
#include  // For I/O and other AVR registers
#include  // For timing

/\* Pinmap (Arduino UNO compatible) \*/
#define YM\_IC (5) // PC5 (= pin A5 for Arduino UNO)
#define YM\_CS (4) // PC4 (= pin A4 for Arduino UNO)
#define YM\_WR (3) // PC3 (= pin A3 for Arduino UNO)
#define YM\_RD (2) // PC2 (= pin A2 for Arduino UNO)
#define YM\_A0 (1) // PC1 (= pin A1 for Arduino UNO)
#define YM\_A1 (0) // PC0 (= pin A0 for Arduino UNO)
#define YM\_CTRL\_DDR DDRC
#define YM\_CTRL\_PORT PORTC
#define YM\_DATA\_DDR DDRD

#define YD0 (0)(= pin D0 for Arduino UNO)
#define YD1 (1)(= pin D1 for Arduino UNO)
#define YD2 (2)(= pin D2 for Arduino UNO)
#define YD3 (3)(= pin D3 for Arduino UNO)
#define YD4 (4)(= pin D4 for Arduino UNO)
#define YD5 (5)(= pin D5 for Arduino UNO)
#define YD6 (6)(= pin D6 for Arduino UNO)
#define YD7 (7)(= pin D7 for Arduino UNO)

#define YM\_DATA\_PORT PORTD // Whole PORT D for data bus (= pins D0 to D7 for Arduino UNO)
#define YM\_MCLOCK (1) // PB1 = OC1A (= pin D9 for Arduino UNO)
#define YM\_MCLOCK\_DDR DDRB

extern uint8\_t chflash[6];
uint8\_t dacflash;
#define NOTEONFLASH 4
#define VGMWAIT 15

static void write\_ym(uint8\_t data) {
 YM\_CTRL\_PORT &= ~\_BV(YM\_CS); // CS LOW
 YM\_DATA\_PORT = data;
 \_delay\_us(1);
 YM\_CTRL\_PORT &= ~\_BV(YM\_WR); // Write data
 \_delay\_us(5);
 YM\_CTRL\_PORT |= \_BV(YM\_WR);
 \_delay\_us(5);
 YM\_CTRL\_PORT |= \_BV(YM\_CS); // CS HIGH
}

/\*\*
 \* Write data into a specific register of the YM2612
 \*
 \* @author Furrtek
 \* @param reg Destination register address
 \* @param data Data to write
 \*/
static void setreg(uint8\_t reg, uint8\_t data) {
 YM\_CTRL\_PORT &= ~\_BV(YM\_A0); // A0 low (select register)
 write\_ym(reg);
 YM\_CTRL\_PORT |= \_BV(YM\_A0); // A0 high (write register)
 write\_ym(data);
}

void call() {
 setreg(0x28, 0xF0); // Key on
 \_delay\_ms(1000);
 setreg(0x28, 0x00); // Key off
}

uint8\_t getfilebyte() {
 return Serial.read();
}

int main() {
 init();

 //Serial.begin(9600);
 /\* Pins setup \*/
 YM\_CTRL\_DDR |= \_BV(YM\_IC) | \_BV(YM\_CS) | \_BV(YM\_WR) | \_BV(YM\_RD) | \_BV(YM\_A0) | \_BV(YM\_A1);
 YM\_DATA\_DDR |= \_BV(YD0) | \_BV(YD1) | \_BV(YD2) | \_BV(YD3) | \_BV(YD4) | \_BV(YD5) | \_BV(YD6) | \_BV(YD7);
 YM\_MCLOCK\_DDR |= \_BV(YM\_MCLOCK);
 YM\_CTRL\_PORT |= \_BV(YM\_IC) | \_BV(YM\_CS) | \_BV(YM\_WR) | \_BV(YM\_RD); /\* IC, CS, WR and RD HIGH by default \*/
 YM\_CTRL\_PORT &= ~(\_BV(YM\_A0) | \_BV(YM\_A1)); /\* A0 and A1 LOW by default \*/

 /\* F\_CPU / 2 clock generation \*/
 TCCR1A = \_BV(COM1A0); /\* Toggle OCA1 on compare match \*/
 TCCR1B = \_BV(WGM12) | \_BV(CS10); /\* CTC mode with prescaler /1 \*/
 TCCR1C = 0; /\* Flag reset \*/
 TCNT1 = 0; /\* Counter reset \*/
 OCR1A = 0; /\* Divide base clock by two \*/

 /\* Reset YM2612 \*/
 YM\_CTRL\_PORT &= ~\_BV(YM\_IC);
 \_delay\_ms(10);
 YM\_CTRL\_PORT |= \_BV(YM\_IC);
 \_delay\_ms(10);

 /\* YM2612 Test code \*/
 setreg(0x22, 0x00); // LFO off
 setreg(0x27, 0x00); // Note off (channel 0)
 setreg(0x28, 0x01); // Note off (channel 1)
 setreg(0x28, 0x02); // Note off (channel 2)
 setreg(0x28, 0x04); // Note off (channel 3)
 setreg(0x28, 0x05); // Note off (channel 4)
 setreg(0x28, 0x06); // Note off (channel 5)
 setreg(0x2B, 0x00); // DAC off
 setreg(0x30, 0x71); //
 setreg(0x34, 0x0D); //
 setreg(0x38, 0x33); //
 setreg(0x3C, 0x01); // DT1/MUL
 setreg(0x40, 0x23); //
 setreg(0x44, 0x2D); //
 setreg(0x48, 0x26); //
 setreg(0x4C, 0x00); // Total level
 setreg(0x50, 0x5F); //
 setreg(0x54, 0x99); //
 setreg(0x58, 0x5F); //
 setreg(0x5C, 0x94); // RS/AR
 setreg(0x60, 0x05); //
 setreg(0x64, 0x05); //
 setreg(0x68, 0x05); //
 setreg(0x6C, 0x07); // AM/D1R
 setreg(0x70, 0x02); //
 setreg(0x74, 0x02); //
 setreg(0x78, 0x02); //
 setreg(0x7C, 0x02); // D2R
 setreg(0x80, 0x11); //
 setreg(0x84, 0x11); //
 setreg(0x88, 0x11); //
 setreg(0x8C, 0xA6); // D1L/RR
 setreg(0x90, 0x00); //
 setreg(0x94, 0x00); //
 setreg(0x98, 0x00); //
 setreg(0x9C, 0x00); // Proprietary
 setreg(0xB0, 0x32); // Feedback/algorithm
 setreg(0xB4, 0xC0); // Both speakers on
 setreg(0x28, 0x00); // Key off
 setreg(0xA4, 0x22); //
 setreg(0xA0, 0x69); // Set frequency

 call();

 while(1000) {
 if (Serial.available() > 0) {
 \_delay\_ms(1000);
 call();
 \_delay\_ms(1000);
 char var = getfilebyte();
 Serial.print("Yeah: ");
 Serial.println(var);
 } else {
 Serial.print("Nooo: ");
 Serial.println(Serial.available());
 call();
 }
 }
 while(1);
}

```<issue_comment>username_1: You cannot set pin states in multiple ports simultaneously, if that's what you're asking.

At the instruction set level, setting pin states is a single that writes to an 8-bit register which corresponds to the 8 pins in a port. There is no way to write to two different registers in the same instruction, so if you need all eight bits to change exactly at the same time you're out of luck. However, if you can tolerate a little bit of time between 6 bits in one port changing state and 2 bits in another port changing state, then you can simply write a wrapper function.

```
PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
void set_ym_ctrl_port(uint8_t data) {
    PORTD &= ~(0x3f<<2);
    PORTB &= ~(0x3<<3);
    PORTD |= (data & (0x3f<<2));
    PORTB |= (data & 0x3)<<3;
}

```

Or something like that. If you need even less delay and you think you can do better than the compiler, inline assembly can be helpful.

As an aside, syntax like

```
var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];

```

is not valid for a number of reasons.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Adding to what @uint128\_t said, if you really need to change the state of many pins at the same time, you can add some external latched shift registers as a SIPO (serial-in/parallel-out) interface towards the outer world.

The price you pay is that you have to load the entire register with the data you want to send before you can update the output pin states. This requires a clock cycle for each loaded bit (here I'm speaking of the clock of the external register, not Arduino's) and thus may add too much latency in your system, depending on what you are trying to do.

The 74HC595 is a classic (8-bit shift register with output latches), and can be cascaded to obtain a register of the desired width.

Here is an excerpt from [the datasheet of TI's 74HC595](http://www.ti.com/lit/ds/symlink/sn74hc595.pdf) (yellow emphasis mine):

>
>
>  [![enter image description here](https://i.stack.imgur.com/FXZuH.png)](https://i.stack.imgur.com/FXZuH.png)
>
>
>
>

It's also sold in 16-pin DIP package, very convenient for breadboarding, in case you need it (common need for people that play with Arduinos).

The internal logic diagram is the following (from the same datasheet):

>
>
>  [![enter image description here](https://i.stack.imgur.com/VymKA.png)](https://i.stack.imgur.com/VymKA.png)
>
>
>
>

It is so common in the Arduino world that there are also open libraries do drive it, for example [this](https://playground.arduino.cc/Code/ShiftRegister595). But even without pre-written libraries, it is not difficult to drive it from an Arduino, if you have a little experience in digital logic and can understand the timing requirements stated in its datasheet (the table in section 7.6 is fairly easy to understand, once you know what setup and hold times are).
Upvotes: 2 <issue_comment>username_3: This is intended as a complement to uint128\_t's answer. I would like to
point out that the code in that answer changes the outputs in four
steps:

1. set to `LOW` the pins of `PORTD` that need to be `LOW`
2. set to `LOW` the pins of `PORTB` that need to be `LOW`
3. set to `HIGH` the pins of `PORTD` that need to be `HIGH`
4. set to `HIGH` the pins of `PORTB` that need to be `HIGH`

I compiled it on my system (with gcc 5.4.0): the generated assembly
shows that the whole process takes 18 CPU cycles. I.e. during
1.125 µs the outputs can be in an inconsistent state.

I then tried this alternative version:

```
void set_ym_ctrl_port(uint8_t data) {
    uint8_t new_portd = PORTD & ~(0x3f<<2) | (data & (0x3f<<2)),
            new_portb = PORTB & ~(0x03<<3) | (data & 0x03)<<3;
    cli();
    PORTD = new_portd;
    PORTB = new_portb;
    sei();
}

```

This changes the outputs on two steps:

1. update `PORTD`
2. update `PORTB`

The generated assembly showed that the updates are only one CPU cycle
apart. I.e. the outputs are inconsistent during only 62.5 ns.

Your mileage may vary. In case of doubt check the generated assembly.
Upvotes: 0


<issue_start>username_0: i want to operate a relay with an ARDUINO UNO, but i want to use a separate power supply for the relay. Ive seen relays with VCC and jVCC (dont know what that is), but mine only has this pins: GND, IN1, IN2, VCC.
how should i connect it to the Arduino and the external power supply?
[![enter image description here](https://i.stack.imgur.com/s3dUm.jpg)](https://i.stack.imgur.com/s3dUm.jpg)<issue_comment>username_1: External psu to gnd and vcc, in1 and in2 to arduino pins which control each relay (on is LOW) and most importantly gnd also to arduino gnd.
Upvotes: 0 <issue_comment>username_2: The Arduino and the external PSU should have the GND or - connected with each other.

Then connect the external PSU + or Vcc to the relay boards Vcc.
Upvotes: 1 <issue_comment>username_3: This relay is designed to operate on 5V.

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

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

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

---

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

---

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

---

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

---

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

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

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

```
Upvotes: 2


<issue_start>username_0: Solution:
=========

Majenko properly pointed out that I was trying to write across page boundaries and either overwriting or skipping blocks of the EEPROM when I did. This updated write function checks for a page boundary and splits the write into two writes if it is going to write over one.

```
void writeEEPROMPage(long eeAddress)    {
  int writes = incr;
  bool overflow = false;

  //check for page overrun, adjust writes to fill page and set flag if overrun
  if((eeAddress % 128 + incr) > 127)    {
    writes = 128 - eeAddress % 128;
    overflow = true;
  }
  Wire.beginTransmission(EEPROM_ADR);

  Wire.write((int)(eeAddress >> 8)); // MSB
  Wire.write((int)(eeAddress & 0xFF)); // LSB
  //Write bytes to EEPROM
  Wire.write(rwBuffer, writes); //Write the data
  Wire.endTransmission(); //Send stop condition
  eeAddress += writes;

  if(overflow)  {
    delay(5);
    Wire.beginTransmission(EEPROM_ADR);

    Wire.write((int)(eeAddress >> 8)); // MSB
    Wire.write((int)(eeAddress & 0xFF)); // LSB

    //Write remaining data to new page
    Wire.write(rwBuffer + writes, incr - writes);

    Wire.endTransmission();
    eeAddress += incr - writes;
  }
}

```

Problem:
========

I am currently working on a project to record sensor readings to a 24FC512 512kb I2C EEPROM and have been teaching myself to read and write properly to this chip using an Arduino Uno. I am having a problem: when I write too many bytes in one I2C cycle, some bytes of data are skipped and not written.

In theory, I believe I should be able to write up to a 128-byte page to the EEPROM and the buffer in the Arduino Wire library should allow me to write up to 32 bytes (including address) in one transmission without modification. However, when I write more than a certain number of bytes, typically 16, and then read back the data from the EEPROM, I notice that the write commands seem to have skipped part of the write.

For instance, when trying to clear pages of 20 bytes at a time using 0xF0 to fill the space I get this result in the first few lines in blocks of 20:

```
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88
+12 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  55  66  77  88  99  AA  BB  CC
+12 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  99  AA  BB  CC  DD  EE  FF  00
+5 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88

```

The section that has not been cleared matches the original pattern in that location. When I reduce the page size to 16 bytes, the problem goes away and everything is written correctly. The uncleared pattern is also periodic after the first three lines, running 12 lines, error, 12 lines, error, 5 lines, error for the rest of the data. When tried with 30 bytes per transmission, it's periodic by 3-8-3 when organized in lines of 30. In all cases the errors have been at the end of each page of transmission.

This has become very frustrating because I'd like to get the data written to the EEPROM in as little time as possible so I can get a good sensor sample rate (currently 24 bytes per sample) and have time to run other functions. Ideally I'd be able to write every 5 ms to increase the sampling rate to the maximum supported by the EEPROM, so I need to solve this problem.

Here is the code I am using to clear and read the contents of the EEPROM. The variable incr holds the size of the writes I want to make, and pin 12 decides whether the program will read the EEPROM (high) or clear the EEPROM (low). I write data to the EEPROM with the commented out array to run my tests. It is based on example programs for EEPROM from Sparkfun.

```
#include

#define EEPROM\_ADR 0x54

const int incr = 30;
byte rwBuffer[] = {
 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0
};

void setup() {
 pinMode(13, OUTPUT);
 pinMode(12, INPUT);
 Wire.begin();
 Wire.setClock(400000);
 long currentSpot = 0;
 if (digitalRead(12)) {
 dumpEEPROM();
 } else {
 while (currentSpot < 64000) {
 writeEEPROMPage(currentSpot);
 currentSpot += incr;
 delay(7);
 }
 }
}

void loop() {
 digitalWrite(13, !digitalRead(13));
 delay(500);
}

void writeEEPROMPage(long eeAddress) {
 Wire.beginTransmission(EEPROM\_ADR);
 Wire.write((int)(eeAddress >> 8)); // MSB
 Wire.write((int)(eeAddress & 0xFF)); // LSB
 //Write bytes to EEPROM
 Wire.write(rwBuffer, incr); //Write the data
 Wire.endTransmission(); //Send stop condition
}

void dumpEEPROM() {
 long i;
 int j, readnum, timer = 0;
 Serial.begin(115200);
 timer = millis();
 for (i = 0 ; i < 64000 ; i += incr) {
 //Read all bytes from EERPOM
 readnum = readToBuffer(i);
 for (j = 0; j < incr; j++) {
 if (rwBuffer[j] < 0x10)
 Serial.print("0");
 Serial.print(rwBuffer[j], HEX);
 Serial.print(" ");
 }
 Serial.println();
 }
 timer = millis() - timer;
 Serial.print("Full data dump took ");
 Serial.print((float)timer / 1000, 3);
 Serial.println(" seconds.");
 Serial.end();
}

int readToBuffer(long address) {
 int i = 0;
 Wire.beginTransmission(EEPROM\_ADR);
 Wire.write((int)(address >> 8)); // MSB
 Wire.write((int)(address & 0xFF)); // LSB
 Wire.endTransmission();
 Wire.requestFrom(EEPROM\_ADR, incr);
 for (i = 0; i < incr && Wire.available(); i++) {
 rwBuffer[i] = Wire.read();
 }
 return i;
}

```<issue_comment>username_1: The arduino is a "small memory" device. So it probably does not have a big serial buffer. On say "linux on a PC" you get a 4096 byte buffer, but on an arduino, probably only say 16. Now as luck will have it "+CMGR: "REC READ" is precisely 16 characters....

From the code that I see, you seem to be sending commands to the modem and then reading/echoing them. I would have liked to use two different serial ports or something like that.

In any case, if it sort of works for those first 16 characters, remove all the delays and put one of them near the end of the loop() function. Remove the initial print to the modem in the setup function.
Upvotes: 1 <issue_comment>username_2: I changed the code. so It works fine

```
String inputString = "";         // a String to hold incoming data
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
}

void loop() {

  Serial.println("AT+CMGR=1");

}

void serialEvent() {
    inputString = Serial.readString();
    Serial.println(inputString);
    delay(5000);
  }

```
Upvotes: 1 [selected_answer]


<issue_start>username_0: I made a counter to count pulses:

```cpp
int count  = 0 ;
.
.
.
setup()
{
}

while (count <= 35000)
{
  digitalWrite(9, HIGH);
  delayMicroseconds(500);
  digitalWrite(9, LOW);

  count = count + 1;
}

```

But when I try `while(count <= 40000)`, it does not stop counting.<issue_comment>username_1: `int` in AVR GCC is [16 bits](https://gcc.gnu.org/wiki/avr-gcc#Type_Layout). ***All*** possible `int` values are less than 32767.
Upvotes: 3 <issue_comment>username_2: >
> But when I try while(count <= 40000), it does not stop counting.
>
>
>

"int" has a range from -32k to +32k-1. so "count <= 40000" will always be true as count is "int".
Upvotes: 0 <issue_comment>username_3: You have reached the maximum number that an `int` can represent. That is **32767**.

`int` is a variable type that is made up of **16 bits**. It is **signed**, meaning that it can represent positive and negative numbers.

Out of the **65536** (ie. **2^16**) possible numbers from the 16 bits, half of them represent negative numbers and the remaining half represents positive numbers (including zero). Or in other words, **-32768 to 32767**.

If you don't need negative numbers, then you can change your variable type to `unsigned int` which will use numbers up to a maximum of **65535**. So it becomes:

```
unsigned int count = 0;

```
Upvotes: 2


<issue_start>username_0: I am not very experienced with Arduino and I am trying to learn it. I was wondering what is the easiest and most effective way to calculate speed and log it every second so to say. This would be mounted in a model rocket to see what speeds it can reach. How would I achieve this?

Would it be hard to send over RF to see it in real time?

Thanks in Advance<issue_comment>username_1: Quite different questions, but you need two items:

* A gyroscope/accellerometer, I don't think this should be a problem. You need to check beforehand if the Arduino is fast enough, since a rocket acceleration is probably very high.
* An RF transceiver, there are several types which work over big distances, but I don't have experience while they move fast. Maybe radio signals might get distorted, but for that hopefully someone has a better answer. Probably you cannot use a (big) external antenna which extends outside the rocket.
Upvotes: 0 <issue_comment>username_2: You can use an [accelerometer](https://diyhacking.com/arduino-mpu-6050-imu-sensor-tutorial/) or a [barometre](http://arduinolearning.com/code/bmp180-barometric-pressure-sensor-example.php) for measure speed and for RF you can use:

* [Radio NRF24L01](http://howtomechatronics.com/tutorials/arduino/arduino-wireless-communication-nrf24l01-tutorial/)
* [wifi ESP8266](http://www.instructables.com/id/Quick-Start-to-Nodemcu-ESP8266-on-Arduino-IDE/)
* [bluetooth HC-06](https://create.arduino.cc/projecthub/user206876468/arduino-bluetooth-basic-tutorial-d8b737)
Upvotes: 1


<issue_start>username_0: I'm doing my project regarding 40khz ultrasonic sensor which will be used to get accurate distance measurements. I have a separate transmitter and receiver. I want to get the time between the moment my transmitter transmitted the waves and the time my receiver received it. However, I couldn't actually make it work. Does any of you give me a code that would help me transmit and receive the 40khz waves and get the time in between so I could use it to compute for the distance?Thank you in advance. I would greatly appreciate it!<issue_comment>username_1: I don't have 'a code', but what you can do is using a timer set to 40 kHz and send the pulses you need. .

If nothing else needs to be done (nor in the future) you can use a delay function.

Also check the pulseIn function from Arduino, you can use this convenience function for the checking the result.
Upvotes: 0 <issue_comment>username_2: This is the most basic ultrasound pulse and receive code. I wrote it to work with the `HC-SR04` modules; so hopefully it will work fro you too as those also sound at `40khz`.

The main functionality comes from the [`pulseIn()`](https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/) funciton.

```
#define TRIGPIN 9
#define ECHOPIN 10

void setup() {
  Serial.begin(9600);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(ECHOPIN, INPUT);
}

void loop() {
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);

  uint16_t duration = pulseIn(ECHOPIN, HIGH, 4000);
  int distance = (duration*.0343)/2;
  Serial.println(distance);
}

```

---

Note that you will need to adjust the `4000` (`μs`) to whatever timeout in you want (or emit entirely if you don't want it).
Upvotes: 1


<issue_start>username_0: Before bothering anybody, I've been Googling this issue for the last three weeks and have not been able to solve the issue, so must reach out for help.

My son has done multiple Arduino projects after having a Creation Crate subscription, and now we're working on a project together. We bought a 28BYJ-48 stepper with driver, and figured it'd be just a question of copy-and-paste coding and we'd be in business.

I've tried the Arduino library, the AccelStepper library, countless other sketches from various websites and for some reason the stepper only vibrates when it's supposed to turn CCW. There was one sketch we were using that used Serial Monitor to enter in the number of steps, and when i'd do a minus number of steps, it'd go CCW, but the next day no longer would! I thought this was a motor or driver issue, but we've bought three more motor/drivers and still have the same problem. In researching an answer, I've seen some people say to switch IN 3 & 4 but I still get same results.

We've been connecting 8 to IN1, 9 to IN2, 10 to IN3 and 11 to IN4. Using a separate 5V power supply to the driver which is also grounded to the Arduino (have tried both ground pins just in case that makes a difference, but no). We've also tried changing for another Arduino and this hasn't made a difference either.

we've tried multiple sketches from multiple sources, here's one as an example:

```
#include

const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
 // set the speed at 60 rpm:
 myStepper.setSpeed(60);
 // initialize the serial port:
 Serial.begin(9600);
}

void loop() {
 // step one revolution in one direction:
 Serial.println("clockwise");
 myStepper.step(stepsPerRevolution);
 delay(500);

 // step one revolution in the other direction:
 Serial.println("counterclockwise");
 myStepper.step(-stepsPerRevolution);
 delay(500);
}

```

The Serial Monitor will state that it's turning CCW, but it isn't. Any help would be much appreciated! What we thought would be a simple step in our project has become a major roadblock!<issue_comment>username_1: I had this issue myself, when I tried to use these stepper motors (which are to be honest really crappy ones, but very cheap). Vibrating mostly means, that the phases of the motor are not activated in the correct order. These motors seem to work with an activation pattern for half steps (I don't know, if the motor is really doing half steps with this, because I didn't counted them for a whole revolution. But at least they worked). The [Stepper library](https://github.com/arduino-libraries/Stepper) (I assume from your code, that you are using this one) isn't meant for this driver, so it will turn on the phases in a wrong order and always two phases at the same time (as for full steps).

I had success, when driving the 4 phases of the driver with the following pattern (for half steps):

```
1000
1100
0100
0110
0010
0011
0001
1001

```

I also found hints on the web (on a [german site](https://blog.thesen.eu/es-geht-doch-schrittmotor-28byj-48-mit-der-original-arduino-stepper-library/), just for reference, if you can read german), that - despite being meant for half steps - you can drive the motor with full steps with the Stepper library as well. You would have to change the order of pins in the definition of the stepper:

```
Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

```

This assumes the wiring as: D8->IN1, D9->IN2, D10->IN3, D11->IN4. Note, that using full steps means 2048 steps per revolution.

---

I also found a library specific for this stepper motor, but I haven't tested it: [Stepper\_28BYJ\_48](https://github.com/thomasfredericks/Stepper_28BYJ_48)

---

Now you can decide yourself, which way you want to go. I personally would go for the full steps with the official Arduino Stepper library.

---

About the number of steps per revolution: I don't know, why the stepper doesn't work with a vale of 2048. But since the library only uses this to wrap up the correct phases for the revolutions, you can use a lower value, that is dividable by 4. For example 32, which is the number of full steps per revolution of the actual motor (it is attached to gears with a factor of 64). That should work.
Upvotes: 2 <issue_comment>username_2: <https://forum.arduino.cc/index.php?topic=549927.0>

This guy just flipped IN2 and IN3 and it solved the problem of going forwards and backwards. It worked for me and here is the code.

```
#include  // Include the header file

// change this to the number of steps on your motor
#define STEPS 64

// create an instance of the stepper class using the steps and pins
Stepper stepper(STEPS, 8, 10, 9, 11);

int Pval = 0;
int potVal = 0;

void setup() {
 Serial.begin(9600);
 stepper.setSpeed(200);
}

void loop() {

potVal = map(analogRead(A0),0,1024,0,100);
if (potVal>Pval)
 stepper.step(10);
if (potVal
```
Upvotes: 1


<issue_start>username_0: I am sending strings to an Esp8266 via web browser.

The below code returns the following in serial monitor if I send in browser:

Send from browser to esp8266 - <http://192.168.1.220/s1s2s3s4s5d1>

Receive in Arduino Serial monitor - GET /s1s2s3s4s5d2 HTTP/1.1

How do i read only the contents s1s2s3s4s5d1 ? This content can vary in length, numbers could be double digits but alphabets will remain in between.

Please note I am still a novice.

```cpp
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

```<issue_comment>username_1: I have this

```
if (client.connected()) {
  if (client.available() && client.find(' ')) { // GET /fn HTTP/1.1
    char fn[20];
    int l = client.readBytesUntil(' ', fn, sizeof(fn));
    fn[l] = 0;
    while (client.read() != -1);
    Serial.println(fn);
    client.stop();
  }
}

```
Upvotes: 1 <issue_comment>username_2: you can try something like this

```
int first_space = request.indexOf(' '); // location of the first space
int second_space = request.indexOf(' ', first_space); // the next space after first

String query_arg = request.substring(first_space,second_space);

```
Upvotes: 0