text:
esp_now.h: No such file or directory
Arduino: 1.8.19 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 4M (1M SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
esp_now_testing:3:21: fatal error: esp_now.h: No such file or directory
 #include <esp_now.h>
                     ^
compilation terminated.
exit status 1
esp_now.h: No such file or directory
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Couldnt compile for a node mcu esp8266 board. Have installed esp8266 library from boards manager
#include <ESP8266WiFi.h>
#include <esp_now.h>

// Variables for test data
int int_value;
float float_value;
bool bool_value = true;

// MAC Address of responder - edit as required
uint8_t broadcastAddress[] = {0x24, 0x6F, 0x28, 0x7A, 0xAE, 0x7C};

// Define a data structure
typedef struct struct_message {
 char a[32];
 int b;
 float c;
 bool d;
} struct_message;

// Create a structured object
struct_message myData;

// Peer info
esp_now_peer_info_t peerInfo;

// Callback function called when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
 Serial.print("\r\nLast Packet Send Status:\t");
 Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

void setup() {

 // Set up Serial Monitor
 Serial.begin(115200);

 // Set ESP32 as a Wi-Fi Station
 WiFi.mode(WIFI_STA);

 // Initilize ESP-NOW
 if (esp_now_init() != ESP_OK) {
   Serial.println("Error initializing ESP-NOW");
   return;
 }

 // Register the send callback
 esp_now_register_send_cb(OnDataSent);

 // Register peer
 memcpy(peerInfo.peer_addr, broadcastAddress, 6);
 peerInfo.channel = 0;
 peerInfo.encrypt = false;

 // Add peer
 if (esp_now_add_peer(&peerInfo) != ESP_OK){
   Serial.println("Failed to add peer");
   return;
 }
}

void loop() {

 // Create test data

 // Generate a random integer
 int_value = random(1,20);

 // Use integer to make a new float
 float_value = 1.3 * int_value;

 // Invert the boolean value
 bool_value = !bool_value;

 // Format structured data
 strcpy(myData.a, "Welcome");
 myData.b = int_value;
 myData.c = float_value;
 myData.d = bool_value;

 // Send message via ESP-NOW
 esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));

 if (result == ESP_OK) {
   Serial.println("Sending confirmed");
 }
 else {
   Serial.println("Sending error");
 }
 delay(2000);
}

Where did you get this code from? Although it does load <ESP8266WiFi.h>, the rest of this code seems to be for an ESP32 and not an ESP8266/NodeMCU.

To use ESP-NOW with ESP8266 and Arduino IDE, you must use the "espnow.h" header file. In this case, the error codes change and only need to use int values for success(0). esp_now_peer_info_t is not required to add peers. Here is the code:
#include <ESP8266WiFi.h>
#include <espnow.h>

// Variables for test data
int int_value;
float float_value;
bool bool_value = true;

// MAC Address of responder - edit as required
uint8_t broadcastAddress[] = {0x24, 0x6F, 0x28, 0x7A, 0xAE, 0x7C};

// Define a data structure
typedef struct struct_message {
 char a[32];
 int b;
 float c;
 bool d;
} struct_message;

// Create a structured object
struct_message myData;

// Callback function called when data is sent
void OnDataSent(uint8_t *mac_addr, uint8_t status) {
 Serial.print("\r\nLast Packet Send Status:\t");
 Serial.println(status == 0 ? "Delivery Success" : "Delivery Fail");
}

void setup() {

 // Set up Serial Monitor
 Serial.begin(115200);

 // Set ESP32 as a Wi-Fi Station
 WiFi.mode(WIFI_STA);

 // Initilize ESP-NOW
 if (esp_now_init() != 0) {
   Serial.println("Error initializing ESP-NOW");
   return;
 }

 // Register the send callback
 esp_now_register_send_cb(OnDataSent);

 // Add peer
 if (esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 0, NULL, 0) != 0){
   Serial.println("Failed to add peer");
   return;
 }
}

void loop() {

 // Create test data

 // Generate a random integer
 int_value = random(1,20);

 // Use integer to make a new float
 float_value = 1.3 * int_value;

 // Invert the boolean value
 bool_value = !bool_value;

 // Format structured data
 strcpy(myData.a, "Welcome");
 myData.b = int_value;
 myData.c = float_value;
 myData.d = bool_value;

 // Send message via ESP-NOW
 int result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));

 if (result == 0) {
   Serial.println("Sending confirmed");
 }
 else {
   Serial.println("Sending error");
 }
 delay(2000);
}

Your description of what needed to be changed is not complete. You have changed more than just the header file.


text:
Read gyro output values with other programming languages
I have a large quantity of gyro values and I read them through the Arduino serial monitor. I'd like to know how I can use these values in other programming languages (such as C/C++/Java) after the values are read. Are there particular  libraries for the Arduino that could help me in this way?

See http://arduino.stackexchange.com/questions/1850/how-can-i-reset-the-program-on-an-arduino-uno-while-the-device-isnt-recognised?rq=1. Seems to be much that same issue.

If your Arduino sketch is printing the data as ASCII numeric strings (human-readable), then any language with support for reading and writing to a serial device can interact with your Arduino on the port it is connected to, and collect the gyro data as it is being sent.

