text:
Ethernet Shield 2 data to PHP server doesn't work
I am trying to send data via GET to my PHP server from my Ethernet Shield2.
This is part of my sketch:
char myserver[] = "www.myserver.com/";
if (client.connect(myserver, 80)) {
  Serial.print("Connected to ");
  Serial.println(myserver);
  client.print("GET /arduino/controller.php?");
  client.print("air_temp=");
  client.print(DS18B20_temperature);
  client.println(" HTTP/1.1");
  client.print("Host: ");
  client.println(myserver);
  client.println("Connection: close");
  client.println();
  client.println();
} else {
  // if you didn't get a connection to the server:
  Serial.println("Connection failed to Server");
}

The serial monitor displays "Connect to myserver.com" but my PHP code doesn't seem to receive the air_temp value from DS18B20_temperature. I checked this value and it's true.
However, when I try myserver.com/arduino/controller.php?air_temp=25 in my browser, the PHP code is running well.
What's going wrong with my code?

Try changing char myserver[] = "www.myserver.com/"; to char myserver[] = "www.myserver.com"; (so without tailing slash)

Hi, I changed the line with char myserver[] = "www.myserver.com"; and now the serial monitor send "Connection failed to Server".  :(

There shouldn't be a slash in the Host header. So create a second variable, without the slash and use that one in line behind Host...

Why create another variable ? Theproblem is that my shield does not connect to my server, Why ?

Apparently client.connect needs the slash at the end, while Host:  required no slash at the end.

When I try Shield Exemple with www.google.com (without slash) it's works!

Don't forget the client close else it will not work after 4 requests

I just removed the line server.begin() and it's works !!!
Thanks.

authors: ازاد صابر فتاح


text:
Powering Arduino Uno from 5V pin, what exactly is the voltage range/tolerance?
I want to bypass the onboard regulator and use the 5V pin to feed arduino with external, regulated source.
Everybody just keeps saying regulated 5V, but how precise does the regulation need to be exactly? Can you state a voltage range and what makes you think so?
10 ways to destroy arduino, Method #5: Apply >5V to the 5V Connector Pin mentions "applying more than 6V", can anyone elaborate how it can be calculated?
Is there a higher spike that arduino can handle for a short period of time?
My concern is that the current draw from arduino might be under 60mA (right after switching power on and before the program initilizes and starts running), which is the lowest draw at which my source guarantees the 5V regulation --- when unloaded it gives out 6.5V. How could I resolve this better than putting a 60mA dummy load between the regulator and arduino itself?

Ditto on https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/ - The one thing I don't see in your question is precisely why you would want to bypass the internal regulator?  That could help guide more-specific answers.

Unfortunately there is no one "clear cut" answer for all you ask.
There are some hard limits, though, which you can get from the main chip's datasheet:

Operating Voltage: 1.8 - 5.5V

But that's not the whole story. The minimum voltage depends on the clock speed of the chip, as shown in this graph:

But wait, there's more. The Arduino also contains a 3.3V regulator which is fed from the 5V supply. That will have a minimum voltage above 3.3V that it needs to maintain a 3.3V output. So if you want to use the 3.3V regulator then, according to the datasheet for the regulator (LP2985-33DVBR):

3 Description
  The LP2985-N low noise linear (LDO) regulator delivers up to 150mA output current and only requires 300mV dropout voltage of input to output.

So a minimum of 3.3 + 0.3V, or 3.6V.
That gives you a usable range, clock frequency permitting, of 3.6V to 5.5V.
As to how to protect the Arduino from a power-on spike like you describe - you could:

Add your own extra regulation in the form of a 5.1V zener diode.
Add a dummy load which the Arduino can switch out of the circuit once booted up
Change your source to something with better regulation
Ignore it - the regulation with even a light load will be considerably better than open circuit.  Add a resistor across your supply that would draw much less than 60mA and measure the voltage. See how bad the regulation at low load is.

I am more worried about the top limits rather than underpowering, but it's interesting thought, I didn't generally expect that low voltage could break stuff too.

According to the datasheet the absolute maximum is 6V - above that and you will kill it. The "safe" maximum though is 5.5V, above which they don't guarantee it will keep working reliably for any sustained period of time.

Can too low voltage damage components too? Or will they just stop working until the mimimal required voltage is supplied.

It depends on what else they are wired to. In general you just get stability problems. In some situations, though, such as when you have a 5V signal feeding into a chip that is being under-powered, you may get physical damage from over-voltage on the input.

Too low a voltage can make the micro controller brown-out and do funny things. It might jump to anywhere in the code. So it could theoretically set pins that are meant to be inputs, to output, and cause damage that way. Though the ATMega on the arduino has brown-out detection. So unless you specifically disable it, this isn't a problem.

Ad protection by zener diode: Do I need to carefully select a diode that would be able to conduct all arduino might need (~200mA?), while operating below the actual breakdown voltage (5V, maybe 4.9V, not exactly the 5.1V)? Do I need to care about characteristics of the "knee region", or can we simplify the situation by saying that most of the diodes would be fine for the purpose?

You want a zener reverse polarity across the supply with a small resistor in series between the supply and the zener (the Arduino is powered from the join between the two). The resistor is to limit the current through the zener and drop the voltage between the supply voltage and the zener voltage. http://www.electronics-tutorials.ws/diode/diode_7.html

The 6.5V is too much. I have had an ATtiny chip which seems to run fine after applying 8V to it. But how can I be sure that it is okay ? There are so many parts in the chip die that can be damaged.
There has been a few broken voltage regulators reported, when applying 5V to the 5V pin of an Arduino Uno. The reverse diode inside the voltage regulator might not keep up with a large current peak. In some of my projects I power an Arduino via the 5V pin. I have added an extra diode 1N4007 from 5V to VIN, to save the voltage regulator, and my 5V power is not very strong.
I also don't apply that 5V while it is on. It is from a DC/DC converter that is part of the project. So when I turn on the power, the 5V raises not too fast, and there is no high current peak.
When applying 5V to the 5V pin, the current can flow into the computer via the usb cable. The polyfuse of 500mA on the Arduino board will prevent most troubles, but it could damage the computer. When I turn off my computer with that project connected, I do indeed see an increase of the current to my project. My computer is luckely not broken (yet).

Most decent 5V supplies (e.g. USB chargers) are within 5% of 5V. I use these all the time to power directly to the 5V pin. There has never been an issue with this. I don't use supplies outside 5% for this. Check with your multimeter first.

You don't say why you want this information, but there are others who are trying to do similar.  (Starting with NOT destroying their Arduino)
For instance, at the end of the article
10 Ways to Destroy An Arduino
is a reference (broken link in the article) to
The Ruggeduino
which might be more suitable to your requirements.
Here is an excerpt of its specs:

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Why do the LEDs visibly flicker?
The aim of the project was to be able to show two "kinds" of LEDs in a 8x8 single color LED matrix. I used a MAX7219 chip to drive the LEDs using my Arduino UNO R3 as the driver (with the usual connections).
Despite the frequency of the blackupdate() function being near to a 100Hz, why do I see the LEDs corresponding to currentblack() flickering? 100Hz is much beyond the resolution of the eye, as I understand it. The multiplexing frequency of the MAX7219 chip is also much beyond resolution (800Hz). Why do the "white" LEDs not flicker?
Here's the code with Serial.println() added for debugging:
int DataPin = 2; // Pin 1 on MAX
int LoadPin = 3; // Pin 12 on MAX
int ClockPin = 4; // Pin 13 on MAX
int currentwhite[8]={B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000};
int currentblack[8]={B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000};

#define SCAN_LIMIT_REG 0x0B
#define DECODE_MODE_REG 0x09
#define SHUTDOWN_REG 0x0C
#define INTENSITY_REG 0x0A
#define DISPLAY_CHECK_REG 0x0F

void setup() {
  pinMode(DataPin, OUTPUT);
  pinMode(LoadPin, OUTPUT);
  pinMode(ClockPin, OUTPUT);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, SCAN_LIMIT_REG); // scan limit set to 0:7
  shiftOut(DataPin, ClockPin, MSBFIRST, B00000111);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, DECODE_MODE_REG);
  shiftOut(DataPin, ClockPin, MSBFIRST, B00000000);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, SHUTDOWN_REG);
  shiftOut(DataPin, ClockPin, MSBFIRST,  B00000001);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, DISPLAY_CHECK_REG);
  shiftOut(DataPin, ClockPin, MSBFIRST, B00000000);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
  shiftOut(DataPin, ClockPin, MSBFIRST, 0);
  digitalWrite(LoadPin, HIGH);
  Serial.begin(9600);

  currentblack[3]=B00001000;
  currentblack[4]=B00010000;
  currentwhite[3]=B00010000;
  currentwhite[4]=B00001000;
}

void blackupdate() {
  digitalWrite(LoadPin, LOW);
    shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
    shiftOut(DataPin, ClockPin, MSBFIRST, 0);
    digitalWrite(LoadPin, HIGH);
  for (byte row=0; row<8; row++){
    digitalWrite(LoadPin, LOW);
    shiftOut(DataPin, ClockPin, MSBFIRST, row+1);
    shiftOut(DataPin, ClockPin, MSBFIRST, (currentblack[row]));
    digitalWrite(LoadPin, HIGH);
  }
}

void whiteupdate() {
  digitalWrite(LoadPin, LOW);
    shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
    shiftOut(DataPin, ClockPin, MSBFIRST, 15);
    digitalWrite(LoadPin, HIGH);
  for (byte row=0; row<8; row++){
    digitalWrite(LoadPin, LOW);
    shiftOut(DataPin, ClockPin, MSBFIRST, row+1);
    shiftOut(DataPin, ClockPin, MSBFIRST, (currentwhite[row]));
    digitalWrite(LoadPin, HIGH);
  }
}

void loop() {
  Serial.print("A");
  Serial.println(millis());
  blackupdate();
  Serial.print("B");
  Serial.println(millis());
  whiteupdate();
  delay(5);
  Serial.print("C");
  Serial.println(millis());
}

And the Serial output was as follows:
A1
B3
C10
A10
B12
C19
A19
B21
C28
A28
B30
C37
A37
B39
C47
A47
B49
C56
A56
B59
C65
A66
B68
C75
A75
B77
C84
A84
B87
C94
A94
B96
C105
A105
B112
C123
A123
B131
C142
A143
B150
C161
A161
B168
C180
A180
B187
C198
A198
B205
C217
A218
B225
C236
A236
B243
C254
A254
B262
C273
A274
B281
C292
A292
B300
C311
A311
B318
C329
A329
B336
C348
A349
B356
C367
A367
B374
C386
A386
B393
C404
A404
B412
C422
A423
B431
C442
A442
B449
C460
A460
B467
C479
A480
B487
C498
A498
B505
C517
A517
B524
C535
A535
B542
C553
A555
B562
C573
A573
B580
C591
A591
B599
C610
A611
B618
C629
A629
B636
C648
A648
B655
C666
A666
B673
C685
A686
B693
C704
A704
B711
C722
A722
B730
C741

