text:
How to Jump from one loop to another while executing
For my program I have to sense 3 inputs (A1, A2 and A3 in Arduino). If any one or two or more signals become zero (low), it goes in different case as per below program.
However, I want to reset the Arduino when all signals become high again. Therefore I have to again write another program loop2().
So how can I exit from one loop and get into another loop. If I have to use goto, please tell me how to use it?
The Arduino program given below.
const int analogPin1 = A1;
const int analogPin2 = A2;
const int analogPin3 = A3;
const int ledPin = 13;
const int ledPin2 = 7;
const int  thresold = 400;
unsigned int x1,x2,x3,fault = 0;

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

void Config()
{
    delay(1000);
    Serial.print("ATE0r");
    Response();
    Serial.print("ATr");
    Response();
    Serial.print("AT+CMGF=1r");
    Response();
    Serial.print("AT+CNMI=1,2,0,0,0r");
    Response();
}

void Response()
{
    int count = 0;
    Serial.println();
    while(1)
    {
        if(Serial.available())
        {
            char data =Serial.read();
            if(data == 'K'){Serial.println("OK");break;}
            if(data == 'R'){Serial.println("GSM Not Working");break;}
        }
        count++;
        delay(10);
        if(count == 1000){Serial.println("GSM not Found");break;}

    }
}

void loop()
{
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);

    if (analogValue1 < thresold)
    { x1=1;
        fault=x1;
    }
    if (analogValue2 < thresold)
    {  x2=x1+3;
        fault=x2;
    }
    if (analogValue3 < thresold)
    {  x3=x1+x2+5;
        fault=x3;
    }

    switch(fault)
    {
    case 1:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("PHASE 1 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        loop2();
        break;

    case 3:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 4:
        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("1 AND 2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 5:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("AT+CNMI=2,2,0,0,0");
        break;

    case 6:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("1 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 8:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("2 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 10:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("ALL 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    default:
        x1,x2,x3,fault=0;
        digitalWrite(ledPin, LOW);
        break;

    }

    x1,x2,x3,fault=0;
    digitalWrite(ledPin, LOW);
    do
    {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    }
    while ( analogValue1 < thresold || analogValue2 < thresold || analogValue3 < thresold );

}

do
{
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);
}
while (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));

}

void loop2()
{
    if (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
    {

        digitalWrite(ledPin, HIGH);
        Serial.begin(9600);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("Nikunjsinh2");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919712554766\"\r");
        delay(1000);
        Serial.print("Nikunjsinh2");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);

        do
        {
            int analogValue1 = analogRead(analogPin1);
            int analogValue2 = analogRead(analogPin2);
            int analogValue3 = analogRead(analogPin3);
        }
        while (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
    }
}

x1,x2,x3,fault=0; doesn't do what you think it does.

Also, with do  { int analogValue1 = ...} you are creating new variables that only exist inside the loop body. Remove the int s.

you can use goto in arduino to hop around labels. serious/team programmers might cringe, but it works.

It is clear from your question you intuitively know this program will not perform as desired.  Simply put, if you do not check all states during every loop, you can not possibly react to all possibilities.  Therefore you can only have 1 loop.  Get rid of the other loops.

...but i want to reset arduino when all signal becomes again high...

This statement identifies what is missing.  You need a temporal aspect to the loop in order to "remember" that all signal(s) were not high on the previous loop and now in the current loop they are all high.
Programmers commonly refer to this feature as a Finite State Machine.  A way to "remember" what state the loop was in the last time it was executed.  And a way to know what state(s) is(are) next possible.
If all you need to remember is that not all 3 inputs were high the last time through the loop, your state machine only needs the one value.  And that value only needs to be a zero or one.


text:
How to declare char array[] using integers?
Can anyone please tell me how to declare a char variable using a few integers?
I need to declare a byte information for shiftOut() function as char.
int a = 0;
int b = 1;
int c = 0;
int d = 1;
int e = 1;
int f = 0;
int e = 0;
int f = 1;

char information[] = {"B" + a + b + c + d + e + f};

void setup() {
  Serial.println(information);
}

void loop() {
  shiftOut(pin, pin, MSBFIRST, information);
}

In command Serial.println(information); I want to get back B01011001
Now the output I am getting ⸮⸮
Of course the simpliest way to create that will be:
char information[] = "B01011001";
But I need to change the individual bits in int bit = variable.
Please note that substition int bit = with char bit = is unable for my code, using int of value of individual bits is necessarily. Because I am using my project with blynk, and there is function a = param.asInt(); ,  param.asChar(); does not exist.
How to do that?
Thank you for responses!

I think you are getting something wrong about shiftOut(). It will transfer exactly 1 byte (or 1 char). It does not take an array as parameter. I guess you want to write the 8 bits, that you are defining with your ints, as one byte out. Defining at byte directly would look like this:
byte information = 0b00101100;

The 0b tells the compiler, that the following number is encoded in binary. So you have one single byte, that contains all your information (all the bits). Then you can do
shiftOut(data_pin, clock_pin, MSBFIRST, information);

(Please note, that the data_pin and the clock pin need to be different).
If you want to print the information variable to Serial, showing the binary representation, you can use the corresponding parameter of the print() function.
Serial.print(information, BIN);

Will print the binary representation (zeros and ones as text) of the variable. So, to get "B1011001", you would do:
Serial.print("B");
Serial.println(information, BIN);

Note, that the print()/println() function will remove all leading zeros.

How to put the information byte with your ints? Each of them is either zero or one and represents one bit. So you can use the bitwise operators to put them together:
information = (a << 7) | (b << 6) | (c << 5) | (d << 4) | (e << 3) | (f << 2) | (g << 1) | h;

For each int only the first (Least significant) bit is important, since the others are always zero (because the int can be only one or zero). So we shift the int value to the left by the number of the corresponding bit minus 1 (so shifting a 7 places to the left to put its least significant bit to the most significant bit of information. We are doing that for all our int values. Then we put them all together into one byte by using the | (bitwise OR) operator.
Note: We don't know, where these ints are coming from. Even when stating, that you absolutely need those ints, you could organize them in an array instead of single variables. That would look like this:
int int_data[8] = {0, 0, 1, 0, 1, 1, 0, 0};
...
// in a function (like loop() or setup())
byte information = 0;
for(int i=0;i<8;i++) information |= int_data[7-i] << i;

It's up to you, if you want to do that.

source: Stack Exchange

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

sort: votes


text:
Defining Serial UART
I'm new to Arduino..
I'm currently trying to create a GPRS connection through SIM card. For that, I need to connect a serial UART port.
I don't know how to define the Serial UART. Could you please help me with that?

There are millions of examples on google for how to do it. Have you tried asking it?

In the setup function you will need to call the Serial.begin() function.
To receive a serial character you should call the Serial.available() function inside an if statement.
To send a character you can either use the Serial.write() or Serial.print() functions.
Below is a simple example program that will echo the characters back to the PC.
//-------------------------
// Simple serial loopback
//-------------------------

void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop()
{
  byte inChar;

  // check if data has been sent from the computer:
  if (Serial.available())
  {
    // read the most recent byte
    inChar = Serial.read();
    // send back the charater
    Serial.write(inChar);
  }
}

There are plenty of "built-in" examples in the Arduino IDE that use the various serial functions. These can be viewed without any hardware attached. In the IDE go to File > Examples and from there a lot of the examples for the serial UART are in the Communications section. Details of these examples can be found on the Arduino Tutorial site.

The uno's only hardware UART is used for peogramming and producing debug outpt.  If it is connected to a GPRS module then programming will not be possible and debug output will be problematic.

I've seen many boards use jumpers/switches/solderlinks/shields that you disconnect when you need to reprogram. Hopefully you get to a stage where you device works and you don't need to reprogram the micro.

The Arduino has only one UART which is used for program upload and for the serial terminal output to your computer. While you can connect it to another serial device that will make debugging cumbersome as 1) you won't be able to send any debug output; and 2) you will need to change it back and forth between your computer and the GPRS as you re-build and upload your code. You pretty much need a second UART to do this any kind of conveniently.
Look up the library module called SoftwareSerial which can simulate a UART on a second pair of pins, with some limitations: It is limited to communicating at 9600 baud; it can not transmit and receive at the same time; at most, one SoftwareSerial port can be receiving (or even listening) at any one time; and it can interfere with some other internal hardware, notably the interrupt system and at least one of the timers.  (The link points to the Arduino website whose documentation isn't always the very latest, but what's there will give you the idea).
In many cases, and yours is likely one of them, these are not show-stoppers, just something to be aware of as your code becomes more complex. As long as you can operate your device by occasionally sending it a string and receiving another in reply, and your system doesn't include other high-speed devices that must be serviced quickly when they request it, you probably won't notice the limitations.

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:
How to store the content of message sent to GSM module (SIM900a) into a string?
I am Working on a project to control the system via the GSM messaging Scheme.
eg:- If I send 1 via an SMS to the GSM module, the Arduino would read this message and disable or enable the system.
But I am unable to process the message, since the received message format is;

+CMT: "+91xxxxxxxxx","","17/07/07,21:57:04+08"

#include<SoftwareSerial.h>
SoftwareSerial myGSM(9,10);// Rx and Tx
int a;
int b[5];
int actuator = 5;

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