Yes, of course you can.
In C/C++ there are different libraries depending on your operating system - that is if you even really need a library to help you at all (in Linux you certainly don't - you just use standard system calls - open, read, etc).
In Java there are a few different ones.  RXTX is a common (though not very good) one.  Personally I ise JSSC(Java Simple Serial Connector) since it contains the JNI files for all the main platforms - you don't have to get the right separate library packages for your specific OS like you do with RXTX.
Then of course there's things like PySerial for Python, Device::SerialPort for Perl, and whatever nonsense Microsoft have created for C# and their .NET stuff.
So in general: pick a language you are comfortable with, then ask Google how to use the serial port in it.

source: Stack Exchange

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

sort: votes


text:
Can't send HTTP request using ESP8266 and Arduino Uno
I have an Arduino Uno and for Wifi an ESP8266.
My ESP8266 Firmware is
AT+GMR

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

baund = 115200,
 Both NL & CR

Server -- www.linysoft.com
The URL I want to send is either: http://www.linysoft.com/arduino/?light=off OR http://www.linysoft.com/arduino/?light=on.
Depending on to the link I send the result should be either ==> on or ==> off on the page http://www.linysoft.com/arduino/light.json.
Now I want to send an HTTP request (Weblink - http://www.linysoft.com/arduino/?light=on) so it can write according to that link "on" in the light.json page.
The AT command I am sending (my wifi module is connected to my wifi automatically):
WIFI CONNECTED
WIFI GOT IP

AT+CWMODE=1

OK

AT+CIPMUX=1

OK

AT+CIPSTART=0,"TCP","www.linysoft.com",80

0,CONNECT

OK

AT+CIPSEND=0,200

OK
>

Here I am getting a problem after this > I can't send **GET /arduino/?light=on**. I also tried GET /arduino/?light=on HTTP/1.0\r\n.
After putting this line in the textbox, I press the Enter button or Send Button, but nothing happens.
It is stuck here > for some time. And then it shows me:
OK
> 0,CLOSED

Pin Connection
ARDUINO UNO        ESP8266
RX  -------------->  TX
TX  --------------> RX
VCC--------------> 3.3
CH_PD ----------> 3.3
GND -------------> GND

What technology are you using to connect to the Internet, and hence to "www.linysoft.com"? How have you checked that WiFi access point, and internet connection works?

linysoft.com is a virtual host. Just try going to http://100.42.56.28/ and see that the connection is reset.
So after the GET /arduino/?light=on, you have to also send Host: www.linysoft.com (on the next line).

The domain is missing. Try this instead:
GET http://www.linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n

Cheers!
Ref. http://contractorwolf.com/esp8266-wifi-arduino-micro/

I didn't know that was allowed in HTTP, as browsers use the Host header. But apparently using an absoluteURI is allowed.

Just found out a POST wouldn't work. Try this GET request to turn on the light.
    GET /arduino/?light=on HTTP/1.1\r\nHost: www.linysoft.com\r\n\r\n

Then you can get the status of the LED by GETting light.json like this:
    GET /arduino/light.json HTTP/1.1\r\nHost: www.linysoft.com\r\n\r\n

I was having same problem and this one solved the problem that after you get a '>'
sign then write
GET http://linysoft.com/arduino?light=on HTTP/1.0\r\n\r\n(or if you are directly writing this on serial monitor then press enter key twice and then wait for somemoment like 2-3 sec in this case dont put \r\n\r\n)
If this didnt worked then try
GET http://linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n
But in this I guess you need to specify arduino.php or arduino.html whichever type you have
and too you have to take care the cipsend should be the byte no of get request excluding \r\n\r\n and add 4 to it because we are too sending \r\n\r\n these are 4 character
I hope this will surely work for you

authors: Кристиян Илиев

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


text:
I want to pour 500ml of Water in jar with Arduino water flow controller?
I want to pour 500ML of water with Arduino water flow controller with maximum accuracy.
How will I get the maximum accuracy with this sensor?
Could someone can give suggestion for accuracy or any other sensor that i can use?

What flow controller? What accuracy?

I want to fill jar with 500 ml of water. I thought this can done with two ways either water flow controller sensor or Ultrasonic sensor. Is water flow controller sensor will pour accurate 500 ml  into jar. If it pours more or less  then my marking on jar will fails. so that' why i want accurate performance.

option three is using a scale (i.e. weigh the water). Forth option is a Liquid Level Sensor. There are probably even more solutions. PS you still haven't told what flow-controller-sensor you are using!

What flow sensor? Why is water flowing both directions through the pipe? How much money have you for 'maximum accuracy'? i.e., What accuracy do you really require? How will you turn off your water? How will you allow for the amount of water between the valve and the jar if the flow rate changes?

Flow Sensor / Fluid FLowmeter Control Switch YF-S201

Above sensor offers +/- 3% Accuracy Please refer below video https://www.youtube.com/watch?v=CtgP6Ewtinc

And you still have not updated your question with the information requested by multiple users.

I suppose that you already found a solution. If you haven't, one inexpensive way for the Arduino to sense when the water reaches the desired level is to drill two thin parallel holes into the container (using a wire gauge drill bit, provided you're not using glass or something difficult to drill) slightly below the "trigger point." Then, you can insert two thin strands of conductor so that they protrude a millimeter or less inside the container(consider something like graphite 0.5 mm pencil leads to prevent corrosion). You'll need to seal the holes using epoxy. If you make a voltage divider and put these two pencil leads in the place of the second resistor, you can measure the resistance change (using an Arduino analog input pin) when the pencil leads are "connected" by the water. Once you find the ADC value for the "water full" state of your connection, you can make the Arduino turn off the flow when this value is detected. You should place the pencil leads below the "trigger point" so that you can experiment with different delay periods between sensing the water and turning the flow off (to compensate for the water that remains in the pipe "downstream" the flow controller. I've used this approach successfully to measure flow rate, but I can't guarantee it would work in your application.

The flow meter you specified, YF-S201 Hall Effect Water Flow Meter (datasheet) measures the water flow rate, producing signal output frequency in range 16Hz (at 120L/H) to 90.2Hz (at 720L/H). Datasheet claims "error range +/- 10)". Note that this only measures the rate of flow, it is not a valve and so does not control the flow.
Problem with using a flow rate sensor to measure total quantity of water, is that you must constantly integrate the flow rate over time to get the total volume. Any errors in rate measurement or integration time, will accumulate; so this is generally not an accurate approach. Cumulative errors are highly undesirable, because they are difficult to detect and compensate. You have to not only measure the output frequency, but also carefully control the time between measurements, because you are integrating over time. This will be even more of a problem if you are printing out messages to the serial port.
If the water supply is well regulated and always provides a steady flow, then you will open the valve for a specific time interval. But if the supply pressure is not well regulated, then you may accumulate integration errors and dispensing will not always be accurate.
If you care about dispensing precisely 500mL of water, a more practical solution is to use a weigh scale (load cell). First, measure the tare weight of the empty container, then dispense (using a control loop) until net increase in weight is 500g. With this setup, the dispenser accuracy is determined by the load cell repeatability error (0.1% for a good quality load cell, a couple % for a fair quality load cell) and the measurement accuracy of the ADC (depends on resolution and reference voltage stability). You could try using the Arduino's on-chip ADC which is only 10 bits, or for best accuracy use a real 24-bit weigh scale ADC. The load sensor's offset error is set to zero by measuring the tare weight of the empty jug, so you only need to be concerned about gain error at 500mL and repeatability of the load sensor. This approach does not have cumulative errors.
You have not specified what kind of valve you will use to control the flow. If you use a solenoid value, the valve is only on-or-off, there may be some overshoot due to valve reaction time (10ms), so you will need to experiment and determine an "off threshold" before reaching 500g.
Since you have no way to compensate if the system overfills the jar, you will need to dampen the system response so that it slows down as it approaches the target level, without overfill. I'd therefore suggest using a proportional valve instead of a solenoid valve. Start with a fast flow rate when net weight <400g and then switch to a slower rate as the jar reaches its target weight.

Another option is to use a stepper motor and a Peristaltic Pump (or IV pump). You can use this to control the flow rate AND volume. For speed you need to make the motor run faster and for volume just run the stepper motor x times to get x volume. I do not know how precise it is. Good luck with what ever option you pick.

You haven't specified what level of accuracy you are aiming for so I have assumed 0.01ml.
What ever solution you go for you will also need an accurate temperature and pressure sensor, because these will affect the density of the water.
Each individual sensor you use has a degree of error associated with them.  You would nee to calibrate each sensor to establish what level of error each individual instance of a sensor has.
Weight would seem to be the best solution.  Surface tension could affect a flow metre or a contact sensor.  I have to be honest I don't see how an ultrasonic sensor could give you any degree of accuracy.  With a weight sensor you would need to establish the dry weight of the container then pour the liquid in until the desired volume was achieved.  A quick response to close the very end of the inlet pipe would be required to prevent un-necessary drips.
As to marking the container, are you using some computer controlled marking tool, because if you are just drawing on the side with a Sharpie you may as well use a measuring jug. :)
You should be able to get a weighing PCB, a pressure and temperature sensor off any of the usual electronic sites to suit you budget and the libraries will be on Git hub.


text:
Arduino loading variables from an SD card
Hello I have made a small game using and Arduino Uno and a Nokia 5110 screen. I use bitmaps to draw the images onto the screen. The problem is that bitmaps take up a lot of space and I can only use up to three bitmaps before running out of space. Is it possible to use an SD card to store the bitmaps on and have a method in the Arduino code to load a bitmap at a certain time, like when a button is pushed?

How about storing the bitmaps in program memory? And use run-length compression?

How big are the bitmaps you want to use? How much RAM is free, and how big is the program? Are you storing the bitmaps in RAM, Flash or EEPROM? That screen is 84x48, and monochrome, hence 504 Bytes is a complete screen. Several complete screens stored in Flash would likely be smaller than the SD library code.

Typically a bitmap for the Nokia 5110 (PCD8544) requires 504 bytes of memory (48*84/8). A bitmap as a initiated global variable will be stored in program memory, transfered to data memory on startup and then to the device (when drawn). Three bitmaps will use up 1.5 Kbyte. This is the limit for the Arduino Uno as an additional bitmap will require all data memory.
The first trick that can be used is to define the bitmaps in program memory with the attribute PROGMEM and when needed transfer to a buffer (504 byte) in data memory (and then to the device).
void *  memcpy_P (void *, const void *, size_t)

The second trick is to transfer the bitmap directly from the program memory to the device. This may be supported by the library. If not the bitmap draw function will need to be updated to explicitly read program memory.
The upper limit for the bitmaps is now the size of the program memory (30 Kbyte, 60 bitmaps).
Cheers!

Yes, it is possible, but is it practical?
There's basically two ways of doing it:

Load the entire bitmap into RAM for displaying multiple times
Display the bitmap direct from the SD card.

As the Uno only has 2KiB of RAM that rather limits the size of bitmap that can be loaded into it. As you currently can have 3 bitmaps in flash (max 32KiB) I will assume they are considerably bigger than 2KiB each, so loading them into RAM is not really going to be doable on the Uno.
So the second option - drawing it direct from the SD card - is really the only practical way. The problem with that is reading from the SD card is considerably slower than reading from the internal Flash.  That means that your screen updates could be really slow, which would seriously impact the playability of your game.
All that happens when you draw a bitmap normally is that a loop iterates through the data and interprets each bit of each byte as a pixel being on or off and sets the relevant pixel to be on or off on the screen.  Instead of reading data from flash you just read bytes from the SD card and interpret them in exactly the same way.  If you take a look at the bitmap drawing routine in your LCD library you will see how simple it is - replacing the Flash access with SD card reading should be a simple enough matter to implement in your own copy of the routine.
A much better option would be to use a more powerful Arduino - one that has considerably more flash, such as the Mega2560.

authors: Рустам Юнусов


text:
Why does Ethernet.begin() require a MAC address when WiFi.begin() doesn't?
I am working on an Arduino application which is dependant on a certain library. This library uses the Ethernet class for network communications, but ideally, I would like it to be wireless (I have both an Ethernet and WiFi shield available for testing).
When working on replacing the Ethernet functionality of the library with the corresponding WiFi functionality, I noticed that the Ethernet.begin() function requires a MAC address while the WiFi.begin() doesn't (it instead accepts SSID and password, among a couple of other things).
As both come shipped with a MAC address sticker on them, I couldn't really figure out why this is the case (and if I need to supply the MAC address found on the WiFi shield in some other fashion).
Why is this the case?

The flip answer would be "because it doesn't need it…"
I think what is going on is that older Ethernet shields did not have a MAC address and it was necessary for the code to set one (and I would guess that on at least some of them you can still set the MAC address, overriding the one that is on the sticker).
WiFi cards, I would guess, are newer and the MAC address is always there, so there is no need to require you to assign it.