You're trying to implement two different brightness's for each led. I think the problem is that the update rate of the MAX7219 and the update rate of your Arduino code are not in sync, causing some variations in the brightness. Also you are setting the brightness of the MAX7219 to max, before updating the pixel data, which would cause the 'black' pixels from being a lot brighter for a short while. I'd move the first 4 lines in whiteupdate to the end of the function. PS you only need to do digitalWrite(LoadPin, LOW);...;digitalWrite(LoadPin, HIGH); once per function. No need to do this 9x.

I tried putting the intensity function at the end of the fuction, but it changed nothing. Even if the black LEDs are bright for a while, the entire function takes only 2 milliseconds to happen, so shouldn't be visible. Can you expand on what you mean by the two devices not being in sync?

Wouldn't we need to latch the data by putting the loadpin to high every time? Otherwise the data would simply be outputted through the Dout pin?

The max7219 updates the display at around 800hz. Your code updates the display data around 100hz. But not exactly. So ideally the max would multiplex every column 8 times between every update. But is it's slightly slower, it might have done the last column only 7 times. Which would make it less bright.

But then the entire black set invariably flickers irrespective of the position.

The hardware setup isn't clear. For example, do you have two matrix's or one? In any event, the effect of black update() stays on much shorter than the effect of white update() due to the delay inserted in the main loop.

One matrix. And I agree, but the functions still cycle at a very high frequency, and should be indistinguishable by eye. Only the average should be visible, right?

The pattern of white update is briefly interrupted by the pattern of blaackkuodate. That's the flickering you see. You can test this by commenting out one of the patterns. The MCU ISS doing what your code wants it to Do. What do you want your code to do?

I see only the blackupdated LEDs flickering. If the interrupts were a problem, the whiteupdated LEDs should flicker, right?

The white leds are probably too bright to see them flicker.

You are correct that this is updating at about 100 Hz. The clue is in the serial output:
A1
B3  <<
C10 <<
A10
B12 <<
C19 <<
A19
B21 <<
C28 <<
A28
B30 <<
C37 <<
A37

There is always a big gap between the ms reading between B and C. This is due to the delay in after the whiteupdate().
void loop() {
    Serial.print("A");
    Serial.println(millis());
    blackupdate();
    Serial.print("B");
    Serial.println(millis());
    whiteupdate();
    delay(5);    // <-- DELAY HERE
    Serial.print("C");
    Serial.println(millis());
}

There is no update between the blackupdate() and the whiteupdate(), so even though 5ms is just on the border of what your eyes can determine, due to the repeating pattern and persistence of vision, your eyes do notice it.
You will find that your flicker will dissapear if you split the delay so you have an equal delay between your blackupdate()->whiteupdate() and whiteupdate()->blackupdate().
void loop() {
    Serial.print("A");
    Serial.println(millis());
    blackupdate();
    delay(2);    // <-- DELAY HERE
    Serial.print("B");
    Serial.println(millis());
    whiteupdate();
    delay(2);    // <-- DELAY HERE
    Serial.print("C");
    Serial.println(millis());
}

Removing the serial debug lines give you:
void loop() {
    blackupdate();
    delay(2);
    whiteupdate();
    delay(2);
}

I tried doing that. I still found the LEDs flickering. I set both the delays at delay(10).

There may be some more physiology at work here, too. Did you notice the flickering while staring fixedly at one LED, or while looking around your project area ("scanning" as it were, with your eyes)? If you scan your vision past a flickering LED, even one that flickers at a rate beyond our perception, you can see a streak of dots cross your vision, where a steadily lit one would make a solid streak. I noticed it driving at night, when LED tail-lights were still new and unusual. Those cars stood out because their tail-lights left the same trail of dots across my vision (although some people have told me they do not see this phenomenon or aren't aware of it...).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Problem with receiving data from Arduino via HC05 sent by Java
I want to both send some sensor data via Bluetooth (HC05) and Arduino to Java and I also want to send some command data via the same Bluetooth and serial port to Arduino.
I've managed to do the first part (arduino to java) successfully with this code:
hc05SerialEx.printf("^%d,%7.3f,%d,%7.3f,%d,%7.3f\n", s1, ss1, s2, ss2, s3, ss3);

^ is the character I devised in my simple protocol and it means the starting point of data.
@ means starting point of command packet.
The problem is whenever I want to write a char packet via the same HC05 connection to arduino, it sometimes works. In fact, whenever I click the button firing the write method, I see the packet received correctly but when I click the button again or click it rapidly, it sometimes outputs garbage in arduino side.
I do have delay in my main loop in arduino side and I'm using it to control the sampling rate of sensors. I've timed arduino side's calculation time (except delay of course) and it takes about 52 milliseconds.
I suspect whenever I fire the write method while arduino is busy in main loop, the received data becomes gibberish. So here are the questions:
1- What is the cause of this problem?
2- How can I achieve the goal I mentioned?
Here is java-side code sending the command packet:
String message = String.format("@%5.3f,%5.3f,%5.3f\n", rmR1, rmR2, rmR3);
System.out.println(message);
rightHC05Port.write(message);

Here is arduino-side code receiving and mirroring the received packet in arduino's own serial port (for me to see):
void loop() {
  serialEventHC05();
  //fetching sensor data and some math operations...
  hc05SerialEx.printf("^%d,%7.3f,%d,%7.3f,%d,%7.3f\n", s1, ss1, s2, ss2, s3, ss3);
  delay(loopTime);

int numOfReceivedBytes = 0;

void serialEventHC05() {
  while (hc05Serial.available() > 0) {
    numOfReceivedBytes = hc05Serial.available();
    String s = hc05Serial.readStringUntil('\n');
    arduinoSerialEx.println(numOfReceivedBytes);
    if (s.charAt(0) == '@') {
      arduinoSerialEx.println(s);
    }
  }
}

For example, here is the string I'm sending from Java via HC05 to Arduino:
@10.000,10.000,10.000

And here is the result of Arduino's behavior caused by me sending the same packet multiple times:

Any help is appreciated.

could you please provide the complete code of your project, so I can check in detail?
(Both java code and arduino code)

Thanks for reply. It seems the problem was with SoftwareSerial since when I used the 0,1 RXTX the code works flawlessly. Even with AltSoftSerial the code still works.... I wonder what are the other undocumented limitations of SoftwareSerial...

Unfortunately I know nothing about undocumented limitations of SoftwareSerial. But I found an example that send command from java side to Arduino that may help you.link
But I also have problem when implementing such an issue. I can successfully receive data in arduino from java side, but I got stuck when receiving data from Arduino in java for a week of try. I would really appreciate that if you can share your experience or your code with me.

@Tony I've asked this very question here : http://forum.arduino.cc/index.php?topic=451673.0   The things I know as of yet is that SoftwareSerial can't handle "receive" in baudrates higher  than 9600. You can use AltSoftSerial but RXTX pin is fixed for each Arduino. The relevant code for communication between Arduino/Java side is exactly as I mentioned above in my post, nothing more.


text:
Delaying an action inside a function
My current function is supposed to play a sound effect, then after the sound effect is done (14 seconds), perform the next action (digitalWrite(CONTROLLINO_R1, LOW)).
if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch) {
  skeleLatch = 1;
  wTrig.trackPlayPoly(2);
  unsigned long currentMillis = millis();
  if((currentMillis-previousMillis) >= 14000) {
    digitalWrite(CONTROLLINO_R1, LOW);
    previousMillis = millis();
  }
}

As it is, it performs both at the same time. I do not know how to correctly implement the delay so that it waits.
Any help would be appreciated. Thank you.

If your program shall not do anything during 14 seconds, why not simply use delay()?

its going into an escape room - meaning, there is a good chance someone else might activate something else while that music is playing.  In the off chance, i'd like to be sure it doesn't interfere with any other inputs

You can get the current time (milliseconds since startup) using millis(). Using that you can tell whether it's been 14 seconds since a particular event.  Does that give enough of a clue?

Where do you set up previousMillis (apart from after the decision in the code you posted)?

previousMillis was set to 0 unsigned long outside loop

  unsigned long triggerMillis = 0;

  if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch)
  {
    skeleLatch = 1;
    wTrig.trackPlayPoly(2);
    triggerMillis = millis();
  }

  if (millis() - triggerMillis >=14000 && skeleLatch)
  {
    digitalWrite(CONTROLLINO_R1, LOW);
    skeleLatch = 0;
  }

This should work, depending on how long your CONTROLLINO_A8 is staying high you might want to invest some more time to set up an interrupt on that pin, to make sure you don't miss a trigger.

If your code does not need to be re-entrant (work within a multitasking environment), the simpler solution is Arduino's delay function, designed specifically for waiting a specific number of milliseconds.
delay(14000)


text:
Analog inputs on ATtiny85 don't work
I want to use a ATtiny85 to check the voltage of two 12 V batteries (later to control a relay). Therefore I'm using the analogRead() function. For programming I'm using an Arduino Mega 2560 board.
//                           +-\/-+
//  Ain0       (D  5)  PB5  1|    |8   VCC
//  Ain3       (D  3)  PB3  2|    |7   PB2  (D  2)  INT0  Ain1
//  Ain2       (D  4)  PB4  3|    |6   PB1  (D  1)        pwm1
//                     GND  4|    |5   PB0  (D  0)        pwm0
//                           +----+

For A1 this works perfectly fine. But for A2 or A3 I'm getting always a value of 15 V (thus the analog input gives 1023 respectively it thinks there is 5 V on the pin, which is not the case). I tried A0 as well, but it's the same.
For seeing the current value I put a serial - USB converter on RX, TX on PB3, PB4. So I guess they cannot work properly as analog inputs then. But still A0 does not work and without serial my LED is always on without having a voltage over 12 V.
At the moment I don't know what to do about it. No matter which of the analog pins I choose, I'm getting always a wrong value (except A1).
I'm not a hundred percent sure about A0. On some diagrams there is an A0 pin, on some not. But I tried to remove all the serial communication code and still having the LED 0 on high.
Thanks in advance!
void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  digitalWrite(0, LOW); // led for displaying the voltage
  digitalWrite(1, LOW); // blinking status led
  int sensorValue1 = 0;
  int sensorValue2 = 0;
  Serial.begin(9600);
}

void loop() {
  int sensorValue1 = analogRead(A1);
  int sensorValue2 = analogRead(A0);
  // <- the problem, A2, A3 do not work as well
  float voltage1 = sensorValue1 * (5 / 1023.00) * 3;
  float voltage2 = sensorValue2 * (5 / 1023.00) * 3;
  Serial.print(voltage1);
  Serial.print("--");
  Serial.print(voltage2);
  Serial.println();
  if ((voltage1 > 12) || (voltage2 > 12)) {
    digitalWrite(0, HIGH);
  } else {
    digitalWrite(0, LOW);
  }
  digitalWrite(1, HIGH);
  delay(1000);
  digitalWrite(1, LOW);
  delay(1000);
}

SOLUTION:
As suggested by Andrei Dragan the problem was the serial communication, which uses just the same pins as the analog inputs A2 and A3. When turned off, the problem disappeared.
As the serial communication is quite useful for me, right now I'm still using the serial communication but only with the pin for sending data. The pin for receiving data is turned off. It looks like this:
#include <SoftwareSerial.h>

#define RX    -1   // *** turned off
#define TX    4   // *** D4, Pin 3