void loop()
{
  msg_read();
  for( int i = 0; i < 5;  ++i )
   b[i] = (char)0;
}

void msg_read()
{
  myGSM.println("AT+CNMI=2,2,0,0,0");//AT command to recieve live SMS
  delay(1000);
  if (myGSM.available()>0)
  {
    char c;
    char store[30];
    c = myGSM.read();
    store[30] = c;
    int a = 10;
    a += 1;
    store[a] = 0;
    char* command = strtok(c, ",");
    while ( command != 0)
    {
      int i = 0;
      b[i] = atoi(command);
      command = strtok(0, ",");
      i++;
    }
  }
  for( int j = 0;j <= 2; j++)
  {
  msg_send(b[j]);
  }
}

void msg_send(int c[])
{
   myGSM.println("AT+CMGF=1");//Sets GSM module in text mode
  delay(1000);
  myGSM.println("AT+CMGS=\"+91xxxxxxxxxx\"\r");
  delay(1000);
  if( c[0] == 1)
  {
    digitalWrite( actuator, HIGH);
    myGSM.println("SYSTEM ENABLED");
  }
  else if( c[0] == 2)
  {
    digitalWrite(actuator, LOW);
    myGSM.println("SYSTEM ENABLED");
  }
  if( c[1] == 3)
  {
    myGSM.println("GEOFENCE ENABLED");
  }
  else if( c[1] == 4)
  {
    myGSM.println("GEOFENCE DISABLED");
  }
}

Requirement

I need a code that will allow me to recover the message content and compare it with a predefined string.
Can I use the GSM library with SIM900a module or is it reserved only for GSM shield?

I am using an Arduino Uno.

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Thank you, the guide helped me figure it out. I encoded the message as #xy,  where x and y can take 0 and 1. I stored each character sent to the arduino in a variable.            char c = myGSM.read();                         Continued this until I found '#' and then used if statements to determine if the message was 1 or 0.

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


text:
Error compiling for board Arduino/Genuino Uno
I am getting the following error message when compiling a program on my Arduino IDE. This does not happen when compiling the given example programs in the IDE.
The error message is as follows :
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware
C:\Program Files\Arduino\hardware -tools
C:\Program Files\Arduino\tools-builder -tools
C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries
C:\Program Files\Arduino\libraries -libraries
C:\Users\mahim\OneDrive\Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path
C:\Users\mahim\AppData\Local\Temp\arduino_build_361527 -warnings=none -build-cache
C:\Users\mahim\AppData\Local\Temp\arduino_cache_227236 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=
C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=
C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=
C:\Program Files\Arduino\hardware\tools\avr -verbose
C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino
readlink
C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino: The system cannot find the file specified.

Error compiling for board Arduino/Genuino Uno.

Following on from duskwuff's answer, the issue with OneDrive folders has been resolved as of version 1.8.6.
https://www.arduino.cc/en/Main/ReleaseNotes

ARDUINO 1.8.6 2018.08.23
[ide]

Updated arduino-builder to 1.4.0:

parallel build (improve compile speed)
better reuse of already compiled files
Windows: fixed build for sketch stored under OneDrive cloud folders

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.


text:
Arduino Mega Sensor shield
I'm using an Arduino Mega Sensor Shield on a Mega 2560 board and so far I have 12 servos attached to it from PWM pins 2 to 13.
I want to add 5 more servos but there are no more PWM pins.
So which pins do I do I use for these.

Since the HW peripherals are finished, I think you have to implement a software timer to control them. This should (never tested, though) be doable with the Arduino Servo library (formerly MegaServo). From the notes, "On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12. ". So it appears that you can use any digital pin using the default library. Did you try?

There seems to be a library called
According to this  Answer you have some possibilities:

Using ShiftPWM library
Using a timer with a generic GPIO

I'm using the MegaServo.h library. I can control the existing 12 servos but which pins do I use to add further servos. It says that the Mega Sensor Shield can support up to 48 servos. I've tried from pin 22 but it does not work.

I think the library name is missing. @MalcolmPalmer the MegaServo library was renamed to Servo; so my suggestion is to avoid using an older version