text:
Getting NaN error in Processing when Xbee is used and trying to create a popup window.
I am trying to get data from D6T Omron thermal sensor. It works fine with both Arduino and Processing when I connect it to pc directly. However, it seems to always cannot read my last data in my data array when i use Xbee on them. It results in a NaN for my last data in my array in processing display [Fig 1].
Anyone having any thoughts on this? Any help will be much appreciated! =D
Another problem i having here is that i was trying to make a popup window when my sensor senses a sum of 34*4 in the center pixels with no success currently. The last data in the array returns in NaN error again and the program is not responding after that. [Similar with Figure 1.] D:
It actually works fine until we reach this stage "Serial.write(0x03)" from Arduino to processing when it senses a sum of 34*4 in the center. I am confused. Any idea on how to improve that? =) Thanks a lot in advance!
Attached below is my code (Arduino sketch):
#include <Wire.h>
#include <WireExt.h>

#define D6T_addr 0x0A
#define D6T_cmd 0x4C

int rbuf[35];
float tdata[16];
float t_PTAT;
float top_sum, bottom_sum, left_sum, right_sum, center_sum, center_row_sum;

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

void loop()
{
  int i;

  if (Serial.available() > 0) {
    int inByte = Serial.read();
    if (inByte == 0x0001) {

      Wire.beginTransmission(D6T_addr);
      Wire.write(D6T_cmd);
      Wire.endTransmission();

      if (WireExt.beginReception(D6T_addr) >= 0) {
        i = 0;
        for (i = 0; i < 35; i++) {
          rbuf[i] = WireExt.get_byte();
        }
        WireExt.endReception();

        t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
        for (i = 0; i < 16; i++) {
          tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
        }

        output_csv();
        delay(250);
      }
      top_sum= tdata[0] + tdata[1] + tdata[2] + tdata[3];
      bottom_sum= tdata[12] + tdata[13] + tdata[14] + tdata[15];
      right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
      left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
      center_sum= tdata[5] + tdata[6] + tdata[9] + tdata[10];
      center_row_sum= tdata[1] + tdata[2] + tdata[5] + tdata[6] + tdata[9] + tdata[10] + tdata[13] + tdata[14];

     if (center_sum>34*4)
    {
      //Serial.flush();
      Serial.write(0x0003);
      delay(100);

    }
}
  }
}

void output_csv() {
  for (int i = 0; i < 16; i++) {
    Serial.print(tdata[i]);
    if (i < 15) {
      Serial.print(",");
    }
    else {
      Serial.println();
    }
  }
}

Attached below is my code in Processing:
import processing.serial.*;
import controlP5.*;
import javax.swing.JOptionPane.*;
ControlP5 cp5;
javax.swing.JOptionPane JOptionPane;

Textlabel myTextlabelA;
boolean canStart = true;
boolean canInput = false;
boolean Start = false;
String typedText = "Comments: ";
PFont font;
int confirm;

float[] tdata = new float[17];
float tptat; // PTAT
String portName;
//int serialport = 0;

String buf;
float colourGreen; //change green in relation to temperature

int lbTemp = 25; //lowest relative temperature
int hbTemp = 40; //highest relative temperature
Serial myPort;  // Create object from Serial class

void setup() {
  size(600,768);
  background(ControlP5.BLACK);
  myPort = new Serial(this, "COM15", 9600);
  myPort.clear();
  cp5 = new ControlP5(this);

  myTextlabelA = cp5.addTextlabel("label")
                    .setText("GUI of Alive Human Detection System.")
                    .setPosition(120,10)
                    .setColorValue(#FFFAF0)
                    .setFont(createFont("Georgia",20))
                    ;

  cp5.addButton("Start")
     .setPosition(115, 670)
     .setSize(100,30)
     ;

  cp5.addButton("Stop")
     .setPosition(375, 670)
     .setSize(100,30)
     ;
}

public void Start(int theValue) {
  println("Initialising...");
  println("Connected.");
  Start = !Start;
}

public void Stop(int theValue) {
  println("Shuting Down...");
  myPort.write(0x02);
  Start = !Start;

}

void draw() {
    if (Start){

    myPort.write(0x01);
    delay(100);
    while (myPort.available() > 0) {
    delay(500);
    buf = myPort.readString();
    myPort.clear();
    tdata = float(split(buf, ','));
    for (int i = 0; i <16; i++) {
    colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
    fill (255,colourGreen,0);

      if (i == 0)
    { rect(450,64,150,150);}
      else if (i == 1)
    { rect(300,64,150,150);}
      else if (i == 2)
    { rect(150,64,150,150);}
      else if (i == 3)
    { rect(0,64,150,150);}
      else if (i == 4)
    { rect(450,214,150,150);}
      else if (i == 5)
    { rect(300,214,150,150);}
      else if (i == 6)
    { rect(150,214,150,150);}
      else if (i == 7)
    { rect(0,214,150,150);}
      else if (i == 8)
    { rect(450,364,150,150);}
      else if (i == 9)
    { rect(300,364,150,150);}
      else if (i == 10)
    { rect(150,364,150,150);}
      else if (i == 11)
    { rect(0,364,150,150);}
      else if (i == 12)
    { rect(450,514,150,150);}
      else if (i == 13)
    { rect(300,514,150,150);}
      else if (i == 14)
    { rect(150,514,150,150);}
      else if (i == 15)
    { rect(0,514,150,150); }

    if (tdata[i]<5) {fill(255);} else {fill(0);}
      if (i ==0)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),525, 139);}
      else if (i == 1)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),375, 139);
      }
      else if (i == 2)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 139);
      }
      else if (i == 3)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),75, 139);
      }
      else if (i == 4)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 289);
      }
      else if (i == 5)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 289);
      }
      else if (i == 6)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 289);
      }
      else if (i == 7)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 289);
      }
      else if (i == 8)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 439);
      }
      else if (i == 9)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 439);
      }
      else if (i == 10)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 439);
      }
      else if (i == 11)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 439);
      }
      else if (i == 12)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 592);
      }
      else if (i == 13)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 592);
      }
      else if (i == 14)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 592);
      }
      else if (i == 15)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 592);
      }
    }
    delay(250);
    CheckSerial();
  }

    }

}

void CheckSerial()
{
    confirm = myPort.read();
    if (confirm == 0x03)
  {
  int dialogResult = JOptionPane.showConfirmDialog (null, "Human found? Please Confirm!!", "Alert!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
  if(dialogResult == JOptionPane.YES_OPTION)
  {
  //futher action
  }
  }
}

Have you tried displaying the string you are receiving in order to confirm it's correct?

Okay! i will try again. =) thanks! @Majenko

@Majenko I tried to change my code a bit but still no positive result. Whenever it detected 32*4, Arduino should be sending Serial.print("found"); to processing and processing should be reading the string "found" and then showing a popup window in result.
In real scenario, when it meet the condition, and Arduino started to Serial.print ("found") , I got ArrayIndexOutOfBoundException :1 in processing and the program is not responding after that. I have no idea where seems to be the problem. D: Any suggestion on how to improve these?


text:
Why can't I print boolean variable values (0 and 1) through println function?
source code :
int buttonPin = 8;
boolean buttonState = 0;

void setup()
{
   Serial.begin(9600);
   pinMode (buttonPin, INPUT);
}

void loop()
{
   buttonState = digitalRead(buttonPin);
   Serial.println(buttonState);
   delay(500);
}

But when, instead of boolean I specify an int data type for buttonState variable it produces the result I want i.e. 1 when pressed and 0 when not pressed.
Is it related to the way these variables when stated with different data types give different values to the println() function to convert them into ASCII values?

Works fine for me. What version of the IDE are you running, and more importantly, what version of the AVR boards package does it have installed?

I also have no problems with the above code.

After testing your sketch using boolean, bool, and byte, they all worked correctly. Using bool with IDE version 1.0.6.2 and GCC version 4.2.1, increased the binary sketch size by 108 bytes (ouch). If boolean doesn't work for you, try using byte. Both variable types occupy one byte of memory.

First, you are not supposed to use boolean with digitalRead.
The function prototype in Arduino.h is:
int digitalRead(uint8_t);

Thus, the correct data type for buttonState in your code is int. Then your other problem goes away. What I am guessing is happening is that the version of the IDE you are using does not have an overloaded function for Serial.println that takes a boolean argument, and the compiler is casting it to byte, in which case it would print as 0x00 (LOW) or 0x01 (HIGH) which are not printable characters.
Unfortunately the documentation for digitalRead on the Arduino site does not mention the datatype, it just mentions that it returns HIGH or LOW which isn't very helpful to help you work out what data type to use. BTW, neither of those values are, per se, booleans. If they had said it returns true or false you might reasonably put the result into a boolean field.
I have tried to get the Arduino developers to improve the documentation in this respect, something they have declined to do. I raised the issue almost 4 years ago, and no-one is even assigned to this particular task.

If you insist on using the boolean type, then a reasonable way of printing would be:
Serial.println(buttonState ? "HIGH" : "LOW");

In response to some comments ...

Works fine for me. – Majenko

...

boolean is a typedef for bool. bool gets promoted to int, not byte - Majenko

What you mean by "is a typedef for bool" is in some (later) versions of the IDE.
Looking at, for example, Arduino pre-release version 0023 I see in the file wiring.h:
typedef uint8_t boolean;
typedef uint8_t byte;

So you can clearly see that boolean and byte are the same, and therefore that using boolean would be treated as byte. Now if you look at the Print class in that release:
class Print
{
  private:
    void printNumber(unsigned long, uint8_t);
    void printFloat(double, uint8_t);
  public:
    virtual void write(uint8_t) = 0;
    virtual void write(const char *str);
    virtual void write(const uint8_t *buffer, size_t size);