SoftwareSerial Serial1  (RX, TX);

(I don't know if this is the best way, but it works for me.)
Once again, thanks for the help!

A0 is the reset pin. Unless you change the fuses (which you shouldn't) you can't use that pin.

Thanks for your advice! So then I have to use A2 or A3 but both are not working, do you have any idea?

So then I have to use A2 or A3 but both are not working: that contains very little information to help others help you. It is likely working but you just don't know yet.

Any type of communication protocol uses pull-up resistors (not 100% sure that all of them do but still, it's a rule of thumb) so using the serial trick on the attiny enables the internal pull-up resistors on PB3 and PB4. I can bet the ADC value is near 1023 isn't it? Disabling the serial communication should in theory fix your problem.

I though I already tested it without. But it seems as I made some mistake. After disabling the serial communication it seems to work.
Is there a way to change the serial pins to get the exact voltage via serial com?
Thank you! :)

You cannot get the ADC to work properly on the pins that the serial communication is using (that lines are going to be pulled up either by the attiny or the other thing you're trying to communicate with, in your case the usb-serial chip). In your current configuration you can't do much about it without losing some of the data you want: you can either measure both of the voltages at once with the help of 2 diodes or you can get rid of the serial communication. As an alternative you can use another chip (attiny84, which has 11 pins, 8 of which are ADCs)

At the moment I'm not sure what the final setup will look like. Originally I have not planned to use serial communication, this was more for testing purposes just as the two LED's, but I will need at least one output for controlling the relay. But I think having the exact voltage can be quite useful.
For now I have changed the serial configuration in that way so that I'm only using the TX pin (PB4) for sending the data. So I can read the exact results and using PB3 as A3 as sensor input. Everything is working now and I'm getting correct voltage values. Thank you again! :)

Yo wrote “Any type of communication protocol uses pull-up resistors”. No. I2C does use pullups, but neither SPI nor asynchronous serial does. The OP's problem has nothing to do with pullups: it's the serial ports (of the ATtiny and the one on the other end) actively driving the line to Vcc.

Take an SD card application, it's good practice to use pull-ups on the SPI line in this case because a floating line (in the order of milliseconds, until the SPI communication is initialized) can cause problems on the SD card, possibly injecting unwanted signals onto it. It's unlikely but at least one time in our life we've seen the "This media is corrupted, reformat it bla bla" message, that's where the pull-ups on the data lines come in handy, to help you avoid that.


text:
Arduino Uno Wunderground weather station - Ethernet connection failed
I'm new to Arduino. For my first project, I've decided to build a weather station where data is collected via sensors and is then sent to Wunderground. I'm using an arduino uno, an ethernet shield as well as a DHT22 sensor for temperature and humidity.
Everything worked for an hour and then I'm getting "connection Failed" constantly.
I would really appreciate it if you could look into my code. I've tried everything and it doesn't explain the sudden failure of the project. I occasionally get a successful upload after dozens of connection failed messages.
Here's my code. I've removed my weather station password for security reasons.
#include <Wire.h>
#include <SPI.h>
#include <Wire.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include "DHT.h"

// Sensor Pins
#define DHTPIN 7
#define DHTTYPE DHT22
// Variables
float temp;
float hum;

byte mac[] = {
  "de,ad,be,ef,fe,ed"
};
EthernetClient ethernetClient;
unsigned int localPort = 8888;
// Wunderground server details
char SERVER[] = "rtupdate.wunderground.com";
char WEBPAGE[] = "GET /weatherstation/updateweatherstation.php?";
char ID[] = "ICHESTER24";
char PASSWORD[] = "iwqnrlex";

DHT dht(DHTPIN, DHTTYPE);
unsigned int connections = 1;
unsigned int timeout = 30000;

void setup(void) {
  Serial.begin(38400);
  Wire.begin();
  dht.begin();

  // Connect to internet
  Serial.print(F("\nInitialising Ethernet module"));
  if (Ethernet.begin(mac)){

    Serial.println("Initialisation completed successfully!");
  }
  else {
    Serial.println("Something went wrong during ethernet module setup!");
  }
} //END OF SETUP

void loop(void) {
  hum = dht.readHumidity();
  temp = dht.readTemperature();
  float tempf = (temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
  float dewptf = (dewPoint(tempf, hum));
  Serial.println("++++++++++++++++++++++++++");
  Serial.println("temp = ");
  Serial.println(tempf);
  Serial.println("Humidity = ");
  Serial.println(hum);
  Serial.println("DewPoint = ");
  Serial.println(dewptf);
  // Send all data to WUNDERGROUND
  if (ethernetClient.connect(SERVER, 80)) {
    ethernetClient.print(WEBPAGE);
    ethernetClient.print("ID=");
    ethernetClient.print(ID);
    ethernetClient.print("&PASSWORD=");
    ethernetClient.print(PASSWORD);
    ethernetClient.print("&dateutc=");
    ethernetClient.print("now");
    ethernetClient.print("&tempf=");
    ethernetClient.print(tempf);
    ethernetClient.print("&humidity=");
    ethernetClient.print(hum);
    ethernetClient.print("&dewptf=");
    ethernetClient.print(dewptf);
       ethernetClient.print("&softwaretype=Arduino%20UNO%20version1&action=updateraw&realtime=1&rtfreq=2.5");//Rapid Fire
    ethernetClient.println();
    Serial.println("New data uploaded");
  }else{
    Serial.println("Connection Failed...");
  }
  delay(2500);

}
void resetEthernet() {
 ethernetClient.stop();
 delay(1000);
 Ethernet.begin(mac);
 delay(1000);
 ethernetClient.available();
}
double dewPoint(double tempf, double humidity)
{
  double A0= 373.15/(273.15 + tempf);
  double SUM = -7.90298 * (A0-1);
  SUM += 5.02808 * log10(A0);
  SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
  SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
  SUM += log10(1013.246);
  double VP = pow(10, SUM-3) * humidity;
  double T = log(VP/0.61078);
  return (241.88 * T) / (17.558-T);
}

I assume u used a W5100 shield. This shield is capable of having 4 connections open. If the connections are not closed for some reason the chip is unable to make another connection.
This means after sending u need to close the connection. (else it will work 4 times).
ethernetClient.stop()
Just before or after
Serial.println("New data uploaded");
https://www.arduino.cc/en/Reference/ClientStop


text:
How to have some code executed at a certain time of day with a DS3231 RTC?
I recently bought a DS3231 RTC, but I cannot seem to figure out how to get it to work. I have tried all different tutorials and example programs but I keep getting 2165.25.165 165:165:165 as the output.
I am using an Arduino Micro, with the RTC connected as follows:

GND > GND
VCC > 5V
SDA > A4
SCL > A5

Project details:
The project uses a 16x2 LCD to display the time of day, and a countdown to the next occurrence of 06:00. Then at 6 it will allow for a button to be pressed to open a servo and do other things. I got temporary test code to work using millis(), but it is only displaying a 12-hour countdown in seconds, and I would like to replace it with a more reliable RTC.

Nostradamus says the problem is with your code, but his crystal ball is a little cloudy at the moment.

Every time I got this 165:165:165 from an RTC, it turned out the RTC wasn't online -- either not powered, or not on the I2C bus for some reason.

Usual questions on wiring of an I2C device: do you use pullup resistors on SDA  and SCL signals? Note that some circuits may already integrate these, but it is hard to say without knowing the exact circuit (you provided the chip name but you probably have some breakout from Adafruit, Sparkfun... with additional components)

BTW if you want some logic to be executed at certain times, it is better to program RTC to generate alarm interrupt and process external interrupt on MCU. This way no constant polling will be needed on MCU.

Sililar to https://arduino.stackexchange.com/questions/30638/how-to-set-alarms-on-the-ds3231-easily

SDA and SDL pins on an Arduino Micro are on pins D2 and D3 as mentioned on the official page:

TWI: 2 (SDA) and 3 (SCL). Support TWI communication using the Wire library.

and shown on this pinout reference:

If you are getting 165:165:165 that indicates usually a problem with your I2C bus. But it might also be a power problem in the RTC.
In any case, check your wiring.
Your processor is simply not properly communicating with the RTC. If the RTC's red light is on then check your wiring and make sure you haven't reversed SDA and SCL.
Also, the DS3231 has and most Arduinos have enough pull-up that you won't need external pull-up resistors in order to communicate directly with the DS3231.
Try plugging it straight into the Arduino - go minimalist and make that work before adding other devices to the I2C bus like a LCD display. Set the clock by code and watch it in the serial monitor.
Once you're sure the RTC is not a problem then you can go from there with the I2C bus. It is certainly possible for other devices on the bus to cause the RTC to be unable to respond correctly. For a short-range I2C bus that includes the DS3231 don't add any external pullups.
The most reliable RTC for Arduino is the DS3231, but if you bought it via the slow boat you might try a voltmeter to verify the battery so it keeps time even when powered down.
And of course, it is only as accurate as you program it to be. When I program my DS3231s, I always add a couple of minutes to the current time to allow for the time to fix forgotten semicolons and such before it gets around to actually programming the device.
One last note: The program will run when you open the serial monitor. So that will be when it sets the time then begins to display it.

I forgot to add that the DS3231 can set alarms that trigger software interrupts.  Look up the data sheets and you'll find out how.  Here is a library that makes it easy to control them:  https://github.com/rodan/ds3231

Your question doesn't match your title so I will go with your title.

How to have some code executed at a certain time of day with a DS3231 RTC?

The typical approach is to set an alarm on the RTC (to the extent that it supports it), and process that interrupt from the RTC on the MCU side.
Alternatively, you can poll the time on the RTC periodically and once the time is up, do your thing.


text:
'MeDCMotor' does not name a type error inside mBlock
I was using a 3rd party programming enviroment, mBlock 3.4.5 for making C++ Arduino programmes with a graphical programming language. I was compiling a program and the following eroor came up.
project_Untitled0_0.ino:65:1: error: 'MeDCMotor' does not name a type
project_Untitled0_0.ino:66:1: error: 'MeDCMotor' does not name a type
project_Untitled0_0.ino: In function 'void move(int, int)':
project_Untitled0_0.ino:85:7: error: 'motor_9' was not declared in this scope
project_Untitled0_0.ino:85:24: error: 'M1' was not declared in this scope
project_Untitled0_0.ino:86:7: error: 'motor_10' was not declared in this scope
'MeDCMotor' does not name a type

I took another look at the program and there were some lines of code that seem they are added in the program by deafult:
MeDCMotor motor_9(9);
MeDCMotor motor_10(10);
void move(int direction, int speed)
{
      int leftSpeed = 0;
      int rightSpeed = 0;
      if(direction == 1){
            leftSpeed = speed;
            rightSpeed = speed;
      }else if(direction == 2){
            leftSpeed = -speed;
            rightSpeed = -speed;
      }else if(direction == 3){
            leftSpeed = -speed;
            rightSpeed = speed;
      }else if(direction == 4){
            leftSpeed = speed;
            rightSpeed = -speed;
      }
      motor_9.run((9)==M1?-(leftSpeed):(leftSpeed));
      motor_10.run((10)==M1?-(rightSpeed):(rightSpeed));
}

Since the program does not recognise the MeDCMotor class the program failed to upload.
I am running Windows 10 home edition on a 64-bit laptop.
Is there a way to remove the lines of code that prevent me from uploading the sketch or are there other ways to solve it?

Yes, just remove them, and the lines that refer to them, and so on. Of course they're there for a reason so the program won't do what it's supposed to do.  As you have correctly identified, it can't find that class.  Perhaps you're missing a #include, perhaps it's not in the library to be included. Hard to tell from the (lack of) detail in the question.

The lines of code mentioned above are dedicated toother tipes of robots, that can be programmed with the software and are useless on the Arduino. The lines of code cannot be deleted, beacause the code that is displayed is just for preview.

You're having trouble with a non-standard piece of software, and you don't even mention what it is.  Maybe you can find the files on disk somewhere and edit them there.  Otherwise, you'll have to give us a bit more of a clue, I suspect.

I looked at some entries in a google search for error: 'MeDCMotor' does not name a type, such as 1, 2, 3 and 4.  The first three of those latter four links directly address the question you ask, and none of them answer it clearly, except to suggest re-downloading or re-installing the makeblock library.  While the fourth link addresses a “does not name a type” error for another library, rather than for makeblock, it has a relatively clear explanation of the problem for that other library:

So, as supplied, the ArduinoByteBuffer.zip file had a complex set of sub-directories, and the two files ByteBuffer.ccp and ByteBuffer.h were located one level down in: \ArduinoByteBuffers\ByteBuffer\
When I 'installed' the library, it went into the directory:

C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.ccp
       C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.h

To solve the problem I moved them up a level to:

C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.ccp
       C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.h

That seemed to be the key - moving the two files (*.ccp and *.h) out of the subdirectory.

Instead of following ordinary C or C++ library-finding rules, the Arduino IDE copies sets of files into a temporary directory according to its own rules when compiling a sketch.  You'll need to move your makeblock library files around to match up with Arduino IDE conventions.

In the MakeBlock, menu "choice of extensions", uncheck all the extensions, keeping only the one called "Makeblock" checked:


text:
How to do weigh scale zeroing (tare weight)?
I'm using the sketch below for a weighing scale. The sketch prints out the load-cell voltage just fine. I can't figure out how to let the scale run a couple seconds to stabilize, then use the current voltage reading (nothing on the scale) as the "Zero" voltage. Then subtract that "Zero" voltage from future readings to get the actual voltage for any weight placed on the scale. For example, let's say the nothing on the scale voltage is 0.5 volts. Then a 10 LB weight is added and the voltage goes up to 1.5 volts. So the actual voltage increase from the weight is 1.5 minus 0.5, or 1.0 volts.
#include <ads1262.h>

const float VREF = 2.50;  // Internal reference

ads1262 PC_ADS1262;  // ADC object

void setup() {
  // initialize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
  pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
  Serial.begin(9600);

  // initialize ADS1292 slave
  PC_ADS1262.ads1262_Init();
  Serial.println("ads1262 Initialised successfully....");
}

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
                  | (uint32_t) buffer[2] << 16
                  | (uint32_t) buffer[3] <<  8
                  | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;

  // Report a smoothed-out reading.
  Serial.println(voltage, 8);
}

So you want it to wait 2 seconds and save a tare value?, and use that for adjustment of the outputs later?

You start out with a variable named Tare initialized to zero float Tare = 0.0; put in a conditional like if (millis() > 2000 & Tare == 0.0) Tare = voltage; and always report voltage - Tare.
float Tare = 0;

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;
  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
    | (uint32_t) buffer[2] << 16
    | (uint32_t) buffer[3] <<  8
    | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;
  if (millis() > 2000 & Tare == 0.0) Tare = voltage;
  // Report a smoothed-out reading.
  Serial.println(voltage-Tare, 8);
}

If you want to make it smarter, add a button for tare and maybe if you have a calibration weight, add a button for calibrating.
float scale= 1.0;
const float calib_weight = 500.0; // grams?
...
if(tareButton | (millis() > 2000 & Tare == 0.0)) Tare = voltage;
if(calibrateButton) scale = calib_weight / (voltage-Tare) ;
...
Serial.println((voltage - Tare)*scale,8);
...

The direct answer to your question is to wait for the scale to settle and store the Tare voltage; then subtract it from future readings.
But that only works if the scale's transfer function (Voltage as a function of weight, or V(f)) is linear (weight = Voltage * CONSTANT). Otherwise you need to keep the Tare in weight units, do the full conversion of voltage to weight on subsequent readings, and subtract the Tare weight from that.

Thank you for that. My main problem right now is the code itself. I'm simply a novice with the Arduino C++.  How to store a voltage after the adc has run a little bit and then name it "Tare".

You start out with a variable named Tare initialized to zero float Tare = 0.0; put in a conditional like if (millis() > 2000 & Tare == 0.0) Tare = Voltage; and always report voltage - Tare.


text:
Using millis() function to start at potentiometer reading
I am trying to use the millis() function to start a countdown of 3 seconds when I turn my potentiometer to high travel. My code so far starts the timer at the beginning of the loop or when reset is hit or when the sketch is uploaded to the board. I need the countdown to start when the potentiometer reaches high travel.
The goal of the program is that when the potentiometer reaches high travel, PumpOne starts (HIGH) and if the potentiometer does not reach low travel before 3 seconds, PumpTwo will come on (HIGH). I am trying to simulate a water tank with two pumps (LEDs in this case) and the potentiometer high and low travel representing the high and low levels of the tank respectively.
I've updated the code since the original post but the timer still starts from the beginning of the program and not when L > Plim1.
Here's the code:
int Pump1 = 3; // Declare Blue LED in pin 3 to simulate Pump 1
int Pump2 = 4; // Declare Green LED in pin 4 to simulate Pump 2
int Alarm = 2; //Delcare Red LED in pin 2 to simulate Alarm
int TDCRPot = A0; // Declare Potentiometer(TDCRPot) an int and assign to pin A0

int L; //Declare L a variable to read the High and Low
//travel of the potentiometer

float Plim1 = 1000; // pot reading for pump 1 turn on
float Plim2 = 1000; // pot reading for pump 2 turn on
float Llim = 100; //pot reading to turn both pumps off
unsigned long T; // current time
unsigned long T1 = 0; // P1  on time
boolean P1 = false;
boolean P2 = false;
boolean Alarmstate = false;
unsigned long Tlim = 3000;

void setup() {
  Serial.begin(9600); //Turn on Serial monitor for troubleshooting
  //purposes and set to 9600 baud
  pinMode(Pump1, OUTPUT); //Declare Blue LED(PumpOne) an output
  pinMode(Pump2, OUTPUT); //Declare Green LED(PumpTwo) an output
  pinMode(Alarm, OUTPUT); //Declare Red LED(Alarm) an output
  pinMode(TDCRPot, INPUT); //Declare Potentiometer(TDCRPot) an input
}

void loop() {
  L = analogRead(TDCRPot); //Read the voltage from the Potentiometer pin
  if (!P1 && L > Plim1) {
    T = millis();
    digitalWrite(Pump1, !P1);
  }
  if (Pump1 != P1 && T - T1 > Tlim && L > Plim2) {
    digitalWrite(Pump2, !P2);
  }
  if (Pump1 != P1 && L < Llim ) {
    digitalWrite(Pump1, P1);
    digitalWrite(Pump2, P2);
  }
}

The statement TDCRLevel = analogRead(TDCRPot); will almost always set TDCRLevel to a non-zero value; hence the && TDCRLevel term of your last if statement almost always is satisfied.  The only time it won't be satisfied is when TDCRLevel is exactly zero.
When TDCRLevel >= 1000 is first satisfied, it's likely to be true for some while; during that time, each pass through loop() will toggle Bluestate and set previousMillisBlue = currentMillis.  This happens many times per millisecond while TDCRLevel has a high value.  Whether Bluestate is on or off when  TDCRLevel goes below 1000 is a fairly random outcome.
To handle the process properly, set up a state machine, using either one state-number variable or several variables to maintain state.  Change states when conditions tied to state, TDCRLevel, and time are met.
More simply, something like the following might work.
loop:
  if !P1 and L > Plim1:
    Set P1; record T1
  if P1 and T-T1 > Tlim and L > Plim2:
    Set P2
  if (P1 or P2) and L < Llim:
    Turn off pumps, clear P1 and P2

where P1, P2 represent pump states; T represents current time and T1 represents time that P1 most recently turned on; L = analogRead(TDCRPot); Plim1 and 2 are pot levels for pump turnons; Llim = low level for pump turnoffs; Tlim = desired time delay before pump 2 comes on.

Edit 1:  The above is pseudocode, rather than any simulacrum of valid C or C++.  As such, you may need to add sets of parentheses and brackets, substitute meaningful variable names, etc.
Note that the constants Plim1, Plim2, Tlim, Llim should be declared via either const int declarations, or via enum {} constructs (enum declares only integer constants), if they are integers rather than floats.  For example, do like either of
const int Plim1 = 1000; // level for pump1 turnon
const int Plim2 = 1000; // level for pump2 turnon
//etc

or
enum { Plim1=1000, Plim2=1000, Tlim=3000, Llim=100};

The phrase “Set P1; record T1” corresponds to code like
P1 = true;
digitalWrite(Pump1, HIGH);
T1 = millis();

in braces.  If you don't set P1 and record T1 as current time, the process won't work.  P1 and P2 represent state variables, not constants.
The phrase “if P1 and T-T1 > Tlim and L > Plim2: Set P2” corresponds to code like
if (P1 && (T - T1 > Tlim) && (L > Plim2)) {
  P2 = true;
  digitalWrite(Pump2, HIGH);
}

The phrase “if (P1 or P2) and L < Llim: Turn off pumps, clear P1 and P2” corresponds to code like
if((P1 || P2) && (L < Llim)) {
  P1 = P2 = false;
  digitalWrite(Pump1, LOW);
  digitalWrite(Pump2, LOW);
}

I've re-edited the question, The timer should start after Plim 1* but starts at the beginning of the sketch

@AbramsM101, see edit 1


text:
How can I use my Arduino sketches on my Raspberry Pi IDE?
I have installed the Arduino IDE 2:1.0.5 on my Raspberry Pi3 under Raspbian and am using a cobbler breakout which provides a nice breadboard.  On that breadboard I have installed an Arduino Nano to do analog voltage readings, which it then communicates back to the Rpi3 via the USB serial port which shows up as /dev/ttyUSB0 on the Rpi3.
This port opens as a regular file in Python for further processing such as adding a date & time stamp (obtained by an NTP server) and saving the results to a data file that is displayed in gnuplot 4.6.

You'll notice I am using 3.3 Volts for the fan to keep it quiet, and the two wires heading up to the top go to the voltage source I am monitoring.  If you look closely you can see the voltage divider circuit.
Here is today's solar plant voltages which this thing tracks.  The block at the bottom means the inverter was on.  Green means the battery bank is full.

Anyway, it turns out that the same serial connection is supported by the Rpi Arduino IDE for programming.
Rather than programming the Nano on a laptop and constantly having to unplug/replug it on the breadboard my goal is to use Rpi Arduino IDE for programming.
So I moved all my sketches over from the Arduino IDE on the laptop to the Rpi.
But
.... then every time I start the Rpi IDE it throws error messages for all the sketches that have underscores in their names.  Turns out the Rpi version will only allow alphanumeric directory names.  I have a couple dozen sketches and this is not productive.  It requires clicking OK for every directory it skips - which turns out to be all of them.
So my question is:  What can I do about this?

Perhaps you could spell out which op sys you installed on your Raspberry Pi, and which IDE version is installed.

Just a little comment: arduino IDE version 1.0.5 is quite old.. Maybe it's worth updating to 1.8.1 (you can't use apt, though; just go on the Arduino download page and download the ARM version (I think)

Ah, I see 1.8.1 there. And yes, I had used apt-get install to do this in the first place.  Not sure I have the know-it-all to do it another way.  Meanwhile, it is working great. I love being able to reprogram my units that are outside and far away without having to bring them back in to the laptop and risk bending pins, etc. I can do updates with almost no downtime.

Obligatory XKCD: https://xkcd.com/1205/

To fix this problem I came up with the following procedure which takes out all the underscores from the directories & filenames and capitalizes each word instead.
First, I copied all my sketches and libraries (from my documents/arduino directory) to a USB flash drive.
The Rpi Arduino IDE creates a sketchbook directory upon install, so I
Copied the libraries folder to ~/sketchbook/libraries
Copied the sketches folder to ~/sketchbook/AMSsketches
Then I wrote a custom script that is copied to my home directory on the Rpi, which can be obtained here as a text file (use Chromium or wget to copy it to the file ~/AMS2Rpi)  - Here is the link:  http://calttc.net/AMS2Rpi
which contains this code:
#! /bin/bash
#
#  AMS2Rpi - Converts MS Arduino IDE Sketch names to RPI Arduino IDE Sketch names
#
#                  SDsolar      2017-01-29
#
#  Reason:    Arduino IDE on MS inserts underscore characters in file & directory names
#             Arduino IDE on Rpi rejects all but alphanumeric characters
#
#  Solution:  Remove all but alphanumeric characters
#             and capitalize each word in the names
#
#  Usage:
#    Install Raspbian Arduino IDE 2:1.0.5 on the Raspberry Pi 3
#    Use a USB flash drive to copy sketches and libraries from the MS-based Arduino IDE
#      On the Rpi, copy the libraries directory to ~/sketchbook/libraries
#      On the Rpi, copy the sketches directory to ~sketchbook/AMSsketches
#    Copy this script to your home directory as AMS2Rpi using Chromium
#    cd
#    chmod +x AMS2Rpi
#    ./AMS2Rpi    (This will take some time)
#    cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMSRpiQ
#    chmod +x ~/AMS2RpiQ
#    ~/AMS2RpiQ
#    Open the Rpi Arduino IDE
#
#  Alternatively, if you have a lot of sketches you might want to
#    change the "mv -i" below to "mv"
#    and cat it into AM2SRpiX above
#    so you don't need to answer "y" for every rename.
#
#  Props to Marco Fioretti for his article at http://www.techrepublic.com/blog/linux-and-open-source/how-to-remove-weird-characters-from-file-and-directory-names-automatically/
# ---------------------------------------------------------------------
rm -f /tmp/AMS2R*
cd $1
find .  | awk '{ print length(), $0 | "sort -n -r" }' | \
        grep -v '^1 \.$' | cut -d/ -f2- > /tmp/AMS2Rpi_1
touch /tmp/AMS2Rpi_2
while read line
  do
  BASE=`basename "$line"`
  NEWBASE=`basename "$line" | perl -e '$N = <>; chomp ($N); $N =~ s/[^a-zA-Z0-9.]//g; $N =~ s/_+/_/g; $N= lc($N); $N =~ s/_([a-z])/_.uc($1)/eg; print ucfirst($N);' `
  if [ "$BASE" != "$NEWBASE" ]
  then
  OLDPATH=$(echo "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  DIR=$(dirname "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  echo "mv -i $OLDPATH $DIR/$NEWBASE" >> /tmp/AMS2Rpi_2
  fi
done </tmp/AMS2Rpi_1
rm -f /tmp/AMS2Rpi_1
mv /tmp/AMS2Rpi_2 /tmp/AMS2Rpi
exit

Then set it to executable and run it:
cd
chmod +x AMS2Rpi
./AMS2Rpi

When it is finished, I filter out just the directory I want (VERY IMPORTANT):
cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMS2RpiQ

(You can look at that file to verify it before running it)
chmod +x ~/AMS2RpiQ
~/AMS2RpiQ

Cleanup if you wish:
rm /tmp/AMS2R*
rm ~/AMS2RpiQ

Now the Arduino IDE on the Rpi opens cleanly and all my sketches are there.
Problem solved.   It works great.

This reminds me of a programmers' joke I read some time ago, which said "a programmer is someone who takes one month to develop a program which automates a one hour task" ;)

That's pretty good.  I would only add that the retired ones are the worst.  ;-)

Turns out there are two easier answers if you are willing to do it manually.
You can use the Windows-based IDE to load each sketch then save them with an allowable name, before transferring them.
So, instead of going through the program, just do it by hand - this is best if you don't have too many, or if you are very patient.
Or jump in with both feet:  use your USB flash drive to just move your libraries and sketches to the appropriate directories under sketchbook.
libraries go to ~/sketchbook/libraries
sketches go to ~/sketchbook/sketches
Go into the IDE preferences and tell it to look into ~/sketchbook/sketches

Manually rename any directories in both directories so they only have alphanumeric characters in the subdirectory names
The Rpi version of the Arduino IDE has no problem with filenames with underscores.  It is just the directories it rejects if they are not strictly alphanumeric.  But it really prefers that the files have the same names as the directories.
Each library must be added to the IDE using the
IDE menu Sketch..Import Library..Add Library

It stores them somewhere else in the IDE's guts.

I might add that this works fine unless you have 40 sketches and libraries that are being ignored due to this error.

here's an expression that strips every character that is not ( alpha numeric or space character, or period character) that is also Followed by an alpha numeric or space or period and replaces it by capitalising the following character.

find  ./ -depth | perl -wan -F'/' -e ' chomp; chomp($F[-1]);$x=$_; if ($F[-1]=~m/[^\p{Alnum}\d \.]/ and substr($F[-1],0,1) ne ".") {  $F[-1]=~s/[^\p{Alnum}\d \.]+([\p{Alnum}\d \.]{1})/uc($1)/eg; $y = join "\\",@F; system("mv",$x,$y);print "mv \"$x\" \"$y\"\n";}'

it ignores unix hidden file starting with "." And it also renames directories.
This will fail on edge cases where the last character in the name is a non alpha character.


text:
Arduino ATmega 2560 frequency measurement
I would like to measure frequency with an Arduino 2560 board. The approach is to use a timer interrupt set to one second and pin interrupt to count interrupts in one second.
The problem I have is that I get the wrong frequency. On my frequency generator I set up a frequency of 1000 Hz in my program I get 1006 Hz instead of 1000 Hz.
What am I doing wrong?
Here is my program. In the stup method I have declared a timer. When the signal comes on pin 2, the counter is increased by 1. After one second passed the flag bData is raised. If the flag is true then I print out a frequency on serial port.
#include <SPI.h>
#include <Ethernet.h>
#include <Math.h>

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 1, 177);
EthernetServer server(80);
const byte interruptPinTemp = 2;
const byte interruptPinSlanost = 3;
//konstante za SBE-3
const double g = 4.85442486e-003;
const double h = 6.77300393e-004;
const double i = 2.65502731e-005;
const double j = 2.06782794e-006;
const double f = 1000.0;
volatile int cnt = 0;
volatile int cnt1 = 0;
volatile double slanost = 0;
volatile double slanost1 = 0;
int timer1_counter;
boolean bData = false;
volatile int dvesek = 1;

void beriTemperatura() {
  cnt++;
}

void beriSlanost() {
  slanost++;
}

double calcTemp(double frekvenca) {
  double logRes = log(f / frekvenca);
  return 1.0 / (g + (h * logRes) + (i * pow(logRes, 2.0)) + (j * pow(logRes, 3.0))) - 273.15;
}

void setup() {
  Serial.begin(9600);       // inicializacija serijskega porta
  noInterrupts();           // disable all interrupts
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  pinMode(interruptPinTemp, INPUT_PULLUP);
  pinMode(interruptPinSlanost, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPinTemp), beriTemperatura, CHANGE);
  attachInterrupt(digitalPinToInterrupt(interruptPinSlanost), beriSlanost, CHANGE);
  TCCR1A = 0;
  TCCR1B = 0;
  timer1_counter = 34286;   // preload timer 65536-16MHz/256/2Hz
  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12);    // 256 prescaler
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
  interrupts();
}