text:
Working on my second project and I'm confused about proper procedure for turning on the arduino
The first project I did was just making the led blink (it was pulsing a signal to pin 13. I'm guessing most of you have seen similar tutorials).
Today I plugged in some wires and resistors and wrote a program for a volt meter.
How am I to stop the pulses on the output pins from my previous project from messing everything up in the newer project in that interval of time after plugging in the usb and before compiling/ uploading the new code?
The question occurred to me when I saw the led blinking from the last project, before I could hit the upload button... maybe I'm wrong, but I'm envisioning this causing problems for me in the future as my circuits become more and more complex.

Just upload a blank sketch (only void setup() {} void loop() {}) before you start.

If you've rewired an Arduino board for a new project, such that outputs from the currently-loaded sketch may cause problems, temporarily jumper from ground to Reset, to hold the MCU (ATmega328, etc.) in reset until you are ready to load the new sketch.  Pull the jumper upon starting a download, of either your new project or an empty sketch as suggested in Majenko's comment.  Typically, Arduinos are reset at the beginning of each download.
Arduino boards (Uno, Nano, Mega, et al) that use an additional chip (FT232, Atmega16U2 or 32U4, CH340G, etc) as a USB interface should be able to register as USB devices even when the MCU is reset.  Arduino boards without a separate USB chip (Leonardo, Micro, et al) should not.

Someone voted this down, which is absolutely their prerogative, but I'm voting it up because it is a possible (if somewhat complex) solution. :)

@NickGammon, it's true that loading an empty sketch, or the new sketch, before attaching the new hardware is a better approach.  But if a board gets built in to controlled equipment before the old sketch is removed, powering it up not-reset  could be risky.  Is there a simpler approach than keeping the board reset?

The timing can be dodgy (you need to release reset fairly precisely) but I agree it is a viable solution, which is why I voted for it.

It is also a recommended solution for escaping from a sketch that has a watchdog timer set so quickly that the bootloader can't load.


text:
Accelstepper - how to switch from fullstep to halfstep in loop?
I am using Accelstepper library to control a unipolar stepper motor. In my project, I would like to run the stepper in full-step mode when I need speed and in half-step mode when I need precision. As you know, the full-step/half-step selection is done in the very beginning of the sketch...
I found a workaround by creating two instances of Accelstepper for the same stepper. That is:
Accelstepper fast(FULL4WIRE, 2,3,4,5);

Accelstepper slow(HALF4WIRE, 2,3,4,5);

With this, when I call (skipping other details of the code) fast.run() the motor moves fast (full-step) and when I call slow.run() it moves slowly as it is in half step mode.
But;
When it comes to determine to current motor position, this workaround fails, since there are two different values returned by the two functions: fast.currentPosition() and slow.currentPosition(). So this workaroud becomes useless.
My first question is: is there a way in Accelstepper to switch from full-step to half-step and vice versa in the execution(let say in the loop)? If so, the second question can be skipped.
The second: XX.currentPosition() function returns the value of a variable, namely "_currentPos" which is calculated in Accelstepper.cpp file. As I understand, there become, as many _currentPos values as Accelstepper instances. In my case, one for fast and another for slow, and somehow they are kept and calculated individually without any confusion. Is there a way to access (extern?) and set this variable from the sketch, by referencing the specific Accelstepper instence? Briefly, is there a way to copy one motor position to another?
Many thanks.

The documentation notes a setCurrentPosition() function.

void AccelStepper::setCurrentPosition ( long position )

Resets the current position of the motor, so that wherever the motor happens
  to be right now is considered to be the new 0 position. Useful for
  setting a zero position on a stepper after an initial hardware
  positioning move. Has the side effect of setting the current motor
  speed to 0.
Parameters
position The position in steps of wherever the motor happens to be right now.

Use the currentPosition() function to get the current position from either mode. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.

Jose, thanks for the answer. But it doen't solve the problem. Consider, the motor is at zero, when it moves 100 steps via fast.run() and then it moves 50 steps via slow.run()...In this case, fast.currentPosition() returns 100 and slow.currentPosition() returns 50, but in fact motor is at position 150! Notice, there is only one single motor although declared 2 times. By reseting the position with setCurrentPosition, you lose your starting point. If you mean that I should record the movements and recalculate in my sketch it becomes too complex as the movements are dependent on many sub-functions

Sorry I wasn't more clear. Also use the currentPosition() function. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.

I thought that the setCurrentPosition() function is only for setting the current motor position to "0". However, it is possible to set current position to anything. So, with this info, it became possible to copy/add one motor position to the other just by considering the step sizes.


text:
How to configure 16x2 character LCD to work with 8bit?
I have the LiquidCrystal library installed but all the examples are for 4bit connection, I want to drive the LCD with 8bit.
In LiquidCrystal.cpp file it says;

When the display powers up, it is configured as follows:
DL = 1;  8-bit interface data

But what's is the function, should it be like this: LiquidCrystal DL(1);? where and how should I call DL = 1;?

You don't "do" anything to enable 8 bit. As it says when the device powers up the DL bit in the configuration is already set, enabling 8 bit.
You just need to wire it for 8 bit and specify all 8 bits of wiring in the constructor.
The manual entry for the constructor shows you what parameters you can specify:

https://www.arduino.cc/reference/en/libraries/liquidcrystal/liquidcrystal/


text:
How to send message to multiple number using arduino and SIM900A mini v3.8.2?
I am using this code to send message using Arduino Uno & SIM900A mini v3.8.2 module. But I need to send same message on multiple numbers.
#include <SoftwareSerial.h>
SoftwareSerial SIM900A(10,11);
void setup()
{
  SIM900A.begin(9600);
  Serial.begin(9600);
  Serial.println ("SIM900A Ready");
  delay(100);
  Serial.println ("Type s to send message or r to receive message");
}
void loop()
{
  if (Serial.available()>0)
   switch(Serial.read())
  {
    case 's':
      SendMessage();
      break;
    case 'r':
      RecieveMessage();
      break;
  }
 if (SIM900A.available()>0)
   Serial.write(SIM900A.read());
}
 void SendMessage()
{
  Serial.println ("Sending Message");
  SIM900A.println("AT+CMGF=1");
  delay(1000);
  Serial.println ("Set SMS Number");
  SIM900A.println("AT+CMGS=\"+639176363802\"\r");
  delay(1000);
  Serial.println ("Set SMS Content");
  SIM900A.println("Sample Message");
  delay(100);
  Serial.println ("Finish");
  SIM900A.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  Serial.println ("Message has been sent");
}
 void RecieveMessage()
{
  Serial.println ("SIM900A SMS");
  delay (1000);
  SIM900A.println("AT+CNMI=2,2,0,0,0");
  delay(1000);
  Serial.write ("Unread Message done");
 }

Thank you in advance

Pass the number as a parameter to SendMessage, and call the function multiple times. NB: Many providers will block messages that are sent too rapidly to prevent spamming.

I'm sorry but can you please elaborate it more because i can't understand it clearly. I'm new at using arduino. Thank you :)


text:
How to connect an Elegoo Nano to a Raspberry Pi and program it?
I own an several Elegoo Nanos and a Raspberry Pi. I would like to connect an Elegoo Nano to the Pi and upload nanpy onto the board and control it's GPIO pins.
I have plugged the nano into the Pi and it is not recognised by the pi. I believe it is something to do with the drivers required for the nano to work. I feel this is similar to this post Arduino Nano not visible in Serial Ports (Mac OS) as I have tried and failed at connecting it to my Mac.
Any help at getting the Elegoo Nano read by the Arduino IDE on my Raspberry Pi so I can program onto it would be greatly appreciated.

Have you gone through the basic Linux troubleshooting steps?

Assuming you are familiar with the Linux OS:  Try "lsusb" or "sudo lsusb" before and after you plug in the USB device.  Note the difference and the user and manufacture ID values.  Google them to see if you have an FTDI chip or something else.  Also, see if the OS mounted your USB device in the device directory. Type "ls /dev/" before and after you plug in your USB device.  Another thought, check the permissions and group of the new device entry if there is one. It's unlikely the RPi distro of Linux is setup incorrectly, but make sure you have permissions to read/write the device.

BTW, a modern MAC is also a Unix (like) computer (the Linux OS on a RPi can be though of as a derivative of Unix).  You can open a MAC console and type the same commands as you type into the RPi above.  However, I'm not sure where the MAC's device directory (the "ls /dev" command above) is.

I think you need to install the Nano USB driver first.

The Elegoo website has a downloads page which contains the drivers.

Using the Raspberry Pi, download the zip file containing the drivers.
Unzip the contents to a location of your choice. (Also see here)
Change to the directory containing the Linux driver source files (ie CH341SER_LINUX).
In the terminal type make. Let it compile the driver.
In the terminal type make load.

Done

thanks for that link. I seem to have some problems installing the drivers.
With the following stack trace
pi@raspberrypi:~/Downloads/Elegoo CH340 Driver 2018.6.19/CH341SER_LINUX $ make
make -C /lib/modules/4.14.30-v7+/build  M=/home/pi/Downloads/Elegoo CH340 Driver 2018.6.19/CH341SER_LINUX
make[1]: *** /lib/modules/4.14.30-v7+/build: No such file or directory.  Stop.
Makefile:5: recipe for target 'default' failed
make: *** [default] Error 2

@apollowebdesigns For that error It can't find the /lib/modules/4.14.30-v7+/build directory specified in the Makefile. You may have to unzip the files to a specific location in your file system and compile them there. I think this is a question best asked on the [raspberrypi.se] or [unix.se] sites. If you get an answer, let us know and I'll update the answer.

Does this help? https://askubuntu.com/q/554624 although the build name will be different. You will need to type something like sudo apt-get install linux-headers-`uname -r`

thanks for your help. For raspberry pi, I did a fresh install of the OS and now it can detect it all and for the Mac I used brew. Thanks for your help. I'll give you the point!


text:
Why won't my code play a tone for my arduino
I have the following code that I use to try to play a melody on my Arduino, but there is no melody just a tapping noise.
I am using the built in tone() function to play on a speaker/buzzer.
I know my hardware setup is correct because running sample code online plays a nice melody.
void setup() { }
void loop() {

    noTone(6);
  // C7 in eighth
    tone(6, 2093, 250); delay(250);
    noTone(6);
    //B7 in eighth
    tone(6, 3951, 250); delay(250);
    noTone(6);
    //G7 in fourth
    tone(6, 3136, 500); delay(500);
    noTone(6);
    //G7 in eighth
    tone(6, 3136, 250); delay(250);
    noTone(6);
    //F7 in eighth
    tone(6, 2794, 250); delay(250);
    noTone(6);
    //E7 in eighth
    tone(6, 2637, 250); delay(250);
    noTone(6);
    //E7 in fourth
    tone(6, 2637, 500); delay(500);
    noTone(6);
    //G7 in eighth
    tone(6, 3136, 250); delay(250);
    noTone(6);
    //G7 in halves
    tone(6, 3136, 1000); delay(1000);
    noTone(6);
    //C6 in fourth
    tone(6, 1047, 500); delay(500);
    noTone(6);
    //B6 in eighth
    tone(6, 1976, 250); delay(250);
    noTone(6);
    //G6 in eighth
    tone(6, 1566, 250); delay(250);
    noTone(6);
    //C6 in eighth
    tone(6, 1047, 250); delay(250);
    noTone(6);

}

This is supposed to be the melody for poker face using the tone() function

you don't need noTone if you start another tone.

The sample code you link to shows pin 8 as the connection, but your code shows pin 6. If your hardware setup is "Correct" because the sample code works, you have to look at what is then different between your code and the sample code that is known to work.

I just downloaded it, and it works for me.
Hmmm.   Try downloading the other examples again, just to make sure you haven't moved a jumper.
Another way to check this out is to cut down the program to one or two lines, and see if that does or doesn't work.

What is the speaker/buzzer you are connecting to? It may need more current then the pin can support (a few tens of mA, absolute max of 40mA to prevent damaging the pin).


text:
How do I use 4 inputs on the Arduino as a binary decoder?
How do I use 4 input lines as a binary decoder? I would like to read the 4 inputs (16 variations) and based on that choose one of 16 output behaviors?
I need to be able to set my “Ten Moon Phase Indicator” (MPI ECP) circuit project to the phase of the Moon as seen in the sky on this day, or to a specific time as indicated in one of the many apps available on the Internet. Currently the MPI ECP resets to the start of the Full Moon loop, as it is the only loop available. (this code works) NOTE: Due to the circuit & Arduino processor power consumption for this application, a eternal power will be necessary.
To resolve this problem my intent is to use four of the available 14 I\O on the Arduino Uno as INPUT's employing four debounced toggle switches (with pull up resistors): (0) Off, (1) as On. The other ten available I/O's to be used for the ten Moon display OUTPUT LED's or to control ten relays.
What I would like the sketch program to accomplish:

digitalRead pins 0, 1, 12, 13
Depending on 1 of 16 resulting four on/off combinations that are possible, run a specific loop.

This is what I came up with: (note, the code does not compile, I'm new)
 void setup()  {
 pinMode(2, OUTPUT);   // New     Waxing:
 pinMode(3, OUTPUT);   // Young  Waxing:
 pinMode(4,OUTPUT);   // Crescent Waxing:
 pinMode(5, OUTPUT);   // Quarter Waxing:
 pinMode(6, OUTPUT);   // Gibbous Waxing:
 pinMode(7,OUTPUT);   // Full Moon:
 pinMode(8, OUTPUT);   // Gibbous Wanning:
 pinMode(9, OUTPUT);   // Quarter Wanning:
 pinMode(10, OUTPUT);  // Crescent Wanning:
 pinMode(11, OUTPUT);  // Old Wanning:
 pinMode(13, INPUT);  // Switch 4
 pinMode(12,INPUT);     // Switch 3
 pinMode(1, INPUT);     // Switch 2
 pinMode(0,INPUT);      // Switch 1

 } void loop() {
 int Reading = digitalRead;
Reading = digitalRead (12); Reading = digitalRead (13);
Reading = digitalRead (1);   Reading = digitalRead (0);

 if  (digitalRead(0) == HIGH; digitalRead (1)==
   HIGH; digitalRead(12) == HIGH; (digitalRead(13) == HIGH);  { } else
    {   // loop Full Moon Start   digitalWrite(7, HIGH);  // FULL MOON ON
  delay(5000);
  digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
   digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
 digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
  digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
   digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
  digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
  digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);
 digitalWrite(11, LOW);      // OLD MOON OFF
          delay(5000);
   digitalWrite(2, HIGH);  // NEW MOON ON
          delay(5000);
  digitalWrite(2, LOW);   // NEW MOON OFF
          delay(10);
 digitalWrite(3, HIGH);  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);  // YOUNG MOON OFF
          delay(100);
 digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
   digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
          delay(10);
  digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
   digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
 digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
  digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);

// loop for New moon Reset   if  (digitalRead(0) == LOW;digitalRead (1)==LOW; digitalRead(12) == LOW;(digitalRead(13) ==
    LOW);
  { } else   // loop New Moon Start
 digitalWrite(2, HIGH);  // NEW MOON ON
          delay(5000);
   digitalWrite(2, LOW);   // NEW MOON OFF
          delay(10);
   digitalWrite(3, HIGH);  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);    // YOUNG MOON OFF
          delay(100);
   digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
   digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
          delay(10);
   digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
  digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
  digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
   digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);
  digitalWrite(7, HIGH);  // FULL MOON ON
        delay(5000);
   digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
   digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
   digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
   digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
   digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
  digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
   digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);
   digitalWrite(11, LOW);      // OLD MOON OFF
          delay(5000);
 { } else  { // Young moon Reset Start
 if  (digitalRead(0) == LOW; digitalRead (1)==LOW; digitalRead(12) ==
    LOW;(digitalRead(13) == HIGH;
 )
   { } else  // loop New Moon Start
         digitalWrite(3, HIGH);
  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);    // YOUNG MOON OFF
          delay(100);
  digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
  digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
          delay(10);
   digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
  digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
  digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
  digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);
 digitalWrite(7, HIGH);    // FULL MOON ON
        delay(5000);
   digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
   digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
  digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
  digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
 digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
  digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
   digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);
  digitalWrite(11, LOW);      // OLD MOON OFF
          delay(5000);
         digitalWrite(2, HIGH);   // NEW MOON ON
          delay(5000);
   digitalWrite(2, LOW);       // NEW MOON OFF
          delay(10);
  }
 // Waxing Crescent Reset Start if  (digitalRead(0) == LOW; digitalRead (1)== LOW; digitalRead(12) ==
    HIGH; digitalRead(13) == HIGH;)    { } else  // Waxing Crescent Moon
    reset Start
  digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
   digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
          delay(10);
 digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
   digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
   digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
  digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);
  digitalWrite(7, HIGH);    // FULL MOON ON
        delay(5000);
   digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
  digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
   digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
  digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
   digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
 digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
   digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);   digitalWrite(11, LOW);      // OLD MOON OFF
         delay(5000);
   digitalWrite(2, HIGH);   // NEW MOON ON
          delay(5000);
   digitalWrite(2, LOW);      // NEW MOON OFF
          delay(10);
   digitalWrite(3, HIGH);  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);       // YOUNG MOON OFF
          delay(100);
  }
  // First Quarter Moon Reset if  (digitalRead(0) == LOW; digitalRead(1) == HIGH; digitalRead(12) ==
    HIGH; digitalRead(13) == HIGH;)   { else  {
  //FIRST QUARTER  Moon
    reset Start
digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
   digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
   digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
  digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);
  digitalWrite(7, HIGH);  // FULL MOON ON
        delay(5000);
   digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
   digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
  digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
  digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
   digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
  digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
   digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);
  digitalWrite(11, LOW);      // OLD MOON OFF
          delay(5000);
  digitalWrite(2, HIGH);   // NEW MOON ON
          delay(5000);
  digitalWrite(2, LOW);    // NEW MOON OFF
          delay(10);
   digitalWrite(3, HIGH);  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);    // YOUNG MOON OFF
          delay(100);
   digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
  digitalWrite(4, LOW);        // WAX CRESCENT MOON OFF
          delay(10);
 }