    void print(const String &);
    void print(const char[]);
    void print(char, int = BYTE);
    void print(unsigned char, int = BYTE);
    void print(int, int = DEC);
    void print(unsigned int, int = DEC);
    void print(long, int = DEC);
    void print(unsigned long, int = DEC);
    void print(double, int = 2);

    void println(const String &s);
    void println(const char[]);
    void println(char, int = BYTE);
    void println(unsigned char, int = BYTE);
    void println(int, int = DEC);
    void println(unsigned int, int = DEC);
    void println(long, int = DEC);
    void println(unsigned long, int = DEC);
    void println(double, int = 2);
    void println(void);
};

So you can see that the overload for print and println treats an unsigned char (effectively uint8_t) to be printed with BYTE default treatment and not DEC treatment.
BYTE is declared:
#define BYTE 0

And the writing is done thus:
void Print::print(unsigned long n, int base)
{
  if (base == 0) write(n);
  else printNumber(n, base);
}

What this boils down to is that both byte and boolean will be written as "binary" bytes, not converted into decimal.
As Majenko says, things are different today, and boolean is now equivalent to bool which is promoted to int.

ElectroManiac did not respond to a question about what version of the IDE s/he is using, however my point is that for some versions of the IDE my explanation is true.

Oh, and assigning the return of digitalRead to a bool is perfectly valid ...

Yes, for bool, but the question was about boolean. Whilst we know, by reading the code and reading the documentation, that digitalRead will return a 0 or 1, the fact that the return type is int means that the compiler can potentially see that you are stuffing a 16-bit return value into a 8-bit variable which will possibly lead to data truncation.
I must admit I don't get a warning when compiling with the Arduino IDE, however there is certainly the potential for truncation. A test program written in C++ and compiled with the -Wconversion flag gives a suitable warning:
warning: conversion to ‘uint8_t {aka unsigned char}’ from ‘int’ may alter its value [-Wconversion]

(There is no warning if you are placing the result into bool, however that is not the version of the IDE that the OP is using).

aren't HIGH/LOW, true/false or 0/1 the same thing for the micro controller?Like these values are interpreted by the micro controller as the same bit 0 and bit 1.

Depends what you mean by "the same thing". Internally they are. However to the compiler, different types may mean that it calls a different function for printing, particularly when you use overloaded C++ functions, which println is an example of.

I am unable to get a complete insight into the print() or println() function from the Arduino site.

Like if you give a INT type number like 123, is it segregating the number to individual digits like 1,2 and 3 and then converting it to binary data to be interpreted by the Arduino and then converting these digits to ASCII charcter representing that same number and then prints it on screen! And since print() takes all data types(being an  overloaded function),

and since boolean returns a BYTE data type(bit 0 and bit 1) as an argument to print() it converts it into ASCII characters which are non printable by Arduino's serial monitor. Am i right?

And if I am wrong can you please educate me with your knowledge on print() function

boolean is a typedef for bool.  bool gets promoted to int, not byte ("the type bool can be converted to int with the value false becoming 0 and true becoming 1."). In Gnu C bool is a macro giving the internal (GCC specific) _Bool type, not a byte. In Gnu C++ bool is a natively supported internal type.

Oh, and assigning the return of digitalRead to a bool is perfectly valid, since "The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true.". And since LOW just happens to be 0 and HIGH 1 they map nicely to false and true in a bool.

It could be nice to have a bool type overloaded print function though - maybe one that prints Y and N, or T and F perhaps.

@Majenko (and others) see amended answer about what boolean is a typedef for.

Like if you give a INT type number like 123, is it segregating the number to individual digits like 1,2 and 3 and then converting it to binary data to be interpreted by the Arduino - this is nothing to do with the Arduino per se. This question is about how do variables get printed which is a whole different question.

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


text:
FlySky TH9X with Arduino: cant get pulseIn() function to return sensible values for any channel
So I've got a FlySky TH9X and I'm trying to read some pulses using an Arduino Uno.
I'm just starting out so I want to get the hang of using the pulseIn function before moving onto interrupts. My problem is that, when I wire everything up, I don't get sensible values. Furthermore, they don't change even though I move around the sticks on the actual remote.
I tried to start off simple by wiring just the channel 1 of the receiver to pin 3 of the Uno. Then I used this code:
int ch1;

void setup() {
  pinMode(3, INPUT);
  Serial.begin(9600);
}

void loop() {
  ch1 = pulseIn(3, HIGH, 25000);
  Serial.print("Channel 1: ");
  Serial.println(ch1);
  delay(100);
}

The serial monitor then spits out numbers ranging from 0 up to 10000+ in a very erratic and apparently not periodic nature. I'll copy a few lines here:
Channel 1: 9989
Channel 1: 10063
Channel 1: 10068
Channel 1: 274
Channel 1: 0
Channel 1: 10085
Channel 1: 10039
Channel 1: 10336
Channel 1: 9629
Channel 1: 9959
Channel 1: 10064
Channel 1: 10088
Channel 1: 378
Channel 1: 0
Channel 1: 10044
Channel 1: 10059
Channel 1: 10424
Channel 1: 9632
Channel 1: 9867
Channel 1: 10069
Channel 1: 10067
Channel 1: 10473
Channel 1: 10037
Channel 1: 10063
Channel 1: 10063
Channel 1: 10253
Channel 1: 9677
Channel 1: 10013
Channel 1: 10064
Channel 1: 10062
Channel 1: 13

As you can see: not only are the higher-end values a whole order of magnitude too big (i thought pulses are normally between 1000 - 2000us?), but the actual range that these numbers span is far, far too wide for me to do anything with. Also, the sticks on my remote seem to have no influence on the numbers.
Can someone please help me? thank you :)
Hassan

The code looks good - at least it looks just like the code given in the docs for PulseIn().  What numbers do you get if you disconnect the receiver and tie the pin to ground or VCC?  What happens if you increase the delay from 100ms up to something like 5000 (5 seconds)?

Have you checked the RX is paired to the TX, and the correct mode is selected? Might be worth using it in an RC model to check it works as expected.  The other thing to try is to see if you can get a sensible/expected reading on an oscilloscope from that channel?

What are the shape of the pulses? Your displays themselves at 9600 baud are likely to take around 21 ms, which could be throwing out your interpretation of the data.

I'm voting to close this question because it has been abandoned for months with none of the requested detail to make it answerable ever being provided and the poster has not even returned to this site since the day the question was asked.

I would not recommend using pulseIn for reading values from the receiver.  pulseIn blocks the program until a signal is received, which is almost always undesirable.
An alternative approach would be to use CHANGE interrupts.  You get an interrupt when the signal goes high and low.  You take note of the time that each change occurs with millis and compare the times to get the duration of the signal.
Here's an example - you can add more channels if you'd like.  Note, this is using the EnableInterrupt library.
#include <EnableInterrupt.h>

#define SERIAL_PORT_SPEED 57600
#define RC_NUM_CHANNELS  2

#define RC_CH1  0
#define RC_CH2  1
#define RC_CH1_INPUT  A0
#define RC_CH2_INPUT  A1

uint32_t last_update_time = 0;
uint16_t rc_values[RC_NUM_CHANNELS];
uint32_t rc_start[RC_NUM_CHANNELS];
volatile uint16_t rc_shared[RC_NUM_CHANNELS];

void rc_read_values() {
  // read the values out of the shared, volatile array (which can change at any time)
  // and into an array that we only will only change when we call this function

  noInterrupts();
  memcpy(rc_values, (const void *)rc_shared, sizeof(rc_shared));
  interrupts();
}

void calc_input(uint8_t channel, uint8_t input_pin) {
  // This is the interrupt.  If the pin is high, we record the start
  // time of the pulse.  If the pin is low, we compare the start time
  // to the current time in order to get the length of the pulse.

  if (digitalRead(input_pin) == HIGH) {
    rc_start[channel] = micros();
  } else {
    uint16_t rc_compare = (uint16_t)(micros() - rc_start[channel]);
    rc_shared[channel] = rc_compare;
  }
}

void calc_ch1() { calc_input(RC_CH1, RC_CH1_INPUT); }
void calc_ch2() { calc_input(RC_CH2, RC_CH2_INPUT); }

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

  pinMode(RC_CH1_INPUT, INPUT);
  pinMode(RC_CH2_INPUT, INPUT);

  // set up CHANGE interrupts, so that we get notified when
  // each signal goes high or low.
  enableInterrupt(RC_CH1_INPUT, calc_ch1, CHANGE);
  enableInterrupt(RC_CH2_INPUT, calc_ch2, CHANGE);
}

void loop() {
  rc_read_values();

  Serial.print("CH1:"); Serial.println(rc_values[RC_CH1]);
  Serial.print("CH2:"); Serial.println(rc_values[RC_CH2]);

  delay(200);  // just so serial log doesn't flood
}

For a more detailed explanation, take a look here:  http://rcarduino.blogspot.com/2012/01/how-to-read-rc-receiver-with.html

Hi, thank you for your answer Ryan.
However, I do still need to know what went wrong with the pulseIn function as I would like to get that working first before moving onto interrupts. Can you offer me any advice on that?
Thanks