//Timer interrupt na 1 sekundo
ISR(TIMER1_OVF_vect) {
  // interrupt service routine
  TCNT1 = timer1_counter;   // preload timer
  cnt1 = cnt ;               // prepisemo vrednost v cnt1
  bData = true;             // postavimo flag
  cnt = 0;  // resetiramo counter
}

void loop() {
  // če je postavljen flag, da so podatki jih izpišemo ali naredimo karkoli drugega
  if (bData == true) {
    bData = false;
    Serial.println(calcTemp(cnt1), 3);
    Serial.println(cnt1);
  }
}

Here is the frequency from my generator:

And here is a frequency measured with my board:

What is wrong that I get 1006 Hz instead of 1000 Hz?
If I raise the frequency for example to 5 kHz then I get 5032 Hz in my program (32 Hz to0 much).
Thank you for any advice.

TCNT1 = timer1_counter;   // preload timer

When you load the offset (timer1_counter), there are some values in the timer1 prescaler (and potentially TCNT1 if the prescaler isn't sufficient large, or the input pulse train is fast). By assigning a value to TCNT1, you would have written over the values in the prescaler / TCNT1 -> read the datasheet on that.
The solution?

Optimal: use a timer with auto-reload function. a timer with output compare can be adopted here as well.
Increment the counter: TCNT1 += timer1_counter; // preload timer, if timer has a 1:1 prescaler.

Or to use the timer to count the pulse and another to provide the time base.

Hi DannyF.. do you have some example? I'am new to microcontrollers (will check on google for auto-reload)

i'm happy to report that your code got accurate results when I drove it to 10Khz. the issue is likely the oscillator -> if they had indeed used a ceramic oscillator, they made a mistake. with a few cents more, they could have used a crystal instead.

with that said, it is generally desirable to NOT write to the counter. the optimal solution is to use auto reloading; if not available, try to increment it -> that typically can get the result down to two - three ticks.

The Arduino Mega 2560 is clocked off a ceramic
resonator, which
should typically have about 0.5% frequency tolerance. Your readings are
off by 0.6%, which is slightly more than the typical resonator
tolerance. I would them assume there is something wrong with your code,
check dannyf's answer.
Now, if you want significantly better accuracy, I would argue than
relying on the Arduino's internal clock is not a good idea. Even if your
code is perfect you cannot expect good accuracy. You could have better
results if you calibrate that clock instead of just assuming it runs at
16 MHz. But even then, ceramic resonators are notorious for having
a very significant frequency drift. Or you may get an Arduino clocked
off a quartz crystal instead, as these are far more stable.

authors: Александр Попов


text:
Using 8-bit instead of 16-bit in Adafruit library
I tried to modify the Adafruit_GFX and Adafruit_ST7735 libraries to make the color variable( as shown in code below) to use 8-bit instead of 16-bit for displaying 8-bit color on LCD screen.
void Adafruit_ST7735::pushColor(uint16_t color) {
 #if defined (SPI_HAS_TRANSACTION)
   SPI.beginTransaction(mySPISettings);
 #endif
  *rsport |=  rspinmask;
  *csport &= ~cspinmask;

   spiwrite(color >> 8);
   spiwrite(color);

   *csport |= cspinmask;
 #if defined (SPI_HAS_TRANSACTION)
   SPI.endTransaction();
 #endif
}

I changed it to the below
void Adafruit_ST7735::pushColor(uint8_t color) {
  #if defined (SPI_HAS_TRANSACTION)
   SPI.beginTransaction(mySPISettings);
  #endif
   *rsport |=  rspinmask;
   *csport &= ~cspinmask;

   //spiwrite(color);
   spiwrite(color);

   *csport |= cspinmask;
#if defined (SPI_HAS_TRANSACTION)
  SPI.endTransaction();
#endif
}

I have made similar changes in other portions of the code. This time nothing was displayed in the LCD(it was blank). However, when the spiwrite(color) is written twice i.e. the comment is removed, the code works fine.
Why is there a need to write 'spiwrite' function twice even in case of 8-bit color?
The original Adafruit library files are also attached.
drive.google.com/open?id=0B3x_NfKXnhtHR0VBcTNZbk5WT0E

If there is a publicly available version of the library that we can easily view online, why do you make us download a .zip file from Google Drive?

Did you read the datasheet of the LCD screen? The LCD expects you to
send the data in a specific format, and you should comply with that
format rather than invent your own and expect it to magically understand
it. If the LCD expects you to send 16 bits, you should do so. Or maybe
it has a 8 bit mode and there is a way for you to tell it “I'm switching
to 8-bit mode”. Read the datasheet to be sure.
If you want to display 8-bit color on an LCD expecting 16-bit, you
should find a way to map the 8-bit values into 16-bit values. The most
obvious way to map the range [0, 255] to [0, 65535] is to multiply the
8-bit numbers by 65535/255 = 257. Which is the same as sending the byte
twice.

I think you / someone asked an identical question here recently.
you didn't say a reason why you want to change a 16-bit type to 8-bit type.
with that said, this should work:
void Adafruit_ST7735::pushColor(uint8_t color_msb, uint8_t color_lsb) {
   ...
   spiwrite(color_msb);
   spiwrite(color_lsb);
   ...

basically, the original code.


text:
Figuring out IR sensor PWM frequency with Arduino
I'm trying to verify the pulse width of an IR receiver I "borrowed" from one of those cheap RGB controllers (like thisone) with an arduino nano. But the data I'm getting right now is about 3.4KHz and not the 38KHz I expected.
I'm trying to measure it by connecting the data pin of the IR on INT0 and listening for any change, if the pin goes low I start a measurement, if it goes high I stop the measurement and read out the value.
I'm using Timer1 and no prescaling
My code is as followes
#include <util/delay.h>

#define inpin 1 << PIND2
#define timeron 1 << CS10 //timer no prescale

bool wasTiming = false;
short i = 0;

volatile short timings[20];
volatile bool print = false;

volatile short seconds = 0;

int main()
{
    USART.begin();

    _delay_ms(500);
    USART.writeln("Arduino online");

    DDRD = 0;

    TCCR1A = 0; //no compares, normal counter mode
    TCCR1B = 0; //clock off

    EICRA = 1 << ISC00; // Any change INT0 (PD2)
    EIMSK = 1 << INT0; // INT0 interrupt enable

    sei();

    char buff[20];
    for (;;)
    {
        if (print)
        {
            print = false;

            for (short j = 0; j < 20; j++)
            {
                sprintf(buff, "% 6d ticks", timings[j]);
                USART.writeln(buff);
            }
        }
    }
    USART.end();

    return 0;
}

ISR(INT0_vect)
{
    if (PIND & inpin) //pin high
    {
        if (wasTiming)//
        {
            TCCR1B = 0; //timer clock off
            timings[i] = TCNT1;
            TCNT1 = 0; //empty timer register
            wasTiming = false;

            i++;
            if (i == 20)
            {
                print = true;
                i = 0;
            }
        }
    }
    else // pin low
    {
        if (!wasTiming)
        {
            TCCR1B = timeron; //timer clock on
            wasTiming = true;
        }
    }
}

and the output data is
 13902 ticks
  8865 ticks
  9961 ticks
  8877 ticks
  9968 ticks
  9842 ticks
  8506 ticks
  9896 ticks
  9585 ticks
  9865 ticks
  9541 ticks
  8853 ticks
  9545 ticks
  8888 ticks
  9885 ticks
  9954 ticks
  8515 ticks
  9885 ticks
  8909 ticks
  9874 ticks

on average that looks like about 9500 ticks, which leads me to the following calculation: (16,000,000 / 9,500) * 2 = 3,368.4Hz
Am I doing something wrong here? Or is the data that I'm getting correct, in which case, how would I go about turning that into 1's and 0's?
I'm not really looking for off-the-shelf solutions, half the fun of doing this is figuring it out myself. Eventually I'm gonna build my own RGB controller with this to replace that cheapo thing I already have (it has a few flaws I would like to correct).

38kHz is the carrier - the data switches the carrier on and off. The output from the TSOP is data.

You need to evaluate the IR waveforms using an oscilloscope. Without this you are running blind. Also consider that the IR remote control is likely to be outputting various pulse widths as part of the protocol that it uses.

@MichaelKaras I don't have one and have no-one in my area has one either, I would've used one if I could

Your data seems about right. If you look at the data sheet of an IR receiver chip, it'll state that about ten cycles (of 38 kHz) is required to detect one baud.

You mistakenly believe that the carrier frequency of 38 kHz should be available at the data output pin of the infrared detector chip. These chips provide a logic output indicating the presence of 38 kHz. Most are frequency-selective, being more sensitive at one frequency somewhere between 35 kHz - 60 kHz.
A data sheet pulled at random specifies typical pulse bursts that might be used to encode digital data (pulse burst timing highlighted in red):

In your case, \$f_o\$ might be close to 38 kHz. No fewer than six cycles \$t_{pi}\$ are recommended for the length of one baud. Perhaps your transmitter includes a few more cycles (ten or eleven?) to be safe. The receiver circuitry requires about five cycles before commit, \$t_d\$. Hopefully, a similar delay at end-of-pulse occurs, but the graph at right suggests the end-of-pulse extends a little longer than \$t_d\$. However, pulse width is impressively constant over five magnitudes of infrared intensity.
Note that the presence of a burst of 38 kHz from the transmitter most often sends the output of the receiver to a logic low. No optical signal yields a logic high at receiver output, sometimes with a fast false-detect glitch (which should be rejected if its length is short). A large-value pull-up resistor added between output pin and Vdd may be required to ensure that an idle receiver goes to logic high.
You will still have to determine how these pulse bursts are encoded into logical bits. Many protocols exist, some use pulse position, others use pulse length encoding.

I was indeed mistakenly believing the frequency was available at the data pin. I have since discovered that the data I'm receiving is encoded in pulse-distance and am now able to extract binary data from it. Thank you!


text:
How do I specify a particular pin to use as output for the Print class?
all.
I'm attempting to write a class that inherits from the Print class.  I only need serial output.
However, I'm having difficulty locating any reference on how to specify which pin on the ATMega my class will use as output of the write(...) functions.
How does the Print class know where to send output to ??
Thanks in advance.

You need to do far more than just "specify a pin". You need to write the software that transmits data through that pin in your chosen format.
You cannot send data through a pin. You can only set a pin HIGH or set a pin LOW. It is the sequence (and most importantly the timing) of setting a pin HIGH and LOW that constitutes sending data.
So you have to write the software that sets the pin HIGH and LOW in the right way and at the right time.
Fortunately sending is far simpler than receiving, as you can see if you look at the source code to SoftwareSerial.
Specifying the pin itself though is simple:
class MyClass : public Print {
    private:
        uint8_t _pin;

    public:
        MyClass(uint8_t pin);
        size_t write(uint8_t data);
};

MyClass::MyClass(uint8_t pin) {
    _pin = pin;
}

size_t MyClass::write(uint8_t data) {
    // In here you do whatever you have to in order
    // to manipulate _pin in the right way to send your data.

    // Don't forget to return the number of bytes written (there
    // is only one, so either 1 for "it got sent" or 0 for "it
    // didn't get sent".
    return 1;
}

It can be quite useful to have a begin() function for setting things up, such as configuring the right pinMode() for _pin, and maybe setting a baud rate like Serial does (although for simplicity you may choose to just have a single fixed baud rate, which means you can pre-calculate delay loops etc).

It seems I got past the "brain block"...  Just had to walk away from it for a while and the procedure just came to me.
Thanks to all.

The parent class (your class, in this case) provides read() and write() functions which in turn, know what ports to use. Presumably those were provided to the parent class' constructor. Now the Print class just has to know the standard function names.

Thank you, JRobert.
Apparently, it's specifying the "specifying which pin to use in my class' constructor" that's causing my "obvious brain block".
I don't want to use the hardware serial so I can leave normal TX and RX available for re-programming.
I tried inheriting from SoftwareSerial, but it apparently requires both TX and RX to be specified, and I only need

I only need my class to send data (not receive).
I hope I stated that clear enough.

It won't hurt to implement the read function anyway; make it an empty one if you wish. But I'd expect Print would refer to it (statically) and you'd get an undefined function error at compile time if no such function is present.


text:
How do you connect parts once all GPIO ports are used?
I have a rather ambitious project in mind. Lots of buttons, sensors, feedback.
If I run out of GPIO ports to attach stuff to my Arduino, what's next? Do you have to buy a separate Arduino to run the extra parts, and then link the two arduinos somehow?
Thanks for any direction you can give.

There is no one solution.  It depends on what you are connecting.

Yes, it is one possible way, another are using some kind of multiplexing as input shift registers, Charlieplexing http://www.instructables.com/id/Charlieplexing-7-segment-displays/?ALLSTEPS, button matrix http://pcbheaven.com/wikipages/How_Key_Matrices_Works/ or i2C bus, which can connects up to 127 different i2c devices

You can use I2C or SPI port expanders (SPI ones are a bit faster but require more pins). Examples are the MCP23017 (I2C) or MCP23S17 (SPI). Or alternatively you can also add shift registers (chained outputs or inputs with just three pins). Good catch the button (or LED) matrix, and thanks for the Charlieplexing (I always used the usual multiplexing, but this is "smarter")

I2C can't connect 127 different I2C devices - not if you wish to adhere to the standard. You can only officially use addresses 16 to 123, which is 107 devices. The other addresses are reserved for specific uses.


text:
Why can't I use just the digital pins and a ground to use a potentiometer?
First of all I am a newbie. So please excuse.
After doing the first basic project, in which I had hooked up the positive of a LED to a digital input of the Arduino and the negative to the ground of the board, I am assuming that the digital pins in Arduino are positive (are they 5v?).
So why can't the potentiometer be connected in the same way?
Thank you.

A rotary knob encoder may do the trick. It looks very much like a potentiometer, but can be read out by digital pins.

A potentiometer is an analog device, meaning it communicates its position by varying the voltage rather than sending discrete ones and zeros.
If a linear potentiometer is turned half way then the output of the pot will be at half the voltage of the input. If it is turned all the way then the output will equal the input voltage and if it is not turned at all then the output will be 0V.
In order to make sense of the potentiometer you must connect the output to the analog pins and it will give you a 10 bit number, the higher this number the closer the output voltage of the potentiometer is to 5v (or whatever you set the Analog Reference voltage to be, but don't worry about the AREF pin for now).
Digital pins are either on or off, there is no in between, so they do not work for this application
This page has an excellent potentiometer user guide: https://www.arduino.cc/en/Tutorial/Potentiometer

What does  “communicates its login” mean?

@jwpat7 It was a typo I was going for "communicate its logic" but I changed it to "communicate its position" to be more clear. I am trying to say that a digital rotary encoder would tell the Arduino how far it is turned via a digital signal (a packet of ones and zeros), whereas a potentiometer tells the Arduino its position via varying the output voltage.

I had hooked up the positive of led to a digital input of the arduino and negative to the ground of the board.

You shouldn't have done that. It damages both the LED and the Arduino.
The care and feeding of LEDs

So I am assuming that the digital pins in arduino are positive (are they 5v?).

Yes and yes (assuming a 5V Arduino).

So why cant the pot be connected in the same way?

The pot has 3 terminals, so I'm not sure what you mean by that. You are going to connect them to ground, a digital pin, and what else?

Normally you connect one end of the pot to ground, the other end to +5V, and the middle terminal to one of the analog inputs. Then when you turn the pot, the voltage at the analog input changes to be somewhere between 0V and 5V.

A potentiometer is a form of voltage divider - I suggest you read those links to understand more about them.

I am assuming that the digital pins in Arduino are positive (are they 5v?).

On a 5V Arduino, when a GPIO pin is set to OUTPUT and switched HIGH then yes, it is (almost) 5V. When switch LOW it is (almost) 0V or GND. When it is set to INPUT it is neither - it is "high impedance" and senses the voltage on the pin using a set of thresholds.
When the voltage being applied to the pin is above the high threshold (known as VIH) the pin sees it as a logic HIGH and digitalRead() reports it as such. When the voltage being applied is below the low threshold (known as VIL) the pin sees it as a logic LOW and digitalRead() reports it as such.

So why can't the potentiometer be connected in the same way?

So yes, you can connect a potentiometer up to to a digital pin in the same way as you can to an analog pin (one pin to +5V, one pin to ground, and the middle "wiper" pin to the digital input):

When you turn it, instead of reading a value between 0 and 1023 as you would on an analog pin, you will either get a HIGH or a LOW depending on how far you have turned the knob and in which direction. In the region in the middle you will read "who knows?" - that is, maybe HIGH, maybe LOW, depending on the weather and the pin itself.
Note that connecting a potentiometer up like this on a pin set to OUTPUT is dangerous (not to you, to the Arduino) and has the potential to damage the GPIO pin's internal circuitry when the pot is turned all the way one way or the other, since it creates a dead short circuit to either ground or +5V, and the GPIO pin itself, when in OUTPUT mode, is also connected internally to either ground or +5V.
Some pins on microcontrollers (not sure about the Arduino off hand) have Schmitt Trigger inputs. These avoide the "who knows?" region by toggling the input HIGH or LOW depending on when the voltage passes a threshold. For the pin to change from reporting a LOW to a HIGH the voltage has to pass above the high threshold. To then switch to reporting a LOW again it has to drop all the way down to the low threshold. Any voltage in between the two thresholds is ignored completely and the previous state is retained.

Yes, the ATmegas do have Schmitt triggers in their inputs, as stated in the datasheet.

For connect a LED you need use a little resistor to limit the current, so you can use the potenciometer with your LED and see the bright ajust.

I had hooked up the positive of a LED to a digital input

A Arduino digital PIN as cofigurable how input or output, if you use it as input you need use this pin for read a digital value (0 or 1), example a button. When you configure the pin to output you can set the value high (~5v) or low (0v).

It depends on what you are trying to accomplish.  If you set the pin as output and turn it on, then can use it as 5v power source. This is done frequently when you want the software to be able to turn some part of your system on/off.  If this is what you want, you can put a pot or any other component downstream as long as it doesn't try to draw too much power. See this post for details on that
If you are trying to read the "value" of the pot, it would work as an on/off switch because this is a digital pin. Digital means 0 or 1. When there is enough voltage, it will register as 1, once the voltage gets low enough, it will register as a zero.  If you want to read a full range of values from the pot, you would have to use an analog pin.

Analog pot on digital pin will give,
0:from min to half way and
1: from half way to end position
You can use it if this suits your program logic.

That is not correct. You might want to read up on voltage ranges for logic levels. Sparkfun offers a basic tutorial.


text:
Why is my code only reading the change of the encoder's pin A?
I am writing code for reading in a quadrature encoder. I used attachInterrupt on pin 2 and 3, but by using the same ISR.
    int encAPin= 2;
    int encBPin= 3;
    volatile int encAValue= 0;
    volatile int encBValue= 0;
    volatile int encCount= 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(encAPin, INPUT);
      pinMode(encBPin, INPUT);
      attachInterrupt(digitalPinToInterrupt(encAPin),encUpdate, CHANGE);
      attachInterrupt(digitalPinToInterrupt(encBPin),encUpdate, CHANGE);
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println(encCount);
    }

    void encUpdate() {
      if(digitalRead(encAPin)==RISING){
        if(digitalRead(encBPin)==LOW){
          encCount++;
        }else if(digitalRead(encBPin)==HIGH){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==HIGH){
        if(digitalRead(encBPin)==RISING){
          encCount++;
        }else if(digitalRead(encBPin)==FALLING){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==FALLING){
        if(digitalRead(encBPin)==HIGH){
          encCount++;
        }else if(digitalRead(encBPin)==LOW){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==LOW){
        if(digitalRead(encBPin)==FALLING){
          encCount++;
        }else if(digitalRead(encBPin)==RISING){
          encCount--;
        }
      }
    }

When I tried Serial.print to check whether or not the pin A's and B's inputs were changing, I noticed that only pin A's (pin 2) input was changing. I made sure that the circuit and the wiring were all correct. Is there something about my code that is not reading pin B's input properly?

What's this? if(digitalRead(encAPin)==RISING) - that doesn't make any sense. It is either HIGH or LOW.

I apologize. I was merely following my notes, and it indicated that there are 8 cases for the input graphs of pin A and B. Thank you.

I think you have mixed up interrupts and pin reading.  A digital pin will only ever he HIGH or LOW, The attachInteruppt() function takes a wider variety of states (I don't know if CHANGE and RISING are valid).

There are only 4 states that a pair of pins can be in. That is, 2² - 2 states (HIGH and LOW), and ² pins.

You're confusing interrupt events and pin states here.
A pin can be either HIGH or LOW. Never anything else.
An interrupt can trigger on one of four events:

The pin transitions from HIGH to LOW (FALLING)
The pin transitions from LOW to HIGH (RISING)
The pin transitions from one state to another (CHANGE)
The pin remains low (LOW)

Your code should be (as you have done) attaching the interrupt to the pins using CHANGE so you can see any change in the state of the pins.
Your interrupt code should then examine the two pins to see their current state.
But there is one bit missing from your code, and that is what was the state before this interrupt triggered? - i.e., from what did the pins change from to get to this state?
The simplest way of coding this kind of thing is to think of each pin as a bit in a 2-bit binary number. Join the two pins together to form a number between 0 and 3:
uint8_t pinVal = (digitalRead(encBPin) << 1) | digitalRead(encAPin);

The truth table for that would be:
B | A | B<<1 | pinVal
0 | 0 |  00  |   00 (0)
0 | 1 |  00  |   01 (1)
1 | 0 |  10  |   10 (2)
1 | 1 |  10  |   11 (3)

There you have 4 states. And if you remember that state from one interrupt call to the next, you can compare the current value to the previous value. And that is where you get your 8 states from.  Encoders use Gray Code so the sequence of numbers you would get as you rotate the encoder would be:
0, 1, 3, 2, 0, 1, 3, 2 ...

Or the other way:
2, 3, 1, 0, 2, 3, 1, 0 ...

And it's the transition between those values that tells you what the encoder is doing:
0 <-> 1 <-> 3 <-> 2 <-> 0 ...

Each of those transitions can go two ways, and if you count the arrows (< and >) there are 8 of them there, which are the 8 states you were thinking of before.
So if the previous value is stored in oldVal from the last time the interrupt triggered, and the new value is in newVal, your 8 states are:

oldVal == 0 && newVal == 1
oldVal == 1 && newVal == 3
oldVal == 3 && newVal == 2
oldVal == 2 && newVal == 0
oldVal == 0 && newVal == 2
oldVal == 2 && newVal == 3
oldVal == 3 && newVal == 1
oldVal == 1 && newVal == 0

The first four are progressing in one direction, the last four in the other - one set is clockwise, one is anti-clockwise.
So you could have an (untested) interrupt handler that looks something like this:
void encUpdate() {
    static uint8_t oldVal = 0; // Static variable to remember the last state
    uint8_t newVal = (digitalRead(encBPin)) << 1 | digitalRead(encAPin);

    if (
        (oldVal == 0 && newVal == 1) ||
        (oldVal == 1 && newVal == 3) ||
        (oldVal == 3 && newVal == 2) ||
        (oldVal == 2 && newVal == 0)) {
            encCount++;
    } else {
        encCount--;
    }
    oldVal = newVal;
}

You notice I've only implemented the comparison for the first four states and not the last four. Since there are only 8 states, and those states cause one of only two things to happen, if it's not one of the first four states, which would increase your count, it must then be one of the last four states which decrease your count. No point in checking for them since it can't be anything else.  If you turned it clockwise then increase the value. Otherwise you must have turned it anti-clockwise since there is no other direction you can possibly turn it in, so decrease the count.
This is precisely why Gray Code is used - only one pin ever changes at a time, so there is no ambiguity in what has happened - either you turned it one code-point in one direction or you turned it one code-point in the other. Even if there is lots of bounce it will just bounce between two neighbouring code-points and settle on the final new code point (as long as the interrupt can react fast enough to catch all the bounces).


text:
Different functions using 2 buttons
I'm currently learning Arduino. So right now I'm trying to create an Arduino app that will use buttons, LEDs and RGB.
So I have 2 buttons, 8 LEDs and an RGB. The first button is the function switcher: when you press it the LED will light according to their function. The second button is the function activator so right now here's I want to do:

Function 1: Turn on/off RED light
Function 2: Increase RED light brightness by 5; if already at 255, reset at 0
Function 3: Turn on/off GREEN light
Function 4: Increase GREEN light brightness by 5; if already at 255, reset at 0
Function 5: Turn on/off BLUE light
Function 6: Increase BLUE light brightness by 5; if already at 255, reset at 0
Function 7: Turn on ALL lights, all brightness to 255
Function 8: Turn off ALL lights, all brightness to 0

I already started coding and I'm stuck at turning on and off the red light. Here's my code:
const int red = 5;

int b1, b2; //Buttons
int dir = 0;
int light = 11;
int func = 0;
boolean buttonValue = true;
boolean buttonState = true;

void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(red, OUTPUT);
  for (int i = 11; i <= 18; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop() {
  b1 = digitalRead(2);
  if (b1 == HIGH) {
    dir = 2;
    func++;
    if (func >= 8)
      func = 0;
    } else {
      dir = 0;
    }
    digitalWrite(light, LOW);
    if (dir == 2 && light < 18) {
      light++;
    }
    digitalWrite(light, HIGH);
    delay(200);
  }

void function(int pin) {
  b2 = digitalRead(3);
  switch (func) {
    case 1:
      if (b2 = true) {
        digitalWrite(5, HIGH);
      } else {
        digitalWrite(5, LOW);
      }
  }
}

ArduinoMenu library can do that, using a code driven menu (driven by the 2 buttons) and an headless menu (no output devices). Menu event handlers can then control the led, I've done this for an RGB led with only 2 buttons. https://github.com/neu-rah/ArduinoMenu

I have to be honest after reading you description and looking at you code I have no idea how you arrived at the code you have arrived at.
For now lets try a much simpler bit of code, once that is working you can build on it.
#define PIN_BUTTON_1    2
#define PIN_LED_RED     5

void setup() {
    pinMode(PIN_BUTTON_1, INPUT);
    pinMode(PIN_LED_RED, OUTPUT);
}

void loop() {
    const int buttonState1 = digitalRead(PIN_BUTTON_1);
    digitalWrite(PIN_LED_RED, buttonState1);
    delay(200);
}

If that code doesn't work then there is something wrong electrically.
I think is the next step you were trying for:
#define PIN_BUTTON_1    2
#define PIN_LED_RED     5

int lastButtonState1 = LOW;
int functionNumber = 0;
int currentLedValue = 0;

void setup() {
    pinMode(PIN_BUTTON_1, INPUT);
    pinMode(PIN_LED_RED, OUTPUT);

}

void loop() {
    const int currentButtonState1 = digitalRead(PIN_BUTTON_1);
    if (lastButtonState1 != currentButtonState1)
    {   // If the button's state has changed
        if (currentButtonState1 == HIGH)
        {
            ++functionNumber;
        }
        lastButtonState1 = currentButtonState1;
    }
    DoFunction(functionNumber);
    delay(200);
}

void DoFunction(const int& function)
{
    switch (function)
    {
    case 1:
        if (currentLedValue > 0)
        {
            currentLedValue = LOW;
        }
        else
        {
            currentLedValue = HIGH;
        }
        digitalWrite(PIN_LED_RED, currentLedValue);
        break;
    case 2:
        currentLedValue = 128;
        analogWrite(PIN_LED_RED, currentLedValue)
        break;
    default:
    }
}

If you would like to call the function you defined at the end of your code you need to give it a name function name()....
In your code you used if (b2 = true). That will not work as expected, since it sets the b2 variable to true. Note the if expressions use == to compare values, see the Arduino Reference. Further you should use the HIGH and LOW Pin level constants for comparing pin states as described here.
So your code will look like

    if (b2 == HIGH) {
        digitalWrite(5, HIGH);
    } else {
        digitalWrite(5, LOW);
    }

or shorter just:
digitalWrite(5, b2); without the if/else expressions.

Hi! I already figured it out but I was wondering why the RGB doesn't turn on.


text:
Best way to send text to ESP8266 remote display
I need a remote display to show information sent via WiFi from another ESP8266. What needs to be sent is a string along with some variables, for example a string to be displayed along with two integers for the position on the display:
0, 12, "message to display on screen"

As I am absolutely new to network stuff, what would be the best way to achieve this?

Sending a POST request through REST API?
Use UDP instead?
Or better use a framework like MQTT?

Define "best".  For example, easiest to implement?  Most reliable?  Most flexible?  Smallest code size?  Most easily extensible?  Easiest to expand?  Or, maybe you don't want best, but adequate..?  There are examples in the SDK of how to connect to wifi and send and receive data.

Try the esp8266 UDP messages
With UDP you can send and receive messages quite easily and without consuming lots of resources.

Thank you! I'll check back as soon as I've learned something about UDP.

UDP was exactly what I need.

I set up one esp8266 as an access point sending udp messages to multiple displays. The remote displays connect to the access point and then can receive whatever is sent. The displays are esp8266 devices as well. This works well and I can have multiple displays all listening to the same udp messages. This thread is pretty old but I would just lend support to the reply of using udp for a remote display. You will occasionally miss a message so that needs to be considered. In my testing it was rare, like maybe 1% of the time. If you must get the message there, another protocol might be more approp


text:
Error while trying to drive relay through the state of a digital input pin in Arduino
I'm trying to change the state of a relay according to the state of a digital input in an Arduino with an ethernet shield. It works sometimes and some other times it doesn't work.
My code:
const int led1 = 2;
const int enable1 = 4;
boolean led1_OnOff;

void setup() {
  led1_OnOff = false;
  pinMode(enable1, INPUT);
  digitalWrite(enable1, LOW);
  pinMode(led1, OUTPUT);
}

void loop() {
  if(digitalRead(enable1) == HIGH) {
    if(led1_OnOff == true) {
      led1_OnOff = false;
    } else {
      led1_OnOff = true;
    }
  }

  if(led1_OnOff == true)
    digitalWrite(led1, HIGH);
  else
    digitalWrite(led1, LOW);
}

My schematics:
Relay 5v -> arduino 5v
Relay gnd -> arduino gnd
Relay in -> digital pin 2
Relay com -> 220 AC
Relay NC -> 220 AC
Push button pin 1 -> Arduino 5v
Push button pin 2 -> digital pin 4
Pin 2 is connected to the relay enable pin and pin 4 is connected to a push button and the boolean is used for saving the state.
Can anyone tell me what the problem is, and why the relay doesn't work most of the time?

Your "My Schematics" is a description, not a schematic. Please make a schematic showing how the Arduino drives your relay. Is it directly connected? How much current does your relay's coil draw? An Arduino pin is only meant to supply 20ma with an absolute maximum of 40ma. It may just not have enough drive. You'll also need a diode to across the coil to quench the inductive kickback when you release the coil, to stop it reaching and destroying the Arduino pin.

Thanks for stopping by...I already answered my question so no need to tell you more about my schematic as it is already right and there is nothing wrong about it...have a good day.

I modified my code and added some code for button debounce and added 10k ohm pull down resistor to my hardware and it works like a charm now.
my new code :
const uint8_t led1 = 6;
const uint8_t enable1 = 7;
const uint16_t buttonConfidenceLevel = 500;
boolean led1_OnOff;

uint16_t pressedConfidenceLevel;
uint16_t releasedConfidenceLevel;
boolean pressed;

void setup() {
    led1_OnOff = false;
    pinMode(enable1, INPUT);
    pinMode(led1, OUTPUT);

    pressedConfidenceLevel = 0;
    releasedConfidenceLevel = 0;
    pressed = false;
}

void loop() {
    if(isButtonPressed()) {
        // Button is pressed
        led1_OnOff = !led1_OnOff;

        if(led1_OnOff == true)
          digitalWrite(led1, LOW);
        else
          digitalWrite(led1, HIGH);
    }

}

boolean isButtonPressed() {
    if(digitalRead(enable1) == HIGH) // button is sensed pushed down
    {
        releasedConfidenceLevel = 0;

        if(pressed == false)
        {
            pressedConfidenceLevel++;

            if(pressedConfidenceLevel > buttonConfidenceLevel)
            {
                pressedConfidenceLevel = 0;
                pressed = true;

                // Button is pressed
                return true;
            }
        }
    }
    else // button is sensed released
    {
        pressedConfidenceLevel = 0;

        if(pressed == true)
        {
            releasedConfidenceLevel ++;

            if(releasedConfidenceLevel > buttonConfidenceLevel)
            {
                releasedConfidenceLevel = 0;
                pressed = false;
            }
        }
    }

    return false;
}

Assuming your circuit is correct (and perhaps it is, since you imply that it works some of the time), the first obvious problem is that when you press the button, the code will repeatedly toggle the output, very very fast.  It may seem to you like you're only pressing the button for a moment, but the code will loop many many times.  When you release the button, it's a 50/50 chance whether it leaves the relay on or off.
To solve this, you can wait until the button is released before checking again.
In addition to this, you may have switch bounce.  There are nicer ways of fixing this, but for your stated purpose, waiting 0.1s after a releae before checking the button again is probably sufficient.
....
void loop() {
  if(digitalRead(enable1) == HIGH)
  {
    if(led1_OnOff == true)
    {
      led1_OnOff = false;
      //+digitalWrite(led1, LOW);
    }
    else
    {
      led1_OnOff = true;
      //digitalWrite(led1, HIGH);
    }

    // Wait for the button to be released
    while(digitalRead(enable1) == HIGH)
    {
      // do nothing, just wait
    }
    // Poor-man's debounce
    delay(100);
  }

  if(led1_OnOff == true)
    digitalWrite(led1, HIGH);
  else
    digitalWrite(led1, LOW);
}

that's a little bit steadier but still doesn't work always

Perhaps you have switch bounce.  Code modified to address that.

I tried something else and it works now, but thanks for the help.

First, how you are set a pin as input and write in this pin?

pinMode(enable1, INPUT);
digitalWrite(enable1, LOW);

You dont need compare a boolean with true

if(digitalRead(enable1) == HIGH)

is the same as:
if(digitalRead(enable1))

use a debbounce with a button state flag to change the button state
if( digitalRead(enable1))
       ena_deb++;
       if(ena_deb > 5){
            change_en_state
       }
}else{
    change_en_state = 0
}

if(change_en_state == X)
    change_output_value;

Thanks for your answer...I already figuered out the answer.

And by the way it's ok to define a pin as input and intialize it at start up...and I already know that trick you said about booleans but it's a programing habit.

When you define a pin as input you can not intialize it, is physically Impossible.
The best way for do a debbounce is use a timer for that. count the debbounce in the timer and set a flag, so you only need read a flag


text:
Custom source directory
How do you specify a custom location for your sketch?
I want my code to be located in a src folder, but when I try to compile my main.ino, arduino complains "The file main.ino needs to be inside a sketch folder named "main". How do I disable this arbitrary restriction?

I found I could accomplish this using the arduino-builder tool. I created this simple bash script to do the compilation:
#!/bin/bash
CURRENT_DIR=`pwd`
mkdir -p $CURRENT_DIR/.build
arduino-builder -compile -hardware /usr/share/arduino/hardware -tools /usr/share/arduino/hardware/tools -tools /usr/share/arduino/tools-builder -libraries $CURRENT_DIR/lib -fqbn arduino:avr:uno -build-path $CURRENT_DIR/.build $CURRENT_DIR/src/main.ino

You can't. It's a feature of Processing, on which the Arduino IDE is based.

The tools ino and ano do this, still using the Arduino internals to do the compilation. I'd like to do this through the official command line interface, because those tools are no longer maintained.