// code would continue with other loops. Thanks for looking at  my 16 RESET problem, email me. Any suggestions would be appreciated

edit your code to be readable!

If the code doesn't compile, the compiler shows some error messages. Include them in your question.

If the code does compile, does it do what you want it to? If not, what does it do?

you have a lot of unnecessarily repeating code ..... put these three lines in a function digitalWrite(X, HIGH); delay(5000); digitalWrite(X, LOW);  .... then just call the function with a pin number as an argument

Edit your question, with a simple title (not a long winded explanation and commentary), put your question in the main body of text, and explain what exactly is wrong with your code. Take a look at other highly voted questions on the site to see how to write a good clear question. And indent your code correctly

This may be a little too advanced for the OP but... reading esoterik’s
answer, I couldn't help the urge to transform that big switch/case into
an array lookup. Admittedly, the syntax for declaring the array of
function pointers is a little bit esoteric. ;-)
void loop()
{
    // List of implemented behaviors.
    static void (* const behaviors[])() = {
        do0, do1, do2,  do3,  do4,  do5,  do6,  do7,
        do8, do9, do10, do11, do12, do13, do14, do15
    };

    // Build the index of the requested behavior.
    int addr = 0;
    for (int i = 0; i < 4; i++)
       addr |= digitalRead(in[i]) << i;

    // Now do it.
    behaviors[addr]();
}

Edit: To address the OP's issue. I may have missed something, but it
looks to me like all the cases do the exact same thing: loop through the
outputs, turn each one on, wait 5 seconds, then turn it off. The only
difference between the cases is the index of the output that is turned
on first. In this case, all this repetitive code can be factored into a
single loop as follows:
// Turn on then off all the outputs in turn,
// starting from the given index.
void loop_outputs(int start_index)
{
    int index = start_index;
    for (int count = 0; count < 10; count++) {

        // Light up that LED for 5 s.
        digitalWrite(out[index], HIGH);
        delay(5000);
        digitalWrite(out[index], LOW);
        delay(10);

        // Go to the next one, wrapping index 10 -> 0.
        if (++index == 10) index = 0;
    }
}

I thought about function pointers, but figured they were to complicated for this.

a skeleton solution:
int in[] = {0,1,12,13};
int out[] = {2,3,4,5,6,7,8,9,10,11};
...
void setup()
{
    for(int i=0; i < 4; i++)
        pinMode(in[i], INPUT)

    for(int i=0; i < 10; i++)
        pinMode(out[i], OUTPUT)
}
...
void do0 {...};
void do1 {...};
void do2 {...};
void do3 {...};
void do4 {...};
void do5 {...};
void do6 {...};
void do7 {...};
void do8 {...};
void do9 {...};
void do10 {...};
void do11 {...};
void do12 {...};
void do13 {...};
void do14 {...};
void do15 {...};
...
void loop()
{
    int addr = 0;
    for(int i=0; i<4; i++)
       addr |= digitalRead(in[i]) << i;

    switch(addr)
    {
    case 0:
       do0();
       break;
    case 1:
       do1();
       break;
    case 2:
       do2();
       break;
    case 3:
       do3();
       break;
    case 4:
       do4();
       break;
    case 5:
       do5();
       break;
    case 6:
       do6();
       break;
    case 7:
       do7();
       break;
    case 8:
       do8();
       break;
    case 9:
       do9();
       break;
    case 10:
       do10();
       break;
    case 11:
       do11();
       break;
    case 12:
       do12();
       break;
    case 13:
       do13();
       break;
    case 14:
       do14();
       break;
    case 15:
       do15();
       break;
    }
}

Note that A0 to A5 are available as for digitalRead() also. I normally initialize them as
byte pin14 = 14; // make the name mean something to you

pinMode (pin14, INPUT_PULLUP);

Then you can read it as

if (digitalRead(pin14) == LOW){

// pin is connected to Gnd

}

Or if you use D14-17 for your 4 inputs, you can read all 4 with a PORT read, and act on that (you still use pinMode() to initialize them):
byte addressByte = PORTC & 0x0F; // result is 0 to 15 based on state of the 4 pins

(I think PORTC is A0 to A5, might want to check that)
then read them and act accordingly. Way cleaner than a while bunch of digitalRead()s and if() statements.
switch(addressByte){

case 0:

// whatever happens

:

:

case 15:

// whatever happens
}

“I think PORTC is A0 to A5”. The OP is using an Uno, and this is indeed correct on that board.


text:
Troubleshooting WS2812B LED strip
I am doing a project for my master thesis and I have 6 stripes of WS2812B LEDs each one containing 77 LEDs. I finished the design and now want to turn them on.
I used an old power supply to power it, but now that I am running it, doesn't work. I checked the voltage with a multimeter and it shows that I have 5 volts and it seems doesn't have any problem but the data doesn't transfer to my strip.
I just copy past FastLED from libraries and changed the number of LEDs. I thought maybe I am using the Funduino from school, maybe this is a problem and I need another Arduino board?