I'd -1 this answer, but I don't have the points yet.  The questioner clearly states that they don't want to use interrupts yet, and they would like to know why the code sample outputs seemingly random numbers.

Use a bigger timeout (30000):
int rcPin1 = 3; // PWM signal arduino pin
int rcPin2 = 4; // PWM signal arduino pin
int rcPin3 = 5; // PWM signal arduino pin
int rcPin4 = 6; // PWM signal arduino pin
int rcPin5 = 7; // PWM signal arduino pin
int rcPin6 = 8; // PWM signal arduino pin
int ch1 = 0;    // Receiver channel 1 pwm value
int ch2 = 0;    // Receiver channel 1 pwm value
int ch3 = 0;    // Receiver channel 1 pwm value
int ch4 = 0;    // Receiver channel 1 pwm value
int ch5 = 0;    // Receiver channel 1 pwm value
int ch6 = 0;    // Receiver channel 1 pwm value
void setup() {
  pinMode(rcPin1, INPUT);
  pinMode(rcPin2, INPUT);
  pinMode(rcPin3, INPUT);
  pinMode(rcPin4, INPUT);
  pinMode(rcPin5, INPUT);
  pinMode(rcPin6, INPUT);
  Serial.begin(9600);
}

void loop() {
  // Read in the length of the signal in microseconds
  ch1 = pulseIn(rcPin1, HIGH, 30000);
  Serial.print("Channel #1: ");
  Serial.println(ch1);
  ch2 = pulseIn(rcPin2, HIGH, 30000);
  Serial.print("Channel #2: ");
  Serial.println(ch2);
  ch3 = pulseIn(rcPin3, HIGH, 30000);
  Serial.print("Channel #3: ");
  Serial.println(ch3);
  ch4 = pulseIn(rcPin4, HIGH, 30000);
  Serial.print("Channel #4: ");
  Serial.println(ch4);
 ch5 = pulseIn(rcPin5, HIGH, 30000);
  Serial.print("Channel #5: ");
  Serial.println(ch5);
  ch6 = pulseIn(rcPin6, HIGH, 30000);
  Serial.print("Channel #6: ");
  Serial.println(ch6);
 delay(1000);
}

Hmm, that might possibly help, but most analog RC systems repeat every 20ms, and digital systems likely faster.  It seems like with the originally 25,000 uS even if the a pulse was "just" missed another would arrive in time, but your longer allowance is probably okay, too.  If this were the solution, then changing just this one thing would presumably make a difference, and changing it back would restore the problem.


text:
Controll the dc motor that works with 2xAA bateries using 5v
I have a toy that has a dc motor and is runing with 2xAA bateries ( i think it is 3v motor)
So i want to run it with 5v power supply.
First question: Can 5v damage the motor
Second question: i think i need to add diode but dont know what diode to add and how to determine what i need
Third question: is there a combination that i can add series of diode so i can drop voltage to 3v

yes ... 2) research motor control with arduino ... 3) yes

can drop current tl 3v ...  current is not measured in volts ... it is measured in amps

DC electric motors are usually rated to run over a range of voltages.  If you are unsure of the specifications of the DC electric motors you have, consider buying new motors which are specified to operate in a rage that includes 5VDC.
Consider not running both the processor (Arduino) and any high current demanding device off the same power source.  Such as solenoids or motors.  This is especially true for mobile devices supplied by battery voltage.  Often is the case the processor will reset (behave unexpectedly) should the supply voltage drop because of activating a solenoid or motor.
Diodes and other components are added to suppress or mitigate undesired effects of a solenoid or motor.  Inductive loads such as solenoids or motors resist changes in current flow and can damage connected components if the undesired current flow is beyond the connected component's abilities.  Read this stackexchange question/answer for more about this.
A silicon diode has a forward bias voltage drop of about 0.6 volts.  Other diodes have different forward bias voltage drops.  This wikipedia article lists a few different diodes. It may be possible to arrange enough diodes in series to drop 5 volts to 3 volts.
Consider searching for a 5VDC controllable Arduino relay module.  There are plenty on the web.  Such a device should include the circuitry to safely control the relay and the relay should provide more than adequate isolation from the DC motor.
For a learning experience, consider following this Arduino / Motor tutorial provided by Adafruit.

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


text:
ST7735s 1.8" SPI 128x160 TFT Module - White Screen
I am having an issue in my 1.8" TFT LCD module with SPI interface in Arduino Nano. I keep seeing the white screen on my tft.
I have made the following connections using Jumper cables:

RST  --- connected to D8 (on Nano)

CE/CS --- Connected to D10

DC ----  Connected to D9

DIN (MOSI) -- connected to D11

CLK --- connected to D13

VCC --- connected to 5V

BL ---- Connected to 3.3 V

GND -- connected to GND

Sorry i am new to this world, so dont know how i can provide you the wiring connections i have made and so jotted it down in this post.
I am using the Adafruit ST7735 GraphicsTest with the code modified according to the above pin:
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  The 1.14" TFT breakout
  ----> https://www.adafruit.com/product/4383
  The 1.3" TFT breakout
  ----> https://www.adafruit.com/product/4313
  The 1.54" TFT breakout
    ----> https://www.adafruit.com/product/3787
  The 2.0" TFT breakout
    ----> https://www.adafruit.com/product/4311
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

#if defined(ARDUINO_FEATHER_ESP32) // Feather Huzzah32
  #define TFT_CS         14
  #define TFT_RST        15
  #define TFT_DC         32

#elif defined(ESP8266)
  #define TFT_CS         4
  #define TFT_RST        16
  #define TFT_DC         5

#else
  // For the breakout board, you can use any 2 or 3 pins.
  // These pins will also work for the 1.8" TFT shield.
  #define TFT_CS        10
  #define TFT_RST        8 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         9
#endif

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 use:
// Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.14", 1.3", 1.54", and 2.0" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
#define TFT_MOSI 11  // Data out
#define TFT_SCLK 13  // Clock out

// For ST7735-based displays, we will use this call
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

// OR for the ST7789-based displays, we will use this call
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  Serial.print(F("Hello! ST77xx TFT Test"));

  // Use this initializer if using a 1.8" TFT screen:
  tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

  // OR use this initializer if using a 1.8" TFT screen with offset such as WaveShare:
  // tft.initR(INITR_GREENTAB);      // Init ST7735S chip, green tab

  // OR use this initializer (uncomment) if using a 1.44" TFT:
  //tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 0.96" 160x80 TFT:
  //tft.initR(INITR_MINI160x80);  // Init ST7735S mini display

  // OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT:
  //tft.init(240, 240);           // Init ST7789 240x240

  // OR use this initializer (uncomment) if using a 2.0" 320x240 TFT:
  //tft.init(240, 320);           // Init ST7789 320x240

  // OR use this initializer (uncomment) if using a 1.14" 240x135 TFT:
  //tft.init(135, 240);           // Init ST7789 240x135

  // SPI speed defaults to SPI_DEFAULT_FREQ defined in the library, you can override it here
  // Note that speed allowable depends on chip and quality of wiring, if you go too fast, you
  // may end up with a black screen some times, or all the time.
  //tft.setSPISpeed(40000000);

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  // large block of text
  tft.fillScreen(ST77XX_BLACK);
  testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE);
  delay(1000);

  // tft print function!
  tftPrintTest();
  delay(4000);

  // a single pixel
  tft.drawPixel(tft.width()/2, tft.height()/2, ST77XX_GREEN);
  delay(500);

  // line draw test
  testlines(ST77XX_YELLOW);
  delay(500);

  // optimized lines
  testfastlines(ST77XX_RED, ST77XX_BLUE);
  delay(500);

  testdrawrects(ST77XX_GREEN);
  delay(500);

  testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA);
  delay(500);

  tft.fillScreen(ST77XX_BLACK);
  testfillcircles(10, ST77XX_BLUE);
  testdrawcircles(10, ST77XX_WHITE);
  delay(500);

  testroundrects();
  delay(500);

  testtriangles();
  delay(500);

  mediabuttons();
  delay(500);

  Serial.println("done");
  delay(1000);
}

void loop() {
  tft.invertDisplay(true);
  delay(500);
  tft.invertDisplay(false);
  delay(500);
}

void testlines(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, 0, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, 0, 0, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, tft.height()-1, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color);
    delay(0);
  }
}

void testdrawtext(char *text, uint16_t color) {
  tft.setCursor(0, 0);
  tft.setTextColor(color);
  tft.setTextWrap(true);
  tft.print(text);
}

void testfastlines(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t y=0; y < tft.height(); y+=5) {
    tft.drawFastHLine(0, y, tft.width(), color1);
  }
  for (int16_t x=0; x < tft.width(); x+=5) {
    tft.drawFastVLine(x, 0, tft.height(), color2);
  }
}

void testdrawrects(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color);
  }
}

void testfillrects(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=tft.width()-1; x > 6; x-=6) {
    tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1);
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2);
  }
}

void testfillcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=radius; x < tft.width(); x+=radius*2) {
    for (int16_t y=radius; y < tft.height(); y+=radius*2) {
      tft.fillCircle(x, y, radius, color);
    }
  }
}

void testdrawcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=0; x < tft.width()+radius; x+=radius*2) {
    for (int16_t y=0; y < tft.height()+radius; y+=radius*2) {
      tft.drawCircle(x, y, radius, color);
    }
  }
}

void testtriangles() {
  tft.fillScreen(ST77XX_BLACK);
  uint16_t color = 0xF800;
  int t;
  int w = tft.width()/2;
  int x = tft.height()-1;
  int y = 0;
  int z = tft.width();
  for(t = 0 ; t <= 15; t++) {
    tft.drawTriangle(w, y, y, x, z, x, color);
    x-=4;
    y+=4;
    z-=4;
    color+=100;
  }
}

void testroundrects() {
  tft.fillScreen(ST77XX_BLACK);
  uint16_t color = 100;
  int i;
  int t;
  for(t = 0 ; t <= 4; t+=1) {
    int x = 0;
    int y = 0;
    int w = tft.width()-2;
    int h = tft.height()-2;
    for(i = 0 ; i <= 16; i+=1) {
      tft.drawRoundRect(x, y, w, h, 5, color);
      x+=2;
      y+=3;
      w-=4;
      h-=6;
      color+=1100;
    }
    color+=100;
  }
}

void tftPrintTest() {
  tft.setTextWrap(false);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 30);
  tft.setTextColor(ST77XX_RED);
  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_YELLOW);
  tft.setTextSize(2);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(3);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_BLUE);
  tft.setTextSize(4);
  tft.print(1234.567);
  delay(1500);
  tft.setCursor(0, 0);
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextColor(ST77XX_WHITE);
  tft.setTextSize(0);
  tft.println("Hello World!");
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_GREEN);
  tft.print(p, 6);
  tft.println(" Want pi?");
  tft.println(" ");
  tft.print(8675309, HEX); // print 8,675,309 out in HEX!
  tft.println(" Print HEX!");
  tft.println(" ");
  tft.setTextColor(ST77XX_WHITE);
  tft.println("Sketch has been");
  tft.println("running for: ");
  tft.setTextColor(ST77XX_MAGENTA);
  tft.print(millis() / 1000);
  tft.setTextColor(ST77XX_WHITE);
  tft.print(" seconds.");
}

void mediabuttons() {
  // play
  tft.fillScreen(ST77XX_BLACK);
  tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE);
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED);
  delay(500);
  // pause
  tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE);
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN);
  delay(500);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE);
  delay(50);
  // pause color
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN);
}

The Output of this code on serial output:
01:16:16.840 -> Hello! ST77xx TFT TestInitialized
01:16:19.829 -> 1876
01:17:44.911 -> done

I have tried many things from past two days but no luck on this issue.
I have seen the following posts and implemented but effort gone in just accumulating knowledge but unable to resolve the issues:
What am I missing? ST7735 TFT white screen
Why am I only seeing white screen in TFT 1.44 ST7735?
Kindly please let me know in case anyone resolves this issue.

Try it without the RST connected. Might work worth a try.

I have a 1.44' SPI 128x128 V2.0 [Blueish (teal) PCB, Green Tab Screen].
I was having the same problem. I had connected the VCC pin to 3.3V.
Solution: connect VCC to the 5V pin
The white screen is gone. I hope it helps.

Hmm, okay.  But, the O.P. is ("was" really) not apparently in that situation: VCC --- connected to 5V


text:
else if is ignored if not Serial.println anything before
I encountered to me inexplicable behavior on an arduino uno.
I'm serial reading a string from the serial monitor/python serial. This string is the conditional on several if/else if statements.
The crazy thing is, some strings just get ignored, but if I print out the read string after reading it, the ignored statements then get executed and the script works the way it's supposed to.
This is the code:
// power outlet 1
# define OUT_1_1 2 // relay #4
# define OUT_1_2 3 // relay #3

// power outlet 2
# define OUT_2_1 4 // relay #2
# define OUT_2_2 5 // relay #1

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  // power outlet 1
  pinMode(OUT_1_1, OUTPUT);
  pinMode(OUT_1_2, OUTPUT);

  // power outlet 2
  pinMode(OUT_2_1, OUTPUT);
  pinMode(OUT_2_2, OUTPUT);

  // init outputs to HIGH
  digitalWrite(OUT_1_1, HIGH);
  digitalWrite(OUT_1_2, HIGH);
  digitalWrite(OUT_2_1, HIGH);
  digitalWrite(OUT_2_2, HIGH);

  Serial.begin(9600);
}

void loop() {
  String str = "";

  // checking for bytes in the buffer
  if (Serial.available() > 0) {
    str = Serial.readStringUntil("\n");
  }
  // Serial.println(str); // if this line is uncommented serial input "2_ON\n" and "2_OFF\n" is recognized and outled 2 is successfully switched

  // identity
  if (str == "IDN\n") {
    Serial.println("Serial Power Outlet");
  }

  // controlling power outlet 1
  else if (str == "1_ON\n") {
    digitalWrite(OUT_1_1, LOW);
    digitalWrite(OUT_1_2, LOW);
  }
  else if (str == "1_OFF\n") {
    digitalWrite(OUT_1_1, HIGH);
    digitalWrite(OUT_1_2, HIGH);
  }

  // controlling power outlet 2
  else if (str == "2_ON\n") {
    digitalWrite(OUT_2_1, LOW);
    digitalWrite(OUT_2_2, LOW);
  }
  else if (str == "2_OFF\n") {
    digitalWrite(OUT_2_1, HIGH);
    digitalWrite(OUT_2_2, HIGH);
  }
  delay(1000);
}

If I serial input 2_ON\n or 2_OFF\n the according else if blocks are just ignored (all other inputs work correctly).
But after I've uncommented // Serial.println(str); these blocks are executed the way they are supposed to and all works just fine.
Where is my mistake, what am I getting wrong here?
These blocks also get executed if I Serial.println any random output.
Why do I have to Serial.println something first so my script works according to plan? What am I missing?
EDIT: added all of the code.

Post the whole code. I bet you have a memory overrun somewhere.

Tank you for reading, I've just added all of the code. Even though that was just the setup() and 4 defines.

I've just found out that the character '2' literally is dropped, when I print out 'str' at the end of loop(). This only happens to '2', not any other character.
So I will go with 'A_ON/OFF' and 'B_ON/OFF' as control strings and continue with my project. Still, this is no clean solution and I'd still like to know why this behavior is observed.

Even though you read until \n, that just controls the ending of your buffered string.  It does not control it's start.  There may be some garbage before the command that you have not cut out.  In other words, I suggest you check if the string endsWith as opposed to == the command string.
As for what noise could be causing garbage or why activity on the tx side of the serial cleaned it up, i do not know.  Heck something might just be weird enough in the wiring that '2' is just the set of bits needed to aggravate it.

That's interesting, thanks for the input! I'll try tomorrow and check if endsWith() works.

Reality has no duty to conform to our theories, but often we do have jobs that require us to make our theories conform to reality.  I'd like to think there's more going on here than a ghost in the machine that hates 2 but likes B.


text:
How to easily invoke Simple REST Service trigerred using Arduino UNO + ESP8266 WIFI Shield programmed with AT command?
My Question is How to easily invoke Simple REST Service trigerred using Arduino UNO + ESP8266 WIFI Shield programmed with AT command? I am new to this Subject and gone through many tutorial over internet but so far I could not making this working as per my requirement
My Requirement: Invoke a simple Get request originated from Arduino Uno and via ESP8266 WIFI Shield to submit to server and process the response.
What all I have done so far:

Used below Blynk example to Submit Up time to the Server and View in MobileThis is Working which means hardware setup at my side should be ok, but I dont want to Submit request to Blynk Server and I want to Submit request to my REST server and first of all I want to do a simple GET request may be to any already working API for ex: http://jsonplaceholder.typicode.com/posts/1
#define BLYNK_PRINT Serial
 #include <ESP8266_Lib.h>
 #include <BlynkSimpleShieldEsp8266.h>

 // You should get Auth Token in the Blynk App.
 // Go to the Project Settings (nut icon).
 char auth[] = "xyz";

 // Your WiFi credentials.
 // Set password to "" for open networks.
 char ssid[] = "xyz";
 char pass[] = "xyz";

 // Hardware Serial on Mega, Leonardo, Micro...
 //#define EspSerial Serial1

 // or Software Serial on Uno, Nano...
 #include <SoftwareSerial.h>
 SoftwareSerial EspSerial(2, 3); // RX, TX

 // Your ESP8266 baud rate:
 #define ESP8266_BAUD 115200

 ESP8266 wifi(&EspSerial);

 BlynkTimer timer;

 void myTimerEvent()
 {
   // You can send any value at any time.
   // Please don't send more that 10 values per second.
   Blynk.virtualWrite(V5, millis() / 1000);
 }

 void setup()
 {
   // Debug console
   Serial.begin(115200);

   // Set ESP8266 baud rate
   EspSerial.begin(ESP8266_BAUD);
   delay(10);

   Blynk.begin(auth, wifi, ssid, pass);
   // You can also specify server:
   //Blynk.begin(auth, wifi, ssid, pass, "blynk-cloud.com", 80);
   //Blynk.begin(auth, wifi, ssid, pass, IPAddress(192,168,1,100), 8080);

   // Setup a function to be called every second
   timer.setInterval(1000L, myTimerEvent);
 }

 void loop()
 {
   Blynk.run();
   timer.run(); // Initiates BlynkTimer
 }

Output :
  ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on Arduino Uno

[517] Connecting to xyz
[13550] AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaea 1
[23591] Failed to connect WiFi
[31752] Ready (ping: 11ms).
[70474] Ready (ping: 12ms).
[86528] Ready (ping: 13ms).

Though I get Failed to connect to wifi but probably it retries and works there after as I can see timer in Mobile APP which is progressing.

Invoke HTTP request using AT Command, but I am getting output as ">" which I am not able to get as why the output is like this:
#include <SoftwareSerial.h>

SoftwareSerial ESP8266(2, 3);

String Network = "xyz";
String Password = "xyz";

void setup()
{

  Serial.begin(9600);

  ESP8266.begin(115200);
  ESP8266.println("AT+CIOBAUD=9600");
  readESP8266(4000);

  ESP8266.begin(9600);
  InitESP8266();
  ConnectToWebsite();
}

void loop()
{
   while(ESP8266.available())
   {
     Serial.println(ESP8266.readString());
   }

}

/* Function to initialise ESP8266 */
void InitESP8266()
{

  ESP8266.println("AT");
  readESP8266(2000);

  ESP8266.println("AT+CWMODE=3"); //Wifi mode
  readESP8266(5000);

  ESP8266.println("AT+CWJAP=\""+ Network + "\",\"" + Password +"\""); //connect wifi
  readESP8266(10000);

  ESP8266.println("AT+CIFSR"); // IP adress
  readESP8266(1000);

  ESP8266.println("AT+CIPMUX=1");  // multiple connections
  readESP8266(1000);

}

/* Function to connect to the server */
void ConnectToWebsite()
{

  ESP8266.println("AT+CIPSTART=1,\"TCP\",\"jsonplaceholder.typicode.com\",80"); //connect to website
  readESP8266(10000);

  ESP8266.println("AT+CIPSEND=1,114");
  readESP8266(2000);

  String httpreq = "GET /posts/1 HTTP/1.1";
  // Make a HTTP request:
  ESP8266.println(httpreq);
  readESP8266(10000);

  readESP8266(5000);

  //Serial.println("\r\n");
}

//read and display message
void readESP8266(const int timeout)
{
  String reponse = "";
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(ESP8266.available())
    {
      char c = ESP8266.read();
      reponse+=c;
    }
  }
  Serial.print(reponse);
}````

Output:
OK

OK
WIFI DISCONNECT
WIFI CONNECTED
WIFI GOT IP

OK
+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"abcd"
+CIFSR:STAIP,"192.168.0.169"
+CIFSR:STAMAC,"abcd"

OK

OK
1,CONNECT

OK

OK
> 1,CLOSED

If I use WIFI ESP then I am getting following error

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

char ssid[] = "xyz";            // your network SSID (name)
char pass[] = "xyz";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "arduino.cc";

// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    //while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");

  printWifiStatus();

  Serial.println();
  Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    client.println("GET /asciilogo.txt HTTP/1.1");
    client.println("Host: arduino.cc");
    client.println("Connection: close");
    client.println();
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    client.stop();

    // do nothing forevermore
    while (true);
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}````

Output:
````[WiFiEsp] I >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
WiFi shield not present
Attempting to connect to WPA SSID: xyz
[WiFiEsp] >>> TIMEOUT >>>

Please let me know in case you figure out the issue.

you don't set the AT baud rate in the WiFiEsp sketch. use AT+UART=9600,8,1,0,0 to set 9600 baud as default

@jsotola tried formatting with ctrl+k but it's not taking effect, looks like a bug in stack overflow :D

@Juraj meaning set these in WiFi esp sketch code??

It’s not a bug in Stack Overflow.

doesn't matter how you execute it. it will be remembered as default

@Rajesh To make a code block inside of an enumeration, you need to add another 4 spaces at the beginning of each line, so 4 spaces for the enumeration item and another 4 for the code block. That is not a bug, but just the way, that such markdown languages work, that SE uses. It is easier to copy the text into a decent text editor, command it to indent the corresponding lines by 4 spaces and then copy it back to the question editor. The toolbar of the editor is only meant for easier formatting

Done formatting as requested

Judge from the sketches you've tried, you are jumping from one example code to another example code without understanding how actually the code works. On your sketch 2, if a request-URI is not a full URL, you need to send extra http header "Host: jsonplaceholder.typicode.com" to indicate which server you want to get data from, and you also need to send an extra CR-LF (as in your sketch 3 and see HTTP/1.1 Request). On sketch 3, as mentioned by @Juraj, you need to setup the baud rate with AT command.

Thanks @hcheung, I am able to send request after formatting as suggested but unable to read response. Any idea what could be the issue now: https://arduino.stackexchange.com/questions/77341/unable-to-read-arduinoesp8266-full-get-response


text:
Unable to use RF M4 Receiver with servo motor
I am trying to control a servo motor with the following code:
#include <Servo.h>

Servo servo;

int const inputPin = 3;

void setup() {
  Serial.begin(9600);
  servo.attach(9);
  pinMode(inputPin, INPUT);
  servo.write(0);
}

void loop() {
  if (digitalRead(inputPin)) {
    Serial.println("HIGH");
    servo.write(40);
  } else {
    Serial.println("LOW");
    servo.write(0);
  }
}

It takes input from pin 3 and controls the servo with pin 9. When pin 3 is connected to a pushbutton, as shown in the following image, it works exactly as expected; for as long as the button is held down, the servo stays at 40° and when the button is released the servo returns to 0°.
It's a little difficult to see in the images, but the resistor on row 24 is connected to ground, not power.

However, if I replace the button with an Adafruit RF M4 Receiver, as shown in the following image, the servo behaves differently. When I hold the button on the remote down, the servo attempts to move to 40°, but returns to 0° before trying again. From the serial output, I can see that the pin is in fact oscillating between HIGH and LOW.

If I remove the commands to the servo and just use the buttons to control the serial output, the code behaves correctly. With both the pushbutton and the RF M4 Receiver, the output says HIGH when the button is held down and LOW when it is released. So the issue only occurs when I use both the receiver and a servo motor, but not one or the other.
int const inputPin = 3;

void setup() {
  Serial.begin(9600);
  pinMode(inputPin, INPUT);
}

void loop() {
  if (digitalRead(inputPin)) {
    Serial.println("HIGH");
  } else {
    Serial.println("LOW");
  }
}

I am using an Arduino Uno R3, this receiver, and this remote.
Edit: The schematic, as requested. I'm new to Arduino, so I apologize if the schematic is a little sloppy.

simulate this circuit – Schematic created using CircuitLab

I will guess you probably have RF feedback getting into the control loop. No idea of how it gets there. Please post an annotated schematic.

@Gil, I'm working on making the schematic. Do you think I need the pull down resistor for the RF receiver? Can that be causing the issue?

No sure, I am not familiar with the parts or circuit you are using.  If that is connected to an Arduino port pin that can switch it low or high.

remove the servo and the servo code... light an LED instead

@jsotola It works as expected with an LED. I'm only having an issue when I'm using the receiver to control a servo.

@Gil, I've added a schematic. It's a little messy, but it's about the best I can do at this point. Let me know if this helps.

"From the serial output, I can see that the pin is in fact oscillating between HIGH and LOW." - Sounds like the receiver is not outputting a HIGH signal the entire time the button is being pressed, or maybe, the current requirement of both loads exceeds the Uno's available current.

@VE7JRO, The receiver normally outputs a HIGH signal the entire time the button is pressed except for when I use it with a servo, so the load requirement explanation sounds plausible. As a beginner, what would be some steps I can take to troubleshoot this? Would powering the servo with a separate battery fix the issue? I'm new to this, so I'm still not quite sure how to manipulate voltages and currents.

Powering the servo with a separate battery MAY solve the problem. Remember to connect the external power supply's ground with your Arduino's ground connection.

@VE7JRO I just tried it out and it worked. I connected the servo to a 9V battery and it operated correctly. I thought it might also work if I power the Arduino and the servo with the same 9V battery, since the voltage is higher that the Arduino's 5V, but the issue persisted when I did that, so I guess for now I just have to run them with different power sources. Is it standard practice to power servos with a separate power source? I know that that's the standard with DC motors, but the starter book I'm using didn't say anything about servos.

"Is it standard practice to power servos with a separate power source?" - Yes. If you look at the servo's power consumption under certain conditions, you'll see it can reach 730mA. Here is a chart for the SG90 servo: https://arduino.stackexchange.com/a/49755/37523 A 9 volt battery may not last very long, so you may want to switch to larger batteries or perhaps a wal-wart (AC to DC converter).

@VE7JRO Thank you for your help. As with the user in the question you linked to, I've been following official Arduino tutorials from the starter kit, and in all the projects that use a servo they connect it directly to the Arduino's power. They only discuss separate power sources for DC motors. For some reason, the tutorials are just not making this clear at all for beginners.


text:
how to convert a line of code for arduino to receive a value
im sending the value 1500 from another MCU with
 fdserial_txChar(transmit, send >> 7);    // send Higher 7 bits
 fdserial_txChar(transmit, send & 0x7F);  // send Lower 7 bits