Please show us a schematic or wiring diagram on the picture we cannot really see the connections. Have you tried to only connect 1 little strip for testing? And please show us your code (you can add it to your question by editing it. Don't forget to format it correctly by selecting it and clicking the {} button of the editor).

Since, in the photo, you are only testing with a very short strip of 4 leds, I'd suggest try powering the strip from the Arduino's 5V. Just to make sure that the code works. After that you can add the PC power supply.

Please show us your code

Are you completely sure that these are WS2812B LEDs? To read more, check out this great link from Core Electronics:
https://core-electronics.com.au/tutorials/addressable-rgb-led-controllers.html
It is more than likely your code. Download the code from a known working example and get that working. Try using an example program such as:

https://howtomechatronics.com/tutorials/arduino/how-to-control-ws2812b-individually-addressable-leds-using-arduino/
https://core-electronics.com.au/tutorials/ws2812-addressable-leds-arduino-quickstart-guide.html
https://learn.adafruit.com/adafruit-neopixel-uberguide/software

Once you have known working hardware then delve into your own code and find the problem.
Also check your wiring with fresh eyes. It could be something simple.


text:
esp8266 WiFi Cannot Connect to a PHP Server
I am using a magnetic float switch sensor to monitor water level in a tank. I am using a ESP8266 board.
I am trying to send the data collected by it to a php page in a host called "weris.link". I've checked the WiFi ssid and password for a myriad of times, yet somehow the connection to server still failed.
Did i commit a mistake ?
Here's my code :
#include <ESP8266WiFi.h>
#define FLOAT_SENSOR  D2     // the number of the pushbutton pin
#define LED           D8      // the number of the LED pin

const char* server = "weris.link"; // alamat server
const char* ssid = "aBee"; // SSID router wifi
const char* password = "xxxxx"; // password wifi
const char* SensorID = "Water_Level_Kelompok_1.Unsrat"; // ID sensor

const char* count1= "Water Tank Full";
const char* count2= "Water Level Low";
const char* recommend1= "Turn Off Flow";
const char* recommend2= "Turn on Flow";

WiFiClient client;

void setup()
{
  Serial.begin(115200);
  // initialize the LED pin as an output:
  pinMode(LED, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(FLOAT_SENSOR, INPUT_PULLUP);

  WiFi.begin(ssid, password);

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

void loop()
{
  if(digitalRead(FLOAT_SENSOR) == LOW)
  {
    // turn LED on:
    digitalWrite(LED, HIGH);
    Serial.println(count1);
  }
  else
  {
    // turn LED off:
    digitalWrite(LED, LOW);
    Serial.println(count2);
  }
  // mulai Kirim data sensor
   if (client.connect(server,80 && LED == HIGH)) {
    Serial.print("Posting data...");
    digitalWrite(BUILTIN_LED, LOW);
    Serial.println("Tank Full: " + String(count1) + ", Tank Level Below Normal: " + String(count2));

// dengan GET /path file php penangkap data
client.println("GET /iot/terima.php?data1=" + String(count1) + "&data2=" + String(recommend1) + "&sid=" +SensorID+ " HTTP/1.1");
client.println("HOST: weris.link");
client.println("Connection: close");
client.println();
client.stop();
Serial.println();
digitalWrite(BUILTIN_LED, HIGH);
}

else if(client.connect(server,80 && LED == LOW)) {
  client.println("GET /iot/terima.php?data1=" + String(count2) + "&data2=" + String(recommend2) + "&sid=" +SensorID+ " HTTP/1.1");
  client.println("HOST: weris.link");
  client.println("Connection: close");
  client.println();
  client.stop();
  Serial.println();
  digitalWrite(BUILTIN_LED, HIGH);
 }
  else {
Serial.println("Koneksi ke server gagal");
 }
  delay(5000);
}

Below is the screen capture from the serial monitor

This line:
if (client.connect(server,80 && LED == HIGH)) {

is definitely not going to do anything useful. Nor is this line:
else if(client.connect(server,80 && LED == LOW)) {

In both lines you're take the logical AND of the number 80 and the result of testing the LED.
Put the closing parenthesis in correct place:
if (client.connect(server,80) && LED == HIGH) {

and
else if(client.connect(server,80) && LED == LOW) {

Written this way you're still connecting twice if the LED is LOW. The code would be better written:
if (client.connect(server,80)) {
    if(LED == HIGH) {
      do stuff
    } else {
      do other stuff
    }
}

Even better would be to have the do stuff and do other stuff sections just set some variables and then write the code to talk to the web server once, using those variables. Having a single instance of the code will help avoid bugs in the future if you ever need to change it - the DRY (Don't Repeat Yourself) principle of programming.
Also, I hope you didn't just publish your wifi password here. If you did, you should change it.

LED is a pin number not a pin state.

good point! I'm sure that @Kenneth W. A. can take it as an exercise for the reader to correct that part of his code :)

Thank you very much, i really appreciate the help, restructured my code, it's working now


text:
Using digital weighing scales with INA125p
Complete electronics beginner here. I'm attempting to build a weighing scale with an Arduino.
I'm attempting to follow this tutorial, with the shield that they use.

I've arranged my load cells on the scale into a Wheatstone Bridge, and I can get some readings just by taking a voltage reading from the two cells marked V+ and V-. The board has terminals that are linked to a INA125p, and the pins should give an amplified reading.
Pin A1:0.96
Pin A2:1.42
Pin A3:5.00
Pin A4:5.00
Pin A5:5.00

Regardless of whether I have the scale wired in or not, I get these readings from the individual pins. The scales seem to be able to take power from the Arduino shield.
The scales that I have are different from the ones in the example. From what I can figure out, the yellow cables that they reference turn their particular scale on when weight is put on it.
I've put the wires where I take the reading into the 2 and 4 terminals on the circuit board that they have (where the tutorial references a differential signal), but again, it makes no change.

unsolder or cut the white wire that is referred to as G3 (Wheatstone bridge mass) on the original printed circuit, extend take it to terminal 1 on the new printed circuit;
unsolder or cut the white wire that is referred to as G2 (Wheatstone
  bridge positive) on the original printed circuit, extend take it to
  terminal 3 on the new printed circuit;
unsolder or cut the white wire that is referred to as G1 and G4 on the
  original printed circuit, extend take it to terminal 4 and 2 on the
  new printed circuit (differential signal on the Wheatstone bridge)

I've attempted lots of different combinations of cables and terminals on the new circuit, but it appears to make no difference to the readings.
My question is:
Based on the tutorial and the drawing above, am I taking the readings from the correct place? Are there any things I'm obviously doing wrong with the circuit itself?
If the circuit is correct, how would I go about trying to get correct readings from the scale when I add weight to it?
I apologise for the vague nature of this question, but I am a complete beginner trying to figure this out, and I am struggling to follow the tutorial. I'll try and provide any additional information that you need.
EDIT - I have a Salter SAL-3003 SSSVDR08 scale.
Each load cell has 3 cables, Red, Black and White. The red ones are the ones marked with the V+, V- etc. On the original board, they were wired in threes.

Re “The scales that I have are different from the ones in the example”, it may help if you edit your question to include the make/model of the scale you got parts from, plus a picture of the load cell and its circuit board connection points

@jwpat7 I've added some information. The original circuit board was wired like this https://goo.gl/photos/epmSuzkkyNKfFSkL7 where R,W,B is red, black and white cables

Wiring 4 three-wire load cells would be done as in http://electronics.stackexchange.com/questions/102164/3-wire-load-cells-and-wheatstone-bridges-from-a-bathroom-scale/199470#199470  Each half-bridge unit would be use as essentially 2 eighths of the cell, with their middle wires corresponding to the non black or white wires in your schematic.  The raw "reading" out of the wheatstone bridge and as an input to the INA125 should be on the order of (5V*0.001 * load/capacity)

See http://arduino.stackexchange.com/a/18698/6628 for some of the load-cell wiring.

Fixed (to some extent)! Faulty connection between the INA125p and the plint it was sitting in. I refitted it and i'm now getting varied readings with the scales, but that's to be expected with the noise the INA125p generates.


text:
Is there a way to use functions defined in a library in any class?
I'm trying to design a menu interface on a 1.8'' TFT display module. I've got it working with the Adafruit_ST7735 + Adafruit_GFX libraries. At least when I was just trying out the features... But now I'm trying to organize the code in Classes as this thing will get too complex soon. I have done some Java and C, so I started learning C++. I've been reading and coding nonstop for a week now, but there are some things that I can't wrap my head around that keep me from making any progress for a couple of days already.
So... For example there's a function public void drawRect(); in Adafruit_ST7735 library and I have a function draw() that draws a bunch of related stuff to the display in my own class (Rectangle.cpp). Say I initialize the display in my main program file how can I use that drawRect() function in my Rectangle::draw()?
Also Rectangle will be used for composing other parts of the menu interface and will probably be initialized in a collection or as a member of another class.
I've tried a bunch of different things but I've come to a dead end.
EDIT:
main program:
#include "_v0_0_0.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

#include "Point.h"
#include "Rectangle.h"
#include "SomeView.h"

#define     TFT_CS  4
#define     TFT_RST 0
#define     TFT_DC  10

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
SomeView a_view;

void setup()
{
    tft.initR(INITR_BLACKTAB); // initializes the display
}

void loop()
{
    a_view.draw(); //draw something to view (a button, scrollbar, menu item, etc)
    while (true) {}
}

SomeView.h:
#include "Rectangle.h"

class SomeView {
private:
    Rectangle a_rectangle;
public:
    SomeView();
    void draw();

    const Rectangle& getRectangle() const {
        return a_rectangle;
    }

    void setRectangle(const Rectangle& rectangle) {
        a_rectangle = rectangle;
    }
};

SomeView.cpp:
#include "SomeView.h"

SomeView::SomeView() :
        a_rectangle(Point::Point(0, 0), Point::Point(0, 0)) {
}

void SomeView::draw() {
    a_rectangle.setCorners(Point::Point(0, 0), Point::Point(2, 6));
    a_rectangle.draw();

    a_rectangle.setCorners(Point::Point(20, 66), Point::Point(100, 100));
    a_rectangle.draw();
}

Rectangle.h:
#include "Point.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

class Rectangle{
private:
    Point p1;
    Point p2;
public:
    Rectangle();
    Rectangle(Point& p1, Point& p2);
    void setCorners(const Point& p1, const Point& p2);
    void draw();

    // ... getters and setters for the points
};

Rectangle.cpp:
#include "Rectangle.h"

Rectangle::Rectangle() : p1(), p2()
    {
    }

Rectangle::Rectangle(Point& p1, Point& p2) : p1(p1), p2(p2)
    {
    }

void Rectangle::setCorners(const Point& p1, const Point& p2) {
    this->p1 = p1;
    this->p2 = p2;
}

// this is where I want to use a function from the adafruit library
void Rectangle::draw() {
    Adafruit_ST7735::drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);

}

So are you asking how to pass the tft to a class after creating this object ?.... Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS,  TFT_DC, TFT_RST);

There are two basic methods to do what you want:

Inheritance
Pointer passing

Inheritance involves making your new class a child class of the Adafruit TFT class.  You new class then gets all the public functions of the Adafruit class - it essentially becomes the Adafruit class plus your extra functions overlaid over the top:
class Rectangle : public Adafruit_ST7735 {
    ...
};

You have to ensure that you provide a suitable constructor that passes the right parameters to the Adafruit parent class, and then you create a Rectangle class instead of the Adafruit class in your sketch.

Inheritance tutorial: http://www.cplusplus.com/doc/tutorial/inheritance/

That is fine if you just want one class that uses the functions from the Adafruit class.  The second option is to pass a pointer (or reference) to the Adafruit class to your other classes, either when you construct them or at function call time.  For instance, you might have:
class Rectangle {
    private:
        Adafruit_ST7735 *_tft;

    public:
        Rectangle(Adafruit_ST7735 &tft) : _tft(&tft) {}
};

Then in your function you can use:
void Rectangle::draw() {
    _tft->drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);
}

You would, of course, construct your class with:
Adafruit_ST7735 myTFTScreen(blah blah blah);
Rectangle myRect(myTFTScreen);

Then call myRect.draw();.

Yes, there is a way.
However that's not how object oriented programming (OOP) is supposed to be used, at least in theory.
Most likely you won't like my advice, but here it is: take it easy, find a good book or online course and learn to program on a system that is simpler to debug, than a microcontroller.
Your PC, for example.
C is closer to the HW than java. C++ can be seen as both of them, but there is not so much you can do without learning C, properly.
From that perspective, C++ can be seen also as a superset of C, only much more complex.
Have a look at this explanation, for example.
It's quite simple, but exhaustive. Read it carefully and you will find out that pointers are not so difficult to grasp, after all.
If you spend enough time to get the basics right, it will save you lots of frustration (and, yes, time!) later on.
For a more systematic approach, try this.

Thank you for your advice! Though this was the kind of answer I was afraid I'm going to get. It's not that I'm not willing to learn. I've read most of the material on [link]http://www.learncpp.com/ but it's like with learning... a new language :D In the beginning you start to grasp the meaning of single words or expressions but it's hard to form a meaningful text - there will be lots of grammar mistakes and cases of misused words. So I understand what you we're saying but you're also suggesting that I should put this project aside. That won't happen.

Sure, it's your time after all and a lesson is not fully learned till one has paid the price for it. But you know the saying: the wise man learns from own mistakes, while the smart one learns from others'  ;-)

More to the point of the question you asked: you got my answer because you question is too generic and doesn't show exactly what you are trying to do, why, how and what error you get. Lacking that, you get the rubber stamp answer.

I thought my question was descriptive enough (though a bit emotional while still trying the best to express myself) but I didn't provide any concrete examples of what I have been doing because my last experiments have become so desperate and ridiculous that these won't have any descriptive value to my problem. I tried to keep it generic also to strip away details which I thought of as being trivial. Also I feel like none of your answers have been more on point than my question.

Indeed. That's what you get for not being clear/precise enough.
How do you think that the answer could be more precise than the question? If I had a working crystal ball, I'd be hitting a different type of website. The type specialized in trading stocks.

Can you be more clear about what was not so clear in my question. I don't own a crystal ball either :D I'm not writing this in my fist language and I'm asking about a programming language that I'm still new to. I'm really OK with providing more info, but I'm not OK with noob-shaming or degrading attitude towards someone who is willing to learn, but needs a little push.

I don't see what noob shaming there is in my answer. It's a heartfelt advice about how to optimize your progress.
Btw, you already got an answer by OP but, as expected, it was not what you wanted. If you only would post the code you are trying to run, even as an example, as long as it represents what you really want to do, it would be possible to have a concrete discussion. Without that, it will be just frustration from both ends.

I don't think Igor's answer was noob-shaming or degrading at all. I looked at your question and couldn't really see what you were asking. You said I've tried a bunch of different things but I've come to a dead end. - is the problem a compile error? If so, what is it? Is it compiling but not working? Your topic is Is there a way to use functions defined in a library in any class? - well, yes there is a way. Otherwise there wouldn't be much point in having libraries, if they couldn't be used anywhere. Can you post a more specific question?

authors: Κωνσταντίνος Πλατσατούρας


text:
Accuracy of liquid level measurement using sonar sensor
Is it a good way to measure liquid level in a water tank using a general purpose sonar sensor? How can echoes from the tank walls affect measurement accuracy?
I have a cylinder shaped horizontal 700L water tank, used for emergency water supply. I need to measure the water level with approx. 5% accuracy and display it in my kitchen.

UPDATE! Today I found this helpful page: Home Heating Hacking Part 1 or How to Measure an Oil Tank.
I had no time to realize my idea, but it's exactly what I wanted to do. So take a look.

How is this cylinder placed? Horizontal, or standing upright.

Water tank is placed horizontally.

Sounds like an interesting project - you might just have to try it!

Since you seem to have everything... Just test it :)

I've implemented this on my 2 x 23,000 litre water tanks using 2x hc-sr04 sensors mounted on the tank lids and a nano in the pump house. Yes water is a good hard reflective surface to bounce the ultrasonic sound waves off. My tanks have an overflow outlet but not sure how well the eletronic will last? However they are cheap to replace. It is only early days but the overall the results are looking good.
Couple of points:
1.polling occurs hourly.
2.I only power the ultrasonic sensor just before taking a reading.
3.Has a sound detection sensor to alert on water pump overrun, ie a leak.
good luck

So it works.
I wonder maybe it's possible to increase the accuracy of the measurement  by putting two ~15cm PVC pipes on transducers. It could avoid receiving echo signals. What do you think?

Maybe the pipes would help? Basically you want good echos off the waters surface so mount the sensor firmly as square on to the surface as possible. I would be more inclined to buy a more accurate Ultrasonic sensor. The HC-SR04 have a resolution of 1 cm but others like the US-100 are down to the 1mm and have built-in temperature adjusted readings.


text:
SPI receive register size of ESP32
ESP32 has 64 byte SPI FIFO size, but I could not find what is the largest bit size it can receive over SPI?
P.S. I need to interface a sensor, which returns 32 bit response.
EDIT to clarify why I am asking:
I am sending 32 bit request by splitting it into 4 bytes, but do not know how to recieve 32 bit response.
This function is for sending:
uint32_t SendRequest(uint32_t Request)
{
    uint32_t Response;
    digitalWrite(PIN_CSB, LOW);
    SPI.transfer(Request >> 24);
    SPI.transfer(Request >> 16);
    SPI.transfer(Request >> 8);
    Response = SPI.transfer(Request);
    digitalWrite(PIN_CSB, HIGH);
    return (Response);
}

SPI.transfer() returns the respond after data send completely. Can I read the SPI register?
Datasheet of the sensor: https://www.murata.com/~/media/webrenewal/products/sensor/pdf/datasheet/datasheet_scc2230-e02.ashx?la=en
EDIT to update SendRequest() function:
uint32_t SendRequest(uint32_t Request)
{
    uint32_t Response = 0x00;
    digitalWrite(PIN_CSB, LOW);
    // Send the request in 8-bit sections
    SPI.transfer(Request >> 24);
    SPI.transfer(Request >> 16);
    SPI.transfer(Request >> 8);
    SPI.transfer(Request);
    digitalWrite(PIN_CSB, HIGH);
    delay(1);
    // Capture the response in 8-bit sections
    digitalWrite(PIN_CSB, LOW);
    Response = SPI.transfer(0x00);
    Response = (Response << 8) | SPI.transfer(0x00);
    Response = (Response << 8) | SPI.transfer(0x00);
    Response = (Response << 8) | SPI.transfer(0x00);
    digitalWrite(PIN_CSB, HIGH);
    delay(1);
    return (Response);
}

1 byte has 8 bits. 32 bits are 4 bytes. what is the problem?

Why I am asking, because, 32 bit data can be send by splitting it into 4 bytes. But I do not know how to capture full 32 bit  respond. I will edit my question to specify.

like 4 bytes and then <<

You don't receive the 32-bit response. You receive the 4 bytes you sent. It's then your job to recombine those bytes into the correct 32-bit value.

You mean receiving 1 byte after each 1 byte transfer? How slave device knows what to respond until command not send completely?

No, receiving the reply after you have sent the request. You send 4 bytes in the request - you then read 4 bytes for the response. Read the datasheet of the (unspecified) "device" - it will contain a protocol diagram detailing exactly what happens on each and every clock cycle of the transfer.

Exactly. But I do not know how to capture the reply after 32 bit transfer is completed. I think SPI.Transfer receives only 8 MSB of the response.

Are you sure you don't first start receiving the response after you have fully transferred your request? Just do four SPI.transfer(0x00) calls after the final request transmit to get the 4 bytes, then, depending on the byte order (little or big endian) of the 32 bit word, shift them back together. It's however not possible to know when your sensor sends the answer because you have provided no datasheet to us.

Yes, you have right. I was also doing it right know. But again I receive 0xFF.
Response = SPI.transfer(0x00);     Response = (Response << 8) | SPI.transfer(0x00);     Response = (Response << 8) | SPI.transfer(0x00);     Response = (Response << 8) | SPI.transfer(0x00);

So what are you inputting as Request?

I have updated the function in my question above. To capture the data I send zero. But for Request I am sending 32 bit SPI frames for different operations. It might have also some timing problem.

If you only ever receive all 0xFF for the response then MISO might be permanently high. Check that with a multimeter, you might have a wrong wiring


text:
How does if(serial) work, a c++ question
The Arduino documentation says if(Serial) always returns 1, except for the case where Leonardo USB serial connection delays becoming ready.
(Leonardo has two USB IDs, and switches between them for boot loader and Serial USB.  After boot loader finishes and kicks off the program, it takes a while for the USB master (e.g. your PC) to process the disconnect of the boot loader USB device and the connection of the Serial USB device.  Thus the need for a wait.)
Now "Serial" is a static external instantiation of the Serial_ class (defined as extern Serial_ Serial;).
The c++ rules, as I understand them, do not allow a constructor to return a value, nor may the class name (which is also the constructor name) be used as a member (function) name in the class.
"Serial" cannot be defined in class Serial_, or the if(Serial) syntax would have to be if(Serial.Serial).
"Serial" cannot be defined outside the class Serial_, or it will conflict with (i.e. hide) the definition of Serial as an instantiation of Serial_.
So how does the Arduino IDE do it?
All I can think of is that the magic pre-scanner does something...  But what exactly, pray tell?

BTW, I switched over to [link]http://drazzy.com/package_drazzy.com_index.json[/link] Spence Konde core and fixed my compile problems.  Sometimes it's a real pain to figure out what is the latest/greatest most evolved / currently developed package to use.

Serial isn't the class name, its the instance name.

@Matt, while what you say is true, where is it misused in the question?  Understand that I can't fix the case in the title (StackExchange edit restriction), and that if(serial) is a quote from the Arduino people, who are trying to dumb things down.  I did say Serial is the instance of Serial_.  So, pray tell, what other words need correction?

It's not the constructor that's returning the value, it's the bool operator:
Uno:
HardwareSerial::operator bool() {
    return true;
}

Leonardo:
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

When you use the object in a setting where a boolean value is expected of it (e.g., if, while etc.) the bool() operator is called (if it exists) and that value is used.
More specifically, the bool() operator is called when the object is being cast to a bool type, either implicitly (as in if...) or explicitly (as in ... = (bool)Serial;).
More on C++ class operators here: http://en.cppreference.com/w/cpp/language/operators

Thanks @Majenjo.  C++ has been inactive quite a while for me, and now that you point it out, I'm doing "head slaps" over how obvious it is!


text:
attiny85: ISR not triggering for PCINT2?
I am using an attiny85 to read the fan speed reported by a pair of 4-wire fans. I had planned to attach the TACH output from the fans to pins 1 and 2, but I ran into a problem: I was able to handle interrupts on pin 1 without a problem, but I can't get the ISR to trigger for changes on pin 2.  Code demonstrating the problem looks like this:
#define PIN_LED 0
#define PIN_TACH2 2

void setup() {
  cli();
  pinMode(PIN_TACH2, INPUT_PULLUP);
  pinMode(PIN_LED, OUTPUT);

  GIMSK |= _BV(PCIE);
  PCMSK |= _BV(digitalPinToPCMSKbit(PIN_TACH2));
  sei();
}

void loop() {
  digitalWrite(PIN_LED, 1);
  delay(2000);
}

ISR(PCINT0_vect) {
  byte tach2;

  tach2 = (PINB & _BV(PIN_TACH2));

  if (! tach2) {
    digitalWrite(PIN_LED, 0);
  }
}

If I replace the definitions of PIN_TACH2 and PIN_TACH2_INT with
pin 1, such as...
#define PIN_TACH2 1
#define PIN_TACH2_INT PCINT1

...it works just fine (interrupts also works for pins 0 and 3).
Why can't I handle pin change interrupts for pin 2?
for @chrisl
This is just testing code. The LED remains on until the ISR fires, at which point it will go out for up to 2 seconds.  With interrupts attached to pins 1 or 3, it works as expected: a falling edge on the pin causes the LED to go off.
On pin 2, the ISR never triggers.

I don't quite understand, what your code should do. You are only turning the LED on every 2s. Explain further what you expect, what happens instead and what can you see using pins 1 or 3

PCINT should turn LED off. Within 2 seconds it will come on again. Simple testing code. With PCINT1/3 it apparently works (LED can be turned off) but not with PCINT2. Looks to me like it should work, but what do I know?

I assume there is a 1:1 mapping between pin numbers and PORTB bits?

@majenko it looks like it based on the datasheet.

You won't find that in the datasheet. You'll only find it in the source code or documentation for whatever core / board definition you are using.

The PCINT* constants are straight from the data sheet and refer to bits in the PCMSK register.  Looking at the board definition, it appears to follow the same pin numbering as the datasheet.

Ok, that all looks fine then. I must say I don't know why it's not working.

Do you have another attiny chip? The one you’re using could be damaged.

@Gerben I see the same behavior with a second attiny chip.

So, it turns out that it was a really stupid problem and entirely my fault, but I'm going to leave this question here in the hopes that it will prevent someone else from running into the same issue.
The answer is...
DISCONNECT THE PROGRAMMER BEFORE TESTING YOUR SKETCH
That's it.  With the programmer disconnected, it all behaves as expected.

Since this is the solution for your problem, please accept your answer as the correct one, so that others can see, that this was right

@chrisl, you have to wait for two days to accept your own answer.

I think 2 days passed already, its time


text:
My software serial code won't work at > 4800bps
I've put together a simple software serial (send-only) implementation for use on my attiny8[45] microcontrollers.  I realize that there are more efficient USI-based implementations out there; this was mostly an educational exercise.  The code uses TIMER0 in CTC mode to time the sending of bits on an available output pin.
It works fine from 300bps up to 4800bps, but anything faster than that just results in garbage.
The complete code is at the bottom of this answer.    The following settings all work correctly:

4800bps
#define BPS 4800
#define SCALE_FLAG 1
#define SCALE_VAL 1

2400bps
#define BPS 2400
#define SCALE_FLAG 2
#define SCALE_VAL 8

1200bps
#define BPS 1200
#define SCALE_FLAG 2
#define SCALE_VAL 8

300bps
#define BPS 300
#define SCALE_FLAG 3
#define SCALE_VAL 64

While this fails:

9600bps
#define BPS 9600
#define SCALE_FLAG 1
#define SCALE_VAL 1

Because everything other than 9600bps works I'm tempted to think that my code is correct, and yet I expect that I should be able to achieve 9600bps with these microcontrollers.
Are there any obvious bugs in this code? I think that's the most likely explanation, but after poking at this for a couple of days I'm not seeing it.

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include <string.h>

#define BPS 9600
#define SCALE_FLAG 1  // This is the value that goes in the TCCR0B register
#define SCALE_VAL 1   // This is the divisor selected by SCALE_FLAG

#define TXPORT PORTB
#define TXDDR DDRB
#define TXPIN PORTB0

#define TICKS_PER_BIT (F_CPU/BPS/SCALE_VAL)
#define mS_PER_BIT (1000000/BPS/1000)
#define uS_PER_BIT ((1000000 / BPS) - (1000 * mS_PER_BIT))

typedef struct SERIAL_PORT {
    uint8_t data;
    uint8_t index;
    uint8_t busy;
} SERIAL_PORT;

void millis_init();
uint32_t millis();

void serial_init();
void serial_putchar(char c);
void serial_print(char *s);
void serial_println(char *s);
void delay(uint32_t m);

volatile SERIAL_PORT port;
volatile uint32_t _millis,
         _micros = 1000;

int main() {
    millis_init();
    serial_init();
    while (1) {
        serial_println("hello world");
        delay(500);
    }
}

void delay(uint32_t m) {
    uint32_t t_start = millis();
    while (millis() - t_start < m);
}

void millis_init() {
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        _millis = 0;
    }
}

uint32_t millis() {
    uint32_t x;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      x = _millis;
    }
    return x;
}

void serial_init() {
    DDRB |= 1<<TXPIN;       // Set TXPIN as an output
    TXPORT |= 1<<TXPIN;     // Set TXPIN high (serial idle)
    TCCR0A = 1<<WGM01;      // Select CTC mode
    TCCR0B = SCALE_FLAG;    // Set clock scaler
    OCR0A = TICKS_PER_BIT;  // Set CTC target value
    TIMSK0 |= 1<<OCIE0A;    // Enable compare match interrupt
    sei();
}

void serial_putchar(char c) {
    while (port.busy);
    port.data = c;
    port.index = 0;
    port.busy = 1;
}

void serial_print(char *s) {
    while (*s) serial_putchar(*s++);
}

void serial_println(char *s) {
    serial_print(s);
    serial_putchar('\r');
    serial_putchar('\n');
}

ISR(TIM0_COMPA_vect) {
    if (port.busy) {
        switch(port.index) {
            case 0:
                // send start bit
                TXPORT &= ~(1<<TXPIN);
                break;
            case 9:
                // send stop bit
                TXPORT |= (1<<TXPIN);
                port.busy = 0;
                break;
            default:
                // send data bit
                if (port.data & 1) {
                    TXPORT |= 1<<TXPIN;
                } else {
                    TXPORT &= ~(1<<TXPIN);
                }
                port.data >>= 1;
                break;
        }
        port.index++;
    }

    _millis += mS_PER_BIT;

    if (uS_PER_BIT > _micros) {
        _millis++;
        _micros = 1000;
    } else {
        _micros -= uS_PER_BIT;
    }
}

What is your clock frequency?

Sorry, I should have mentioned.  The attiny84 is currently running at 1Mhz.

Have you considered that you just don't have enough time to run your ISR at that speed? Simplify it (remove the millis stuff) and see if it improves.

...and if I set the clock frequency to 8Mhz instead, it starts working. I suspect you are correct.

Well for 9600 at 1MHz you have 104 ticks per bit. That's the number of clock cycles you have to git your ISR into, and that ISR compiles to around 126 clock cycles total (I didn't follow the branches, just counted the instructions).