and was receiving it with code that looked like this
servo1  = fdserial_rxChar(receive) << 7;    // get Higher 7 bits
servo1 += fdserial_rxChar(receive) & 0x7F;  // get and add Lower 7 bits

how do i rewrite the receiving code so arduino will compile it?
Thank you.
here is the code im trying to get working
void setup() {
// physical pin 2=TX 3=RX
  Serial.begin(9600);
  pinMode(3, OUTPUT);      // set LED pin as output
  digitalWrite(3, LOW);    // switch off LED pin
}

void loop() {

  if (Serial.available()) {
  //  char data_rcvd = Serial.read();   // read one byte from serial buffer and save to data_rcvd

    int data_rcvd = Serial.read() << 7;     //get Higher 7 bits
    int data_rcvd += Serial.read() & 0x7F;  //get and add Lower 7 bits

    if (data_rcvd == 1500) digitalWrite(3, HIGH); // switch LED On
    if (data_rcvd == '0') digitalWrite(3, LOW);  // switch LED Off
  }

//  if (digitalRead(8) == HIGH) Serial.write('0');    // send the char '0' to serial if button is not pressed.
//  else Serial.write('1');                           // send the char '1' to serial if button is pressed.

}

Please show us a complete code, not only snippets. Where are those functions defined?

i removed the second int for data_rcvd and the code compiled but did not turn on the LED

not sure if it matters but im using an attiny412

Your code doesn't contain any calls to fdserial_rxChar() or similar. So what is your actual problem? You eon't get good answers if you don't ask an understandable and complete question

im sending the value 1500 ... what does that mean? ... are you sending a integer? ... are you sending text? ... something other?

You have a few obvious problems here.

if (Serial.available()) {
 int data_rcvd = Serial.read() << 7;     //get Higher 7 bits
 int data_rcvd += Serial.read() & 0x7F;  //get and add Lower 7 bits

You are testing that one byte is available on the serial port and then reading two bytes. Too soon. Test for two bytes if you are planning to read two.

if (data_rcvd == '0') digitalWrite(3, LOW);  // switch LED Off

Why the quotes? Why not: if (data_rcvd == 0) ?

How are you intending to synchronize the sending and receiving?
Your sender is sending HLHLHLHL - what if the receiver starts while the low byte is being sent? You will receive LHLHLH which means your received data will be meaningless.
You are better off sending "readable" data, like "1500" rather than 1500, terminating with a newline, and structuring your receiving code to read until it hits a newline. That will synchronize the receiver (after the first reading, anyway).

For more tips about reading serial data see: How does serial communications work on the Arduino?
Also my post about serial data on my forum has code for buffering incoming serial data and waiting for a newline.

thanks for your Help Nick, you steered me towards finding my answer. is there a way to get arduino to pause/wait until it receives a specific value such as 129/0x81 ? kinda like a way to sync things up?

@benjaminnikkel The simplest solution is what I suggested in my answer. Send a "line" of data including a newline at the end. The newline will separate each reading from the next. Instead of transmitting the low-order and high-order bytes, just do a sprintf into a buffer, turning the number into ASCII characters, and add a newline to the end. The Arduino can read a line of data. For tips see my post about reading serial data. However the link on my own forum has better information about reading lines of data.

the answer to my question of how to write
servo1  = fdserial_rxChar(receive) << 7;    // get Higher 7 bits
servo1 += fdserial_rxChar(receive) & 0x7F;  // get and add Lower 7 bits

so Arduino would compile it is....
combined = (val1 << 7) | (val2);


text:
Exiting from one loop and get ready for another
I am working on a keypad password lock system based on arduino UNO. I have used the password library from Arduino's website.
What I am trying to accomplish is to set two passwords, namely pass1 and pass 2.
The condition is that this circuit is attached to a gate, if user 1 lets say knows pass1, after entering the pass the gate will unlock for 10 seconds and the pass1 becomes invalid i.e. can not be used in future. However if user 2 comes and knows pass2, after entering the pass2, the gate will open for 10 seconds and then pass2 becomes invalid; so each password can be used only once. I am attaching the code I already have below.
The problem with this code is that when pass1 is executed, the system does not take pass2 until unless the system is reset.
Kindly tell me a solution to fix this.
#include <Password.h>
#include <LiquidCrystal.h>
#include <Password.h>
#include <Keypad.h>

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
Password password1 = Password("1234");
Password password2 = Password("4567");
int ledpin = A5;
int a = 0;
const byte ROWS = 4; // Four rows
const byte COLS = 4; // columns

char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
};

byte rowPins[ROWS] = {A0, A1, A2, A3};
byte colPins[COLS] = { 8,  9, 10, 11};

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

void setup() {
    lcd.begin(16, 2);
    keypad.addEventListener(keypadEvent); //add an event listener for this keypad
}

void loop() {
    keypad.getKey();
}

void keypadEvent(KeypadEvent eKey) {
    switch (keypad.getState()) {
        case PRESSED:
            lcd.println(eKey);
            switch (eKey) {
                case '*':
                    checkPassword();
                    break;
                case '#':
                    password1.reset();
                    password2.reset();
                    break;
                default:
                    password1.append(eKey);
                    password2.append(eKey);
            }
            return;
    }
}

void checkPassword() {
    if (password1.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code1 OK");
        delay(2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password1.append('1');
        lcd.clear();
        return;
    } else if (password2.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code2 OK");
        delay (2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password2.append('2');
        lcd.clear();
        return;
    } else {
        lcd.setCursor(0, 1);
        lcd.println("Wrong");
        delay(2000);
        lcd.clear();
        lcd.print("Wait for 5 Sec");
        delay(5000);
        lcd.clear();
        return;
    }
    return;
}

Regards
Fawad

Password 2 contains password 1 while it's being typed. You need to empty out Password 2 when password 1 is accepted and vice versa.

As a matter of courtesy for those who read your question, you should at least try to properly indent your code, as this makes it easier to read. I've done it for you now, but please do it yourself in the future.

You are never really invalidating the passwords. The statement
password1.append('1');

adds '1' to the guess, it does not change the password itself.
If you really want to invalidate the password, you should change it to
something that cannot be typed on the keypad. For example
password1.set("X");  // untypable password

Whether or not you do invalidate the previously used passwords, you
should reset the guesses once a password has been checked. This can be
done in checkPassword(), or in keypadEvent() as follows:
switch (eKey) {
    case '*':
        checkPassword();
        password1.reset();
        password2.reset();
        break;
    ...
}

BTW, all your return statements are useless, and the first
switch/case in keypadEvent can be replaced by
    if (keypad.getState() == PRESSED)

which would be easier to read.

Thanks Edgar, I am sorry for the indent part as you can tell I am very new to the community.
I will try these changes, and will get back to you!!
Could you kindly elaborate the change in the indent code at the very last.
Regards Fawad

@Fawad: Statements that are at the same logical level should be lined up. There are various common indent styles. They are all OK as long as you pick one and use it consistently.

I tried your suggestion to reset password in the case loop but it only resets it thus eliminating the main requirenment of one use per password...

@Fawad: This requirement is not fulfilled in your current code: typing '#' allows to reuse passwords. The reset() I suggested has nothing to do with this requirement either: it's meant to allow the use of the other password, and to give a second chance if you mistype the password. If you want to enforce single-use, issue passwordN.set("X"); once password N has been accepted, as I already mentioned in the answer.


text:
Quick Programming Check/Review
I've been racking my head trying to start programming in a library organized method. My code works, but the translation and split to a .h and .cpp file is riddled with errors.
It's gotta be stupidly simple all I'm asking for is a review:
Header File
# ifndef _INITIALIZE_H
#define _INITIALIZE_H

#if (ARDUINO >= 100)
# include <Arduino.h>
#else
# include <WProgram.h>
#endif

//-Extra Includes-
#include <config.h> //Provides baud...
#include <SSC32.h>

#define STANDARD 0
#define DEBUG    1
#define VIRTUAL  2

class Initialize {
    private:
        int _mode;
    public:
        Initialize();
        void begin();

};

#endif

associated .cpp file:
//Comments
#include <Initialize.h>
SSC32 SSC;

Initialize::Initialize()
{
    _mode = STANDARD;
}

void Initialize::begin()
{
    SSC.begin(baud);
    if(Serial.available() > 0){
        if(sscReturn == 1){
            Serial.println("ver");
        }
    }
}

The error from the compiler:
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp: In member function 'void Initialize::begin()':
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:12: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected primary-expression before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected ';' before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected ')' before ';' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:17: error: expected primary-expression before '==' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:21: error: expected ';' before ')' token
Failed compiling libraries

What is sscReturn?

Where is sscReturn declared? This seems to be the (main) cause of the compiler errors.

Sorry, figured it out.
In the "config.h" file I was pulling, I had a
 #define = 18;
instead of a #define 18
I might be wrong, but the compiler stopped complaining

What are you defining as 18?

@user you cannot just type #define 18, it should be something like #define xyz 18. This means that from now on in your code xyz will be replaced by 18 (https://www.arduino.cc/en/Reference/Define)

I might be wrong - You are wrong. The line #define 18 doesn't compile: error: macro names must be identifiers. This is not a helpful answer. I'm going to vote to close the question and the answer.