You should move your comments into an answer, because (a) you took the time to look at it, (b) you were spot on, and (c) you even beat me to the cycle counting, which is what I was doing just now :)

At 1MHz and 9600 baud, you have a total of 104 clock cycles available to run your interrupt routine in.  A quick count up of the assembly instructions generated comes to more than that (around 126 at first glance), so you can't fit it into the time.
As a result, your baud rate will actually be lower than 9600, and the chip will be completely starved of clock cycles for doing anything in your main loop.


text:
Diode lights generate false interruptions
I have spent quite a considerable time debugging my code that was triggering false interruptions. I have found out that the source of the error were the diode lights (on the picture). I would like to ask if anyone can point me to the possible source of such behaviour.
I will try to explain really briefly what the issue was providing only needed (from my point of view) details. If you would require more - tell me.
So, I have a board that looks like this:

You can see two reed switches (close circuit in the presence of a magnet) which leads the INT0 (pin 2) and INT1 (pin 3) on arduino to trigger an interruption on their RISING behaviour. The pull down resistors are 1kOhm. This cirquit works perfectly.
The original version of this circuit had lights in positions D5-D10 and D19-D24 (between the reed switches and the connections to the interruptor pins). The lights are these:

The part of the circuit with the red light (connected to INT1) worked flawlessly, while the circuit with the green light (connected to INT0) every once in a while triggered a false interruption in INT1. The lights, however were always blinking correctly.
I have nearly no experience with circuits and hardware, so a pointer on where to start reading to understand the issue is also welcome. Hope to hear from someone who knows what the cause could have been. I would still like to use the lights somehow, because they give a nice feedback on what is happening to the system.
Thanks!
PS. I do not think the code is necessary here, but I will post it too if you like. I am however quite confident that the bug is not on the software side.

Could be mechanical. Like the reed switch triggering due to vibration. Try swapping the two reed switches.

@Gerben, I though about it too. But the reed switches are far away from each other and while I test one, the other just rests on the table. The issue is definitely with the lights. When I take the lights out of the circuit everything works as intended.

What do you use the leds for? and.. They were with a series resistor, right?

@frarugi87, what do you mean by the series resistor? I'm afraid I don't understand that. I use them to indicate that the circuit has been closed. Just for visual information, that the magnet is close enough to trigger the reed switch. The actual functionality does not rely on lights of course. But it is nice to have such an indication.

Now I think I understood your problem ;) check my answer

Aaaaah, ok, now I see...
You put

+5V - Reed - LED - input pin - 1k resistor - ground

right?
If so the problem is that a red led has (usually) a voltage drop of about 1.5V, while the green one has a voltage drop of 1.8V-2.0V. The Atmega 328P has a Vih (i.e. the minimum voltage needed for a reliable high) of 0.6*Vcc, so for a 5V supply this value is 3V.
Consequently with a green LED you will have a value TOO CLOSE to the minimum acceptable value for the input pin. Note that the 2.0V value is an usual one, but different leds have different voltages.
Moreover the so-called high-brightness leds (the ones with a transparent case) have a more-than-3V voltage drop, so if you put for instance a blue led you will never receive a signal.
To solve the problem, you have three solutions:
1) use a (low brightness) red led also for the green path
2) remove the led from that path and drive it directly with the arduino (you will have also the notification that arduino has understood the command)
3) change the path to

+5V - Reed - input pin - LED - 1k resistor - ground

(i.e. take the voltage BEFORE the led, not after)
I think it'll work then :)
EDIT: according to the data I found on the internet the red led is usually 1.8V, while the green one is usually 2.1V. This does not change my answer, anyway.
And... You won't "fry" your pins with the 5V you are prividing to the circuit....

Thanks, that sounds about right! Thanks for the nice explanation! As the last small question - can you elaborate a bit more on your last sentence? "You won't "fry" your pins with the 5V you are providing to the circuit...." - am I on the way to doing this the way I've been addressing the problem?

That sentence was a reply to the edit to another answer (and the answerer removed the answer, so the sentence is meaningless now). He said that you'd better put the reed towards ground instead of vcc, otherwise you could fry the board. But this is not true, or at least this won't solve the problem. The only way to fry a pin with 5V is to connect it to Vcc and set it as an output in the arduino, but the same applies to a pin towards ground. If you set it as an input you can't fry it with 5V.

thanks! That agrees with what I know :) Then the issue is closed. Thank you again :)


text:
ESP8266 Returns 'invalid' - Cause 4
I have tried to get the Ai-Thinker ESP8266 working at all. If you hook it up to an Uno you have garbage returned no matter what the baud rate is. Tried softwareSerial on D3 and D4 (switching pins doesn't help) and over D0 and D1 with no sketch (to send AT commands directly to the device because softwareSerial wasn't working).
I'm using a logic converter from 5v to 3.3v to handle the voltage correctly.
I also know for a fact you can do that. I've done it a bunch with Bluetooth. HC-05.
NOTE: Pins in the wrong order won't return anything, in order to get garbage it needs to be wired correctly.
I also have a FTDI module that functions as another passthrough unit for this. It has a jumper for 3.3v to 5v and will stay on 3.3v as these units are unable to handle 5v.
I used PuTTY in order to view the boot information of this chip. On boot it returns this information.
So here's my issue.
ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x40100000, len 816, room 16
tail 0
chksum 0x8d
load 0x3ffe8000, len 788, room 8
tail 12
chksum 0xcf
ho 0 tail 12 room 4
load 0x3ffe8314, len 288, room 12
tail 4
chksum 0xcf
csum 0xcf

2nd boot version : 1.2
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd▒C▒
Ai-Thinker Technology Co. Ltd.

invalid

At the end of the day this invalid line means that the wifi information (from what I understand) is corrupted. It also refreshes this information over and over and WILL NOT accept AT commands so I can't seem to chase it down.
I am afraid that by attempting to update it if this kind of issue happens it will be bricked.
Both of these modules are opened today and I have tested another 8266 with similar results.
Any help would be appreciated.

Try SoftwareSerial on other pins. D0 and D1 is not a very good idea. These are the HardwareSerial pins. What sketch are you using? And how do you wire the ESP8266? 3V3 power supply?

In order. I used it to be a conduit to get to the chip directly so you don't have to use arduino code. Yes I know how bad it can be for live. I was using software serial to prototype the pins for when it worked. D3 and D4 with everything through a logic 5v to 3.3v converter. No sketch currently. I'm also using A FTDI usb to attempt to access it directly as stated in the original. I'm going to append this information.

I have seen cause: 4 related to power issues on mine.  Try giving it external power >500mA, that can be a power hungry little chip.

I'll give it a shot

Alright so I figured it out. Thanks to user Butters for pointing me in the right direction.
The Arduino Uno DOES NOT have enough power to handle the ESP8266 itself. It needs a power source using a 5v to 3v stepdown chip. The 3v3 rail doesn't handle it by itself.

I don't know what this "invalid" means I am getting this on every boot but my device is working fine. I have tested downloading webpages and it's working. So maybe just ignore this. use cutecom it works there, didn't work in minicom maybe because of carriage return absent.

Invalid means your config is uninitialized or invalid