text:
I have a problem with this code where the buzzer won't work
const int buzzerPin = 7;
const int flamePin = 10;
int Flame = HIGH;
int redled = 8;
void setup()
{
  pinMode(buzzerPin, OUTPUT);
  pinMode(redled, OUTPUT);

  pinMode(flamePin, INPUT);
  Serial.begin(12000);
}

void loop()
{
  Flame = digitalRead(flamePin);
  if (Flame== HIGH)
  {
    digitalWrite(redled, HIGH);
  int i=0;
  do {
    digitalWrite(buzzerPin, HIGH);
    tone(buzzerPin,450);
    delay(200);
    noTone(buzzerPin);
    delay(200);

  }while (i<2);
  }
  else
  {
    digitalWrite(buzzerPin, LOW);
    digitalWrite(redled, LOW);
  }
}

test the buzzer with the simplest code possible

We don't know anything about your buzzer or circuit, so there's little to offer in the way of help. Please make sure when posting code that it's formatted as code so people can actually read it. It's also helpful to include what does work, e.g., there are other factors in your code that could make it seem like the buzzer isn't working.

450 is too low frequency for a piezo. use 3000

Here are the modifications I have done

I changed the Piezo Buzzer frequency to 3000 Hz
The green Button simulates the Flame signal
Change the RED LED from pin 8 to Pin 13 so that I don't have to use an external LED

Here is the simulation output

Observe the onboard LED going HIGH and the buzzer going off. You can find the project link here where you can test with different Piezo buzzer frequency.
Code
const int buzzerPin = 7;
const int flamePin = 10;
int Flame = HIGH;
int redled = 13;
void setup()
{
  pinMode(buzzerPin, OUTPUT);
  pinMode(redled, OUTPUT);

  pinMode(flamePin, INPUT);
  Serial.begin(12000);
}

void loop()
{
  Flame = digitalRead(flamePin);
  if (Flame== HIGH)
  {
    digitalWrite(redled, HIGH);
  int i=0;
  do {
    digitalWrite(buzzerPin, HIGH);
    tone(buzzerPin,3000);
    delay(200);
    noTone(buzzerPin);
    delay(200);

  }while (i<2);
  }
  else
  {
    digitalWrite(buzzerPin, LOW);
    digitalWrite(redled, LOW);
  }
}

Disclaimer: I am not the Wokwi creator but I support it since it is open source and free to use

@Juraj fixed it

@Juraj I Doubt it. if the flame signal is high, he is triggering the alarm


text:
how to use switch case with two push buttons, I don't know how to combine buttonState1 and buttonState2
import muvium.compatibility.arduino.*;

public class Class0 extends Arduino{

/*
Author: First Name MI. Last Name
Date: June 25, 2021
Title: Arduino Experiment 2
Description: Writing to the Output Pins using the FOR statement

Create a program that will display four different LED sequences having
different transition states repeated at different number of times and
that the whole program will repeat itself continuously

Apply the concept of using funcions for each of the four LED sequences,
 each of which are to be called upon from the main program.

This time simplify the LED sequence functions using FOR control statements
to achieve the required iterations

Pin modes of each LED pins are to be iterated together using a FOR statement

The circuit:
 * LEDs connected from digital pin 4-11, all with respect to ground.
*/
// ---------------------------------------------------------
// Declaration of Global Variables:
  int led1 = 4; // LED1 connected to digital pin 4
  int led2 = 4; // LED2 connected to digital pin 4
  int led3 = 4; // LED3 connected to digital pin 4
  int led4 = 4; // LED4 connected to digital pin 4
  int switchPin1 = 2; // PushButton connected to digital pin 2
  int switchPin2 = 3; // PushButton connected to digital pin 3
  int buttonState1 = 0; // variable for reading pushbutton status
  int buttonState2 = 0; // variable for reading pushbutton status
// ---------------------------------------------------------
  public void setup() {
    // the setup() method runs once, when the sketch starts
    // initialize the digital pins as outputs;

    for (led1 = 4; led1 < 12; led1++) {
      pinMode(led1, OUTPUT); // Configure pin 4 to 11 as outputs
    }
    pinMode(switchPin1, INPUT);// Configure pin 2 as input
    pinMode(switchPin2, INPUT);// Configure pin 3 as input
  }
// ---------------------------------------------------------
  public void loop() {
    // the loop() method runs over and over again,
    // as long as the Arduino has power

    // read the state of pushbutton value
    buttonState1 = digitalRead(switchPin1);
    buttonState2 = digitalRead(switchPin2);

    switch (buttonState1) {
      case (0):
        for (led1 = 7, led2 = 8; (led1 > 3) && (led2 < 12); led1--, led2++) {
        digitalWrite(led1, HIGH); // set the LED on
        digitalWrite(led2, HIGH); // set the LED on
        delay(500); // wait for 500 milliseconds
        digitalWrite(led1, LOW); // set the LED off
        digitalWrite(led2, LOW); // set the LED off
        }
        break;

      case 1:
        for (led1 = 11, led2 = 9, led3 = 7, led4 = 5; (led1 > 9) && (led2 > 7) && (led3 > 5) && (led4 > 3); led1--, led2--, led3--, led4--) {
        digitalWrite(led1, HIGH); // set the LED on
        digitalWrite(led2, HIGH); // set the LED on
        digitalWrite(led3, HIGH); // set the LED on
        digitalWrite(led4, HIGH); // set the LED on
        delay(500); // wait for 500 milliseconds
        digitalWrite(led1, LOW); // set the LED off
        digitalWrite(led2, LOW); // set the LED off
        digitalWrite(led3, LOW); // set the LED off
        digitalWrite(led4, LOW); // set the LED off
        }
        break;

      case 2:
        for (led1 = 11, led2 = 10, led3 = 9, led4 = 8; (led1 > 6) && (led2 > 5) && (led3 > 4) && (led4 > 3); led1-=4, led2-=4, led3-=4, led4-=4) {
          digitalWrite(led1, HIGH); // set the LED on
          digitalWrite(led2, HIGH); // set the LED on
          digitalWrite(led3, HIGH); // set the LED on
          digitalWrite(led4, HIGH); // set the LED on
          delay(500); // wait for 500 milliseconds
          digitalWrite(led1, LOW); // set the LED off
          digitalWrite(led2, LOW); // set the LED off
          digitalWrite(led3, LOW); // set the LED off
          digitalWrite(led4, LOW); // set the LED off
          }
          break;

      default:
        for (led1 = 11, led2 = 4; (led1 > 7) && (led2 < 8); led1--, led2++) {
          digitalWrite(led1, HIGH); // set the LED on
          digitalWrite(led2, HIGH); // set the LED on
          delay(500); // wait for 500 milliseconds
          digitalWrite(led1, LOW); // set the LED off
          digitalWrite(led2, LOW); // set the LED off
          }
    }
  }
}

Java on a microcontroller? :o. Blasphemy :p

what do you mean by switch case with two pushbuttons? ... what are you trying to achieve?

I changed your tags: on this site "switch" means a physical component that you press with your finger, not a switch/case programming construct.

If you're asking how can you switch based on the combined state of two variables you have several options. In this particular case you could create a value with a bit representing each state, say bits 0&1 would be the state of buttons 1&2, then just switch on that aggregated value. Whether or not this makes sense from The application's point of view depends on what you're trying to do, which isn't super-clear.

in setup(), why are you repeating the same action 4 times?

@jsotola oh yeah thank you for mentioning that, I already removed the unnecessary

@AnonymousQuestion no, it is still there ... your program listing is unchanged

I don't know what that code is, but it's not Arduino code. It looks like it's wrapped in some other class.  But in real Arduino code...
To "combine" your two button states it helps to think of them as two individual bits within a byte. A byte is made up of 8 bits, and any of them can be on or off. If you associate your two buttons with two of those bits you can represent them as a single number in a byte.
For example if you use:
uint8_t buttonStates = (digitalRead(switchPin2) << 1) | digitalRead(switchPin1);

you create a single variable containing both states.  In simple terms that means "Read switchPin2, shift the result one bit to the left, then read switchPin1 and superimpose the two results together".
So the result is a byte where bit 1 is switchPin2 and bit 0 is switchPin1.
It gives you, then, a truth table of:
SP1 | SP2 | Variable
----+-----+----------
 0  |  0  | 0b00000000
 1  |  0  | 0b00000001
 0  |  1  | 0b00000010
 1  |  1  | 0b00000011

Which of course is the numbers 0-3 in decimal.
So then you can use a switch:
switch (buttonStates) {
    case 0: // switchPin1 == 0, switchPin2 == 0
        // do something
        break;
    case 1: // switchPin1 == 1, switchPin2 == 0
        // do something
        break;
    case 2: // switchPin1 == 0, switchPin2 == 1
        // do something
        break;
    case 3: // switchPin1 == 1, switchPin2 == 1
        // do something
        break;
}

uint8_t doesn't work for my arduino mega in virtual breadboard :((

Then don't use virtual breadboard, whatever that is. This code will work on a real Arduino. If you aren't using a real Ardunio then that's your lookout.

@AnonymousQuestion Then use a different type.

oh it works when I removed the uint8_t thank you

source: Stack Exchange

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

sort: votes


text:
RP2040 example sketch for dual core queuing
I would like to use queuing because i think its best for my application. I have very limited experience in dual core programming all i want is to hopefully pass 32 bit numbers to the second core properly. queuing seems to be good because it makes sure that the second core who is receiving the data wont miss anything in the sequence if data comes in very fast and core 2 is not ready to process it.
But Im having trouble finding examples. I did find one but its for a runner queue, which i think is a bit different to what i want
Can anyone show me an example sketch? what i would really like to see is core 1 adding to the queue and core 2 retrieving and removing data from the queue

If all you  want to pass is 32-bit numbers the FIFO is better suited to your needs.

But that said, Queue or FIFO it's the same (you just have to create a queue before you use it). Push stuff on one end, and pop it off the other (both with optional blocking).

@Majenko I did read about FIFO but decided not to because of the note in the sdk, it is suggested that you do not use the FIFO for your own purposes unless none of the above concerns apply; the majority of cases for transferring data between cores can be eqaully well handled by using a queue  Do you have some simple examples of the queue i can look at?

Yeah, I saw that after I posted the comment ;)

@Majenko Do you think you can show me how to use queue sir? :)

After digging around i was able to use the queue_t from the sdk. and here it is
queue_t queue;

typedef struct queueItem {
  uint32_t value;
} item;

const int QUEUE_LENGTH = 128;

void setup() { //CORE 1 setup

  Serial.begin(9600);
  while (!Serial);
  queue_init(&queue, sizeof(item), QUEUE_LENGTH); //initialize the queue

}

void loop() { //CORE 1 TIGHTLOOP

  queueItem temp;
  temp.value = random (1000);
  if (queue_try_add(&queue, &temp)) { //adding items to the queue
    Serial.print("ADDING:\t");
    Serial.println(temp.value);
  }

  else
    Serial.println("FIFO was full\n");
  delay(500);
}

void setup1() { // CORE2
}

void loop1() {  //CORE 2 TIGHTLOOP

  queueItem temp;
  while (queue_try_remove(&queue, &temp)) { //retrieving item from the queue and deleting it from the queue
    Serial.print("ITEM RETRIEVED:\t");
    Serial.println(temp.value);
  }

  delay(500);

}

This requires a thread-safe queue, where one thread writes to the queue, and another thread reads from the queue.
But I find that with a little care, you can just use a circular buffer where the consumer will increase the head, and the producer will increase the tail.
Something like this:
#define MAXSZ 80
static int buff[MAXSZ];
static int head=0;
static int tail=0;

bool full(void)  { return (tail+1)%MAXSZ == head; }
bool empty(void) { return head==tail; }
int  usage(void) { int num = tail-head; return num<0 ? num+MAXSZ : num; }

int produce(int val)
{
   if ( full() ) return -1;
   buff[tail] = val;
   tail = (tail+1)%MAXSZ;
   return 0; // signal success.
}

int consume(void)
{
   if ( empty() ) return -1;
   int val = buff[head];
   head = (head+1)%MAXSZ;
}

This will work as long as your compiler doesn't do crazy re-ordering of the operations, and as long as you only touch the head with the consumer, and only touch the tail with the producer. Also, the assignments of head/tail need to be atomic, not split up as: tail++ ; tail = tail%MAXSZ;
Come to think of it: if a small capacity suffices, like the 80 from the example code, I would use int8_t for head/tail, just in case writing an int to memory gets context-switched between writing the LSB and MSB parts. (I don't know RP2040 well enough to know if writing an int is atomic.)

So the buffer will just grow larger and larger as more data is transfered? Wont that eventually eat all the memory the more data is passed?

No, the buffer in the example has 80 slots reserved, and will never use more memory. The used slots vary between 0 and 79, so you can't have the consumption lag too much, as the buffer will be full. Both the head and tail will wrap-around as they reach 80th index. Once you consume a value, its slot is now available for queuing in a new value.

How do i know how many are in queue? because from what i undestand looking at it, data in the buffer never gets deleted, just overwritten when the array wraps around.

You can check for the number of valid elements by iterating through the queue from head to tail, counting the needed iterations until you reach the tail. An element is only valid, when its between head and tail (inclusive head, exclusive tail)

@DrakeJest Just look at the distance between head/tail for the number of used slots. See the usage() function that I added.

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


text:
Modifying the neopixel rainbow function to work with 4pins
So my setup is i have strips that is separated into 4 pins and would like to modify this rainbow function from the neopixel so that it will work on 4 separate strip that are on 4 separate pins. I would like to look like strip number 2 is a continuation of strip number 1 and number 3 is to 2 and number 4 is to 3. A very cool feature about this function is the start and end is a continuation so this mean i basically have a ring setup.
void rainbow(int wait) {
  // Hue of first pixel runs 5 complete loops through the color wheel.
  // Color wheel has a range of 65536 but it's OK if we roll over, so
  // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
  // means we'll make 5*65536/256 = 1280 passes through this outer loop:
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
      // Offset pixel hue by an amount to make one full revolution of the
      // color wheel (range of 65536) along the length of the strip
      // (strip.numPixels() steps):
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
      // optionally add saturation and value (brightness) (each 0 to 255).
      // Here we're using just the single-argument hue variant. The result
      // is passed through strip.gamma32() to provide 'truer' colors
      // before assigning to each pixel:
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents
    delay(wait);  // Pause for a moment
  }
}

I do not understand how hue and gamma works so it a bit more tricky for me to modify this function.
Here is my attempt but my attempt is so crude and hoggs so much memory
void rainbow(int wait) {

  unsigned int totalPixelCount = strip1.numPixels() + strip2.numPixels() + strip3.numPixels() + strip4.numPixels();
  uint32_t pixelHueList [totalPixelCount];
  for (long firstPixelHue = 0; firstPixelHue < 5 * 65536; firstPixelHue += 256) {
    for (int i = 0; i < totalPixelCount; i++) {
      int pixelHue = firstPixelHue + (i * 65536L / totalPixelCount);
      pixelHueList[i] = strip1.gamma32(strip1.ColorHSV(pixelHue));
    }

    unsigned int j = 0;
    for (j = j; j < strip1.numPixels(); j++)
      strip1.setPixelColor(j,pixelHueList[j]);
    for (j = j; j < strip1.numPixels() + strip2.numPixels(); j++)
      strip2.setPixelColor(j,pixelHueList[j]);
    for (j = j; j < strip1.numPixels() + strip2.numPixels() + strip3.numPixels(); j++)
      strip3.setPixelColor(j,pixelHueList[j]);
    for (j = j; j < strip1.numPixels() + strip2.numPixels() + strip3.numPixels() + strip3.numPixels(); j++)
      strip3.setPixelColor(j,pixelHueList[j]);

    strip1.show();
    strip2.show();
    strip3.show();
    strip4.show();
    delay(wait);
  }
}

Is there a way to make it more efficient?

"unsinged" compiles?

Doesn't setPixelColor() also need the index of the LED as parameter?

Ok, your code cannot compile due to some syntax errors. Also you don't need to build up an array first. You are iterating through the LEDs either way, so you can just calculare the needed values right there without saving them in an array inbetweeen. When I'm at my PC again I can write you an answer (if nobody is faster)

@chrisl Apologies i have fixed the syntaxes :) . I am still commuting going home so i just actually wrote the code here.

You still have a sytax error with the line pixelHueList[i] = (i, strip1.gamma32(. I will look again at your question tomorrow. In my country its now time to go to bed :)

@chrisl Sure ! i will wait for it :)

Why not make 1 (extended) string out of all 4 NeoPixels strings and control them via 1 single pin with much simpler code?

Currently you are first filling an array with values from a calcuation by going through all LEDs; and then you are again going through all LEDs to actually set them. You can do that in one step. Also your current code will most likely not work, since you just count from zero to the total number of LEDs, but the individual strip doesn't know of that much LEDs. That will get you in problems with everything after the first for loop where you set the LEDs.
For doing it in one step and simultaneously solve the problem:
void rainbow(int wait) {
  for (long firstPixelHue = 0; firstPixelHue < 5 * 65536L; firstPixelHue += 256) {
    int j = 0;
    for (int i = 0; i < strip1.numPixels(); i++){
      int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
      strip1.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
    }
    j = strip1.numPixels();
    for (int i = 0; i < strip2.numPixels(); i++){
      int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
      strip2.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
    }
    j += strip2.numPixels();
    for (int i = 0; i < strip3.numPixels(); i++){
      int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
      strip3.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
    }
    j += strip3.numPixels();
    for (int i = 0; i < strip4.numPixels(); i++){
      int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
      strip3.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
    }

    strip1.show();
    strip2.show();
    strip3.show();
    strip4.show();
    delay(wait);
  }
}

Here I used j as an index over the whole chain of LED strips and i as an index for the individual LED strip. So j is the index starting point of each strip. The calcuation of the hue is then done with the current total index (j as the offset of the current strip in the whole chain and i as the index of the current LED in the current strip) j+i. For actually setting the corresponding LED we use i as the index of the current LED in the current strip.
This solution eliminates the need for creating an additional array. Though it still can be optimized (mostly in terms of code structure). I will leave that to you if you really want to optimize further.
Note: I haven't tested the above code, nor did I compile it.

Hello ! Sorry for the long reply had to deal with something. I will try this out.


text:
Suggest me Arduino device with USB for Mass storage
I want to make a temperature data logger by using Arduino.
I can read a data every 1sec and I want to store 30days data with date&Time.
In data logger, I want to write a temperature data with date&time in the .csv file and this file will be generated after I attaching USB.
So, Please suggest me Arduino board with USB compatible(working on 3V battery) and also suggest me EEPROM who able to store 30 days data.

Take a look at the Atmel SAMD21 xplained pro. Not an Arduino, but it's more powerful and has support for USB mass storage.

This sounds like a job for a Raspberry Pi

60 samples per minute, 60 minutes per hour, 24 hours per day, 30 days - that's 2592000 samples. At 10 bytes per sample (a very generous allocation) that's less than 30MB of data.
You could fit that many many times over on even the smallest of today's SD cards, so why mess with the complexity of USB? Any Arduino can work with an SD card.
A bigger concern of yours should not be the storage medium, which is trivial - you should instead be thinking about how you will run the board off a 3V battery for 30 days.

2937600 = 60602434.   60602430 = 2592000.

@JamesWaldby-jwpat7 You're not wrong there. My mouse must have been operating in nonagesimal at the time...

Despite your poor written question, I'll reply to you with a code, I used in my temperature logger 2 weeks ago. Includes LCD, temp sensor and SD card.
Delay is set for 9,1s which sums up with the calculation times of Arduino to 10 +/- 0.05 sec.
Lower it down to 100ms, if you want to be written every 1 second.
PS: The lower row, most right: There is a sign in letters, the condition of the sistem.
N = something's wrong, not inserted card/not connected SD card module
O = everything's okay, it's data logging
#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>
#define ONE_WIRE_BUS 6 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); LiquidCrystal lcd(8, 7, 5, 4, 3, 2);

const int chipSelect = 10;

void setup() {

  Serial.begin(9600);   Serial.println("Arduino Digital Temperature // Serial Monitor Version");   sensors.begin();
     lcd.begin(16, 2);   lcd.setCursor(0, 0);   lcd.print("Temperatura:");   //*********************************************
    while (!Serial) {   }   lcd.setCursor(15, 1);   lcd.print("??");   Serial.print("??");

  if (!SD.begin(chipSelect)) {
    Serial.println("NO");
      lcd.setCursor(15, 1);
      lcd.print("NO");
    return;   }   else   {   lcd.setCursor(15, 1);   lcd.print("OK");   Serial.println("OK");   }   //********************************************* }

void loop() {

  String dataString = "";

  float abc;

  sensors.requestTemperatures();     Serial.print("Temperature is: "); Serial.println(sensors.getTempCByIndex(0));   lcd.setCursor(0, 1);   lcd.print(sensors.getTempCByIndex(0));

  File dataFile = SD.open("datalog.txt", FILE_WRITE);

    if (dataFile) {
    dataFile.println(sensors.getTempCByIndex(0));
    dataFile.close();    Serial.println(sensors.getTempCByIndex(0));
    }
       else {
    Serial.println("error opening datalog.txt");   }

  //delay(9100);    }

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


text:
Problem with Arduino and INA226 power meter module
I am new to the use of Arduino in general, and to the INA226 Module for power metering.
I first got everything set up WITHOUT anything plugged to the INA226 module metering pins (V+, ISens+, Isens-, V- not connected to any power source) and running a sample code that gets data being read by the INA226, of course, all values return 0, but at least I know the program runs and the arduino can connect to the INA226. Now, the problem comes when I try to get some reading such as 5V or even 3.3V from the Arduino pins.
I connected the circuit as follows:

simulate this circuit – Schematic created using CircuitLab
(I noticed that I wrote A6 instead of A4, sorry about that)
But when I do this, there is no reading at all from the serial console. I tried connecting the V+ and Isens+ directly to the 5V pin leaving everything else as shown in the diagram, but the Arduino board doesn't even turn on.
I tried referencing other sources, but their tests use external power supplies or other equipment I don't have.
I would be really thankful if someone could lend me a hand here or help me understand why am I having this problem and how can I make it read something basic such as 5V or 3.3V directly from the Arduino board.
Thanks!

I normally use 4.7K for the pull ups, don't know if that will make a difference

You need a shunt resistor between Isens+ and Isens- to get any meaningful readings. You also need a load between V+ and Isens+. The way you have it wired right now makes no sense.

@majenko Thank you very much for your reply. I tried getting the load from the Arduino board itself as I don't have many resources and I want to test this INA226 module. Also, as far as I know there is already a shunt resistor embedded into the Module, do I need an additional one?

There is a discrepancy in pin terminology between your schematic & what TI uses in their datasheets. I don't see anything in their datasheets using I+ or I-. I only see V+ & V-. These 2 pins perform all your voltage & current measurements depending on the "mode" you tell the IC to use.
As near as I can tell based on your schematic, you should be seeing the voltage reading based on what is applied between V+ & V- (In your case, 3.3vdc) if you've told the chip to read the bus voltage channel.
You should also be getting a current reading between the V+ & V- pins if you've told the chip to read the shunt voltage channel. Since the part is designed for a full scale voltage differential of 36v between the V+ & V- pins, I suspect a reading of about 10% of max (based on a 3.3v differential).
I confess to not knowing the board or its operation but having looked it up on the TI website, it does appear to have a few jumper settings & a calibration routine to follow. There's a user guide on TI's website as well as the usual technical data pages. Perhaps those will assist in setting the jumpers correctly. ina226 data sheet & eval board user guide
bc

Thank you very much for your detailed reply @user33722 . This module I'm using has some additional components such as the shunt resistor you mentioned I was missing, it's all integrated into it. Turns out it was just a simple wiring problem and now I got it working fine.
For future reference, this is where more information can be found for this module and wiring https://strawberry-linux.com/pub/ina226-manual.pdf (Japanese)

If this is the usual Arduino-style module with a shunt resistor already in it, then with your schematic, you have [nearly] shorted your supply rail. Your schematic should have the load wired in series to the Isense+ and Isense- terminals, and the V+ and V- terminals should be connected in parallel across the voltage powering the load.
The current must "pass through" the Isense terminals, and the module has to measure the voltage across the load in order to be able to get both I and V to compute power consumption.

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


text:
How can I add a LED to this build?
I recreated this project from Fritzing in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.
The concept behind it is:

You plug it in and the time is set to 00:00
You can adjust the time to the time now let's say 22:46
You can put in an alarm to wake up let's say an hour later at 23:46
The piezo beeps in stops, so not continious.

So now my question is, how can I add a led that flickers on the same rhythm as the piezo (when the alarm goes off)? Can someone help me in my circuits.io project?
An update/edit would be great! I'm relatively new to all of this.
Thanks a lot!

That is impressive.  But when it comes to actually building the thing, my opinion is that you would be better off with an actual RTC module like the DS3231.  It not only holds the time even when the power is off, (once you set it with a separate program), but you can also program it to alarm and interrupt the Arduino to trigger the piezo and LED.

Also posted at https://www.reddit.com/r/arduino/comments/6atwt3/how_can_i_add_a_led_to_this_build/

You need to add an LED and series resistor between a currently unused Arduino pin and ground.
In your setup() function, set that pin's i/o mode to OUTPUT.
Where the code turns the tone on, it should also make the LED pin HIGH.
Where the code turns the tone off, it should also make the LED pin LOW.

Why not hang it off the same pin?  If the piezo is software-controlled, problem solved.  I do that for my low-voltage alarms on the solar plant battery monitoring system.  Of course, if the piezo is doing the sound timing internally, that would be a different problem.

That will work but the LED will run at 50% brightness - the tone() function being used in the OP's code generates a 50% duty-cycle square wave at the specified frequency. The sum of the currents drawn by the LED and the Piezo must also be within the pin-driver limits.


text:
How can I automatically get the time from the computer into an alarm clock (starts at 00:00 when plugged in)?
Okay so I did this project from Fritzing first in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.
But here is what I wanted to add, as you can see when you plug the arduino in it will set the time to 00:00 and you can adjust it yourself to the time right now, let's say 12:57. Then you put in the alarm so let's say you want to sleep an hour u put the alarm on 13:57.
Is there a way to automatically get the time from the computer? So you don't have to adjust it yourself everytime and start from 00:00.
Thanks for all the help!

Two ways: 1. Add a network interface to get the time from an internet time server (for example). 2. Write some software for your PC that gets the time and have the Arduino communicate with that through serial.

Alternatively add an RTC so it remembers the time while it's turned off.

But be careful some popular/cheap RTC modules claim to have recharge circuits when they don't and vice versa. (+1 for a good first question, BTW)

There are also atomic clock and GPS options Reading atomic radio clock

There are several ways, and they are covered in the comments above.

The answer to your question. Via Arduino USB to serial interface. and a simple batch file on a windows computer example:
@echo off
set datetimef=%time:~0,2%.%time:~3,2%:%time:~6,2%
echo %datetimef% > COM5

COM5 is used as a example, your serial port can be another number.
The format in the example is hour.minute:second

And you may also need to set the COM port to correct speed: mode COM5 BAUD=9600 PARITY=n DATA=8


text:
Linking Arduino Nano with ESP8266 Wifi module
I recently started playing around with Arduinos to connect a few sensors up. I used an Arduino Nano to measure temperature, humidity, air pressure and light level.
To store the data in a database, I used another Arduino that I connected to a Raspberry Pi, and let the two Arduinos talk wirelessly to each other via 433 MHz.
That all works pretty well, but the 433 MHz communication is not exactly the most reliable (I often miss a transmission). When I stumbled upon the ESP8266 module, it seemed like the optimal solution for communication. How cool would it be if I could just pull out the information via an HTTP call from the Raspberry Pi?
After toying around for many hours, uploading many different firmwares, getting more and more frustrated because I could not get it to do anything, I finally have it working through an FTDI module connected up like this:

I use an MB102 power module to provide the 3.3v required by the ESP8266. I turns out you need to connect the ground from the MB102 to the ground of the FTDI module to get any proper response. After doing that I was able to send AT commands and get the proper responses. I could even connect it to my home Wifi.
The next thing I want to do is connect it to the Arduino. I found a very simple schema for that (http://blog.huntgang.com/2015/01/20/arduino-esp8266-tutorial-web-server-monitor-example/), where you connect RX to TX and TX to RX. Using the MB102 I connected it like this:

Apparently I should now be able to upload a blank sketch to the Arduino, and then use the serial monitor again to sens AT command, exactly the same way I did it when using the FTDI module.
The problem is that I get nothing at all this way. I don't even see my own AT commands in the console. I do see the ESP8266 flashing every time I send a command (I even see it it still connected to my router, probably it remembered the info I send through the FTDI...?)
The question is, what am I going wrong? I read some posts about the TX from the Arduino also being 5v and that you need to do something to bring it back to 3.3v, but there are also many tutorials that say it's not required.

The easiest way to work with these devuces is to connect them to a spare pair of Arduino pins and use SoftwareSerial for communicating (unless you're using one of the Arduinos with more than one UART). SoftwareSerial work up to 9600 baud on 16MHz devices, 4800 on 8MHz devices, so you'll need to set the ESP8266 to accommodate that. They currently ship at 115200 baud. You can use the hardware UART on pins (0, 1) but then re-programming the Arduino means disconnecting & reconnecting the ESP temporarily each time, and gets old pretty quickly.
Here's what I do with new ESPs (If you've re-flashed your ESP, you'll need to download the AT instruction-set emulator and re-flash it with that, first):
# To configure a new ESP module:
# Connect the ESP and the FTDI as in your top diagram, set your
# terminal-emulator to 115200 baud, and enter the following:

AT                             # ESP should respond "OK"
AT+RST                         # Resets the ESP
AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

# Now change the terminal emulator baud rate to 9600

AT+CWMODE=1                    # Set ESP to station mode (client)
ATE0                           # Set ESP's echo off
AT+CWLAP                       # List access points - after a short pause
                               # the ESP returns a list of WiFi access points

For future reference, here is a link to the ESP8266 AT Instruction Set.
Update June 2020: The above link was broken, now fixed. You can also find documentation at Espressif's github account (online readable, but not pdf, as of this date).

I just realized this question has been dredged up from the archive of unanswered questions from 6 months ago. Oh, well - maybe this answer will help someone else now or soon.

Yes, if you are using different power sources the grounds always have to be connected, otherwise the boards don't know what zero volts is.
The TX of the Arduino is 5v, you need a level shifter to convert 5v to 3.3v, something like this (https://shop.pimoroni.com/products/adafruit-4-channel-i2c-safe-bi-directional-logic-level-converter?utm_medium=cpc&utm_source=googlepla&variant=302017581&gclid=CPqujsPxlc0CFcYcGwodb8YIoA)
The TX of the ESP8266 is 3.3v and the RX of the Arduino is 5V and you will need a level shifter to handle this.  You can use the same one as listed above, because it can convert 4 high (5v) signals into 4 low (3.3v) signals.
People say you can so it with resistors, but I have also read that they don't perform well enough to handle fast switching digital signals (so 300 Baud on your serial might be OK, but not 115000 :) )
People also say you don't need level convertors.  That's true things might work for a while without them, but sooner or later something will go pop.  Increasing the voltage will speed up the process so you can imagine what will happen if you connected a 230v supply directly to a USB device.
One final point, do you know the ESP8266 is a 80/160MHz processor with 256KB of RAM, when you compare that to you Arduino its like programming you PC via your phone.  What you could try is connecting the ESP8266 via a FTDI module and program it via the Arduino IDE in Arduino C.  Its a lot easier than all this connection stuff.

There might be an issue with the baudrate from the Nano FTDI chip to the RX/TX and the ESP8266. Did you disconnect when uploading the sketch?
How about trying this instead?
Cheers!

When I work with the ESP8266, it works om 115200 baud, everything else just gives garbage. I've tried the code from the linked blog (only changing the baud rate) , I see it's sending command to the ESP8266 (blue light flashing), but it fails when it tries to execute the Serial.find(">") command. I also see nou output from the ESP8266 whatsoever. I did disconnect the ESP8266 while uploading.

Stumbled on good tutorial here, tried and it does the job:
https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/

That will work except for the CIOBAUD command which has been replaced. The current command for all UART functions is: AT+UART_DEF=<baud>,<databits>,<stopbits>,<parity>,<flowcontrol>, or AT+UART_DEF-9600,8,1,0,0 to be compatible with SoftwareSerial. Replace "_DEF" with "_CUR" if this change is only for the session; the first command makes it the power-on default.

Please can you expand on the information from that blog into this answer if the link dies, but also to make it a better answer


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

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

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

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

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

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

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

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

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

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

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


text:
How to set limits in Arduino of pin x to remain in high state?
I am working on this thermostat, which has a predefined int that sets pin high and low. But now I want to give it a particular range on which the pin 7 stays high, let's say from 24°C to 26°C, because I don't want my relay clicking every second.
const int sensor=A1; // Assigning analog pin A1 to variable 'sensor'
int relay=7;
float tempc;  //variable to store temperature in degree Celsius
float vout;  //temporary variable to hold sensor reading

void setup() {
    pinMode(sensor,INPUT); // Configuring pin A1 as input
    Serial.begin(9600);
}

void loop() {
    vout=analogRead(sensor);
    vout=(vout*500)/1023;
    tempc=vout; // Storing value in Degree Celsius
    vout=analogRead(sensor);
    vout=(vout*500)/1023;
    tempc=vout; // Storing value in Degree Celsius
    Serial.print("temprature in C is ");
    Serial.print(tempc);
    Serial.println();
    delay(2000);
    if (tempc <24) {
      digitalWrite(7,HIGH);
      Serial.print("heating is on as " );
    } else {
      digitalWrite(7,LOW);
      Serial.print("heating is off as ");
    }

Do you mean that you want hysteresis so that the relay goes ON when the temperature goes below 24, but only goes OFF again when the temperature goes above 26?

Your question is not very clear, but I assume, like Mark Smith, that you
want your thermostat to be
hysteretic between 24°C and
26°C. The algorithm is as follows:

If the heater is OFF and you get a temperature reading below 24°C,
then you switch it ON.
If the heater is ON and you get a reading above 26°C, then you switch
it OFF.
In any other case, you leave the heater alone: it will stay in
whatever state you have previously set it.

Translated to C++:
// Pinout.
const uint8_t sensor = A1;  // temperature sensor
const uint8_t heater = 7;   // heater connected through a relay

void setup()
{
    pinMode(sensor, INPUT);
    pinMode(heater, OUTPUT);
    Serial.begin(9600);
}

void loop()
{
    static bool heaterOn;
    float temperature = 500.0 / 1024 * analogRead(sensor);

    // Switch ON if the temperature drops below 24 Celsius.
    if (!heaterOn && temperature < 24) {
        Serial.println(F("Switching the heater ON."));
        digitalWrite(heater, HIGH);
        heaterOn = true;
    }

    // Switch OFF if the temperature rises above 26 Celsius.
    else if (heaterOn && temperature > 26) {
        Serial.println(F("Switching the heater OFF."));
        digitalWrite(heater, LOW);
        heaterOn = false;
    }
}


text:
Where is PORTB defined?
On Arduino I can set digital pins by setting special variables PORTB and PORTD (or maybe they are not variables?). Where are those variables defined? I grepped /usr/share/arduino, but found nothing.
grep -r 'PORTB' /usr/share/arduino/

PORTB is defined by the "toolchain". It is not defined by Arduino.
For instance in my setup the Arduino Uno uses "toolchain" avr-gcc\4.9.2-amtel3.5.3-arduino2\avr.
If you grep that folder (location dependent on tool and installation options) you will find a file called iom328p.h that defines
#define PORTB _SFR_IO8(0x05)

This is a mapping to a physical address of the cpu.

Thank you. And how does this file gets included when my program is compiled and linked? Is it included by Arduino.h?

Arduino.h includes avr/io.h, which in turn includes the ioXXX.h file relevant to your specific MCU.

. Where are those variables defined?

In the device header file. Like other device specific macros.


text:
Is the shiftOut code depending on the (low) speed of an Arduino?
In the (official) file wiring_shift.c I found the following code for shiftOut:
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

However, the last two digitalWrite commands occur directly after each other. I wouldn't hope that digitalWrite depends on some time or delay, so how can it be assumed that the slave device sees the clockPin is HIGH if the Arduino immediately sets the clockPin to LOW again?
(My plan is to convert the shiftIn/shiftOut code to STM32 using HAL/CubeIDE).

Some time ago, I timed digitalWrite() and direct port write commands by looping over 10,000 executions of each and timing them with millis(). I made both tests on a 16MHz Atmega 328p at 16MHz.
For digitalWrite(13, LOW), I got 2.7usec / call.
For PORTB &= 0x20;, I got 0.15usec / statement. (The direct port access was executed 10 times within the loop to further pad it out for the millis() result to have any significance.)
[In my notes I wrote that I timed PORTB &= 0x20;, but the correct equivalent to the digitalWrite() version is PORTB &= ~0x20;. That is probably what I actually did, but note that the bit-mask would be generated at compile time, so either way should have produced the same result.]

how can it be assumed that the slave device sees the clockPin is HIGH

It would depend on the specifics of the slave, but it is quite likely triggered by a pulse, rather than polling its input until it finds a high-level.
Update:
To confirm my timing data, I redid my 2.5-years-ago experiment. I put 10 statements in each of 2 loops of 10,000 iterations, either:
digitalWrite(13, LOW);

or
PORTB &= ~0x20;

And got these total times in msec for the 100,000 executions:
digitalWrite(): 305     // digitalWrite(13, LOW);
PORTB (correct): 15     // PORTB &= ~0x20;
These translate to single execution times in 10s of nanoseconds:
3050 nsec == 3.05 usec for the function call,
150 nsec for direct port I/O, making port I/O about 20x faster.

Re “either way should have produced the same result”: Not really. The compiler can see that PORTB &= ~0x20; affects a single bit, and compiles that to a single cbi instruction that executes in 2 CPU cycles (0.125 µs @ 16 MHz). PORTB &= 0x20; is likely going to give you a 3-cycle read-modify-write sequence (0.1875 µs).

Back to the drawing board... :)

@JRobert thanks for the explanation, the first part I knew (kind of), but the second really answers my question exactly. I know that for timing mostly an IC checks the middle of a fixed state (either high or low), but if it triggers for an edge, yes, than it doesn't matter (as long as of course the IC has the time to get fully HIGH for a rising edge or fully DOWN for a falling edge, but I'm sure that's in the ns scale).


text:
How to purge incoming Xbee packets from the buffer?
I have a need to receive a specific confirmation packet after commanding my transmitting Xbee to stop sending normal packets.
My buffer still has normal packets in it when this happens, so next time I call readPacket(), I don't want to see them. So right before I call my stop command, I try to purge the incoming buffer like this:
void burnSerial(void) {
  while (xbee.readPacket(20)) {
    xbee.getResponse().getRx16Response(rx16);
  } //read all available responses
    // only do this when not in a constant stream of responses or it may hang.

  while (Serial.available()) { Serial.read(); }
  //burn whatever may be in serial buffer
}

But this doesn't work. The next time I call xbee.readPacket(), I see tons of normal packets before I finally see my confirmation packet. Why don't these functions do anything for me at all?

It means there's a lot of latency between your issuing a command and getting a confirmation of the command's effect. When you send the command, it's best that you wait and read packets until you find the confirmation and then you return from the function or do whatever else you want to do. There is no need for a separate burnSerial() function, nor should you blindly discard data. So basically, the sequence of operations should be:

Send the command
Read packets until you find the 'confirmation' identification marker
Return or exit

This assumes that your transmitter only sends confirmation after it has halted the stream.


text:
Getting wrong values from serial.read() connected to a Raspberry Pi
I set up a serial connection and sending integers from a Raspberry Pi to an Arduino.
This is the Python code in my Raspberry Pi:
import serial
ser = serial.Serial('/dev/ttyACM2', 9600)
ser.write(str(x_value));

And this is the command line output for x_value:

-38 -38 -38 -40 - 38 - 39 - 40 - 12 18 26 25 49...

They are x coordinate values I generated and they range from -100 to 100. And here's the Arduino code for receiving serial data:
int ByteReceived;

void loop() {
  while(1) {
    if (Serial.available() > 0) {
      ByteReceived = (Serial.read());
      Serial.print(ByteReceived);
      Serial.print("\n");
    }
  }

On the serial monitor I'm receiving these numbers:

46 45 51 48 45 53 52 45 49 52 45 52 55 55....

They are numbers between 40-60 and no way proportional to the values I sent from serial.write.
I'm really confused right now. Can someone help me to figure out what caused this problem?
Thank you so much.

You're receiving a different type than you're transmitting.

Learn the meaning of ASCII...

46 45 51 48 45 53 52 45 49 52 45 52 55 55....
. - 3 0 - 5 4 - 1 4 - 4 7 7...

ser.write(str(x_value));

Writes the string representation of the integer x_value, which is a sequence of ASCII characters.
ByteReceived = (Serial.read());
Serial.print(ByteReceived);

Reads a character (byte) and prints to the value (again as a sequence of characters).
45 51 48 45 53 52 45 49 52 45 52 55 55....

45 is ASCII character value for the character '-', 51 is the character '3', 48 is '0' and so on.
Cheers!


text:
Using an Arduino as a lithium ion charge controller
I have a trinket that I'm going to be powering off of a small lithium ion battery. I was also considering adding a small solar panel to the mix, and using the solar panel to charge the battery. I'm wondering if I can use the trinket itself as a smart charge controller to charge and monitor the battery.

I'm not saying you can't.  All I'm saying is by the time you do have the equivalent of a "good" Power Management Chip (PMC), you will have used up a lot of trinket resources.  But it you are in it to learn - go for it!

Yeah, wondered if I could simplify it, not make it too complex, something similar to the way Arduino approximates a PID, monitor the voltage and toggle the charge on and off periodically

If you're new to this then you should consider using LiFePO4 instead. It's a little more forgiving of screw-ups.

Why not use a charging+protection IC?

If you have a small solar panel, you probably don't have to worry about limiting the charge current (as the battery will be able to handle more that the solar panel can supply).
So the only thing left to do is prevent over-charge (i.e. disconnect the solar panel if the voltage on the battery goes above 4.2V). Protected cell can do this for you. I'm not knowledgeable enough to know if it's a good idea to rely on this.
Also make sure the solar panel isn't connected when it's dark, as the solor panel will use current when it's not generating it. Though a simple diode will do this trick. But you'd get a 0.6V drop on the diode, so you might want to get some extra efficiency by detecting output and switching the solar panel using the Arduino.
The last problem is overdischarge, unless you have a protected cell. But that's a problem you have, even without the charging bit.

Never rely on the in cell protection. It is there as an emergency fail safe, not part of the battery management.

If you are going to design your own battery management system here are a few issues you will need to deal with:

You need to understand the methods to determine the End Of Charge (EOC).  This could be monitoring cell temperature, measuring cell voltage or current for patterns, or integrating current over time (coulomb counter).  Different battery chemistries usually dictate which approach to take.
You need to check with the specific battery manufacturer to determine what charge rate you should use for this specific battery.  Knowing the chemistry is good.  But it is usually best to use the charge rate data from reputable manufactures.
Some batteries can not be completely drained.  If not already part of the LION battery, you will need to design a protection circuit to cut the battery off before this happens.
For such batteries, you need to add a trickle charging circuit in case the battery has been overly discharged.  Such a circuit only allows a small amount of current in.  The current is usually so small that normal monitoring is not necessary.  This is a last resort procedure built into most good chargers to recover overly discharged LION batteries.

...this is not a complete list. These are some of the issue which might be considered when designing a secondary battery charger.  There is a lot more good information about batteries here if you would like to research this subject in greater depth.

Try this. It's the Adafruit PowerBoost 1000 Charger - Rechargeable 5V Lipo USB Boost @ 1A - 1000C.
It's designed for Lipo, but I think it should work for Li-ION

well, cost is an issue, was wondering if I could simplify it ... also I want to use a solar cell as the charger, so this chip would not work


text:
Getting a truly random number in Arduino
What is the best method to get a truly (as opposed to pseudo) random number in Arduino, or at least the best possible approximation? From my understanding, the function randomSeed(analogRead(x)) it's not random enough.
If possible the method should leverage the basic Arduino setup alone (no additional sensors). Solutions with external sensors are welcome if they improve significantly the randomness over the basic setup.

What is the application? Must it be cryptographically secure? What are you doing with the randomness then? Then without an external chip implementing a TRNG from a physical entropy source, you're out of luck. You could also implement a determenistic RNG like a HMAC DRBG and seed it from something static plus a low-quality entropy source, but that still won't be cryptographically secure.

Yes, I need random numbers for cryptographically secure applications.

randomSeed(analogRead(x)) will only produce 255 sequences of numbers, which makes it trivial to try all combos and produce an oracle that can couple to your output stream, predicting all the output 100%. You are on the right track however, it's just a numbers game, and you need a LOT more of them. For example, taking 100 analog reads from 4 ADCs, summing them all, and feeding that to randomSeed would  be much better. For max security, you need both unpredictable input and non-deterministic mixing.
I'm not a cryptographer, but I've spent thousands of hours researching and building hardware and software random generators, so let me share some of what I've learned:
Unpredictable Input:

analogRead() (on floating pins)
GetTemp()

Potentially Unpredictable Input:

micros() (w/ a non-deterministic sample period)
clock jitter (low-bandwidth, but usable)
readVCC() (if not battery-powered)

External Unpredictable Input:

temp, humidity, and pressure sensors
microphones
LDR voltage dividers
reverse-bias transistor noise
compass/acceleration jitter
esp8266 wifi hotspot scan (ssid, db, etc)
esp8266 timing (the background wifi tasks make scheduled micros() fetches indeterminate)
esp8266 HWRNG - RANDOM_REG32 -extremely fast and unpredictable, a 1-stop

collecting
The last thing you want to do is spit out entropy as is comes along. It's easier to guess a coin flip than a bucket of coins. Summing is good. unsigned long bank; then later bank+= thisSample; is good; it will roll-over. bank[32] is even better, read on. You want to collect at least 8 samples of input for each chunk of output, ideally much more.
Guarding against poisoning
If heating the board causes a certain max clock jitter, that's an attack vector. Same with blasting RFI towards the analogRead() inputs. Another common attack simply unplugging the unit thus dumping all the accumulated entropy. You should not output numbers until you know it's safe to do so, even at the cost of speed.
This is why you want to keep some entropy around long-term, using EEPROM, SD, etc. Look into the Fortuna PRNG, which uses 32 banks, each one updated half as often as the one before it. That makes it difficult to attack all 32 banks in a reasonable amount of time.
Processing
Once you collect "entropy", you have to clean it up and divorce it from the input in a hard-to-reverse way. SHA/1/256 is good for this. You can use SHA1 (or even MD5 really) for speed since you don't have a plaintext vulnerability. To harvest, never use the full entopy bank, and ALWAYS ALWAYS add a "salt" to the output that's different each time to prevent identical outputs given no entropy bank changes: output = sha1( String(micros()) + String(bank[0]) + [...] ); The sha function both conceals inputs and whitens output, protecting against weak seeds, low accumulated ent, and other common issues.
To use timer inputs, you need to make them indeterministic. This is a simple as delayMicroseconds(lastSample % 255); which pauses an unpredictable amount of time, making "successive" clock reads non-uniform in difference. Do that semi-regularly, like if(analogRead(A1)>200){...}, provided A1 is noisy or hooked to a dynamic input. Making each fork of your flow rather difficult to determine will prevent cryptoanalysis on decompiled/ripped output.
Real security is when the attacker knows your whole system and is still helpless to overcome it.
Lastly, check your work. Run your output through ENT.EXE (also available for nix/mac) and see if it's any good. Most important is the chi square distribution, which should usually be between 33% and 66%. If you get 1.43% or 99.999% or something edgy like that, more than one test in a row, your random is crap. You also want the entropy ENT reports as close to 8 bits per byte as possible, > 7.9 for sure.
TLDR:
The simplest fool-proof way is to the uthe ESP8266's HWRNG. It's fast, uniform, and unpredictable. Run something like this on an ESP8266 running the Ardunio core, and use serial to talk to the AVR:
// ESP8266 Arduino core code:
void setup(){
 Serial.begin(9600); // or whatever
}

void loop() {
  // Serial.write((char)(RANDOM_REG32 % 256)); // "bin"
  Serial.print( String(RANDOM_REG32, HEX).substring(1)); // "hex"
}

** edit
here is a bare-board HWRNG sketch I wrote a while back, operating as a not just a collector, but a whole CSPRNG spitting out of the serial port. It's built for a pro-mini but should be easily adaptable to other boards. You can use just floating analog pins, but it's better to add stuff to them, prefereably different things. Like microphones, LDRs, thermistors (trimmed to max spread around room temp), and even long wires. It does pretty well in ENT if you have even moderate noise.
The sketch integrates several notions I've mentioned in my answer and follow-up comments: accumulating entropy, stretching by over-sampling less-than-ideal entropy (von neumann said it's cool), and hashing to uniformity. It forgoes entropy quality estimation in favor of "gimme anything possibly dynamic" and mixing using a cryptographic primitive.
// AVR (ardunio) HWRNG by dandavis. released to public domain by author.
#include <Hash.h>

unsigned long read[8] = {0, 0, 0, 0, 0, 0, 0, 0};
const int pincount = 9; // adjust down for non pro-mini boards
int pins[9] = {A0, A1, A2, A3, A4, A5, A6, A7, A0}; // adjust for board, name analog inputs to be sampled
unsigned int ticks = 0;
String buff = ""; // holds one round of derivation tokens to be hashed.
String cache; // the last read hash

void harvest() { // String() slows down the processing, making micros() calls harder to recreate
  unsigned long tot = 0; // the total of all analog reads
  buff = String(random(2147483647)) + String(millis() % 999);
  int seed =  random(256) + (micros() % 32);
  int offset =  random(2147483647) % 256;

  for (int i = 0; i < 8; i++) {
    buff += String( seed + read[i] + i + (ticks % 65), HEX );
    buff += String(random(2147483647), HEX);
    tot += read[i];
  }//next i

  buff += String( (micros() + ticks + offset) % 99999, HEX);
  if (random(10) < 3) randomSeed(tot + random(2147483647) + micros());
  buff = sha1( String(random(2147483647)) + buff + (micros()%64) + cache); // used hash to uniform output and waste time
  Serial.print( buff ); // output the hash
  cache = buff;
  spin();
}//end harvest()

void spin() { // add entropy and mix
  ticks++;
  int sample = 128;
  for (int i = 0; i < 8; i++) { // update ~6/8 banks 8 times
    read[ read[i] % 8] += (micros() % 128);
    sample = analogRead(  pins[i] ); // a read from each analog pin
    read[ micros() % 8] += ( read[i] % 64 ); // mix timing and 6LSBs from read
    read[i] += sample; // mix whole raw sample
    read[(i + 1) % 8] += random(2147483647) % 1024; // mix prng
    read[ticks % 8] += sample % 16; // mix the best nibble of the read
    read[sample % 8] += read[ticks % 8] % 2147483647; // intra-mix banks
  }

}//end spin()

void setup() {
  Serial.begin(9600);
  delay(222);
  int mx = 2028 + ((analogRead(A0)  + analogRead(A1) + analogRead(A2)  + analogRead(A3)) % 256);
  while (ticks < mx) {
    spin();
    delay(1);
    randomSeed(read[2] + read[1] + read[0] + micros() + random(4096) + ticks);
  }// wend
}// end setup()

void loop() {
  spin();
  delayMicroseconds((read[ micros() % 8] %  2048) + 333  );
  delay(random(10));
  //if (millis() < 500) return;
  if ((ticks % 16) == (millis() % 16) ) harvest();
}// end loop()

(I’m short on characters here, sorry.) Good overview! I would suggest to use a counter for the salt; micros() is a waste of bits because it may jump by several steps between calls. Avoid the high bits in analogue inputs, restrict to the lowest one or two bits. Even with a targeted attack those are hard to pin down (unless you can put a wire on the Input). "Non-deterministic mixing" is not something you can do in software. SHA-1 mixing is standardised: https://crypto.stackexchange.com/a/6232. The indet. timer you propose is only as random as the source you already have is. Not much gain here.

sha simplifies and protects, so that you don't have to worry about how many bits to grab from an analog input for example. a few inches of wire connected to an analog (or a serpentine pcb trace) will swing it more than a few bits. the mixing is non-deterministic by virtue of the unsaved and unknown salt fed to the hash with a subsample of accumulated values. micros() is harder to replay than a counter, esp when fired at non-deterministic intervals.

I have a question. You said that taking 100 measures is better. But isn't taking lots of measures a sort of "average" that limits the effectiveness of taking these "random" data? I mean, usually you average to get less noisy (so less "random") measurements...

well I recommend constant sampling, i was just saying 100 is better than 1 since it offers more combinations. An accumulation model like Yarrow/Fortuna is still vastly better. Consider concatenating (not summing) those 100 analog samples before hashing; stronger because it makes sample order important, and being one char off yields a whole different hash. So, even though one could average the samples to get less noise, an attacker would have to verbatim recite all values or no match... My main point is "accumulate, mix, and verify" more than advocating a specific noise source.

The Entropy library uses:

the watchdog timer's natural jitter to produce a reliable stream of true random numbers

I like this solution because it doesn't use up any pins of your microcontroller and doesn't require any external circuitry. This also makes it less subject to external failures.
In addition to a library, they also provide a sketch that demonstrates the use of the same technique used to generate a random seed for the microcontroller's PRNG without the library:
https://sites.google.com/site/astudyofentropy/project-definition/timer-jitter-entropy-sources/entropy-library/arduino-random-seed

From my experience, analogRead() on a floating pin has very low
entropy. Maybe one or two bits of randomness per call. You definitely
want something better. The watchdog timer's jitter, as proposed in
per1234's answer, is a good alternative. However, it generates entropy
at a pretty slow rate, which can be an issue if you need it right when
the program starts. dandavis has quite a few good suggestions, but they
generally require either an ESP8266 or external hardware.
There is one interesting entropy source that has not been mentioned yet:
the contents of the uninitialized RAM. When the MCU is powered up, some
of its RAM bits (those that happen to have the most symmetrical
transistors) start up in a random state. As discussed in this
hackaday article, this can be used as an entropy source. It is only
available on a cold boot, so you can use it to fill an initial entropy
pool, which you would then periodically replenish from another,
potentially slow source. This way your program can start its work
without having to wait for the pool to slowly fill up.
Here is a example of how this could be harvested on an AVR-based
Arduino. The code snippet below XORs the whole RAM in order to build a
seed that it later feeds to srandom(). The tricky part is that the
harvesting has to be done before the C runtime initializes the .data
and .bss memory sections, and then the seed has to be saved in a place
the C runtime will not overwrite. This is done by using specific
memory sections.
uint32_t __attribute__((section(".noinit"))) random_seed;

void __attribute__((naked, section(".init3"))) seed_from_ram()
{
    const uint32_t * const ramstart = (uint32_t *) RAMSTART;
    const uint32_t * const ramend   = (uint32_t *) RAMEND;
    uint32_t seed = 0;
    for (const uint32_t *p = ramstart; p <= ramend; p++)
        seed ^= *p;
    random_seed = seed;
}

void setup()
{
    srandom(random_seed);
}

Note that, on a warm reset, the SRAM is preserved, so it still has the
whole contents of you entropy pool. This same code can then be used to
preserve the collected entropy across a reset.
Edit: fixed an issue in my initial version of seed_from_ram() that
worked on the global random_seed instead of using a local seed.
This could lead to the seed being XORed with itself, destroying all the
entropy harvested so far.

Nice work! can I steal? re: pins: one or two bits of unknown is enough if utilized right; that would only limit the output speed of perfect secrecy (yuck), but not the computational secrecy we need...

@dandavis: Yes, you can reuse, sure. You are right about analogRead() being usable if you know what you are doing. You just have to be careful not to overestimate its randomness when updating an estimate of your pool's entropy. My point about analogRead() is mostly meant as a criticism of a poor yet often repeated “recipe”: randomSeed(analogRead(0)) just once in setup() and assume it's enough.

If analogRead(0) has 1 bit of entropy per call, then calling it repeatedly will yield 10000/8 = 1.25 KBytes/sec of entropy, 150 times as much as the Entropy library.

If you don't really need entropy and simply want to get a different sequence of pseudo-random numbers on every startup, you can use EEPROM to iterate through consecutive seeds. Technically the process will completely deterministic, but in practical terms it's much better than randomSeed(analogRead(0)) on an unconnected pin, which will often make you start with the same seed of either 0 or 1023. Saving the next seed in EEPROM will guarantee that you start with a different seed each time.
#include <EEPROM.h>

const int seed_addr = 0;
unsigned long seed;

void setup() {
    seed = EEPROM.read(seed_addr);
    EEPROM.write(seed_addr, seed+1);
    randomSeed(seed);
}

If you need real entropy, you can collect it either from clock drift, or by amplifying external noise. And if you need a lot of entropy, external noise is the only viable option. Zener diode is a popular choice, especially if you have a voltage source above 5-6V (it will work with 5V too with an appropriate Zener diode, but will produce less entropy):

(source).
The amplifier output has to be connected to an analog pin, which will produce several bits of entropy with each analogRead() up to tens of MHz (faster than Arduino can sample).


text:
RF transmitter with external 8-12v power not working properly
So I have this pair of transmitter and receiver

RPI is powered by USB from laptop
Transmitter is connected to Attiny85 being interfaced from RPI at 3v3
Receiver is connected to Arduino at 5v
If I have transmitter VCC connected to RPI 5v, data pin to Attiny85 running at 3.3v and all of them having same ground - all works fine, but obviously range is not great.
At this point same ground connects: transmitter, Attiny, RPI.
So I've tried using external power supply for transmitter.
I have power brick with DC output running at 12v

DC output positive goes to VCC, negative to common ground.
At this point same ground connects: transmitter, Attiny, RPI, power brick.
This doesn't work at all, receive nothing.
I have YwRobot breadboard power, which is broken and now supplies 8v on 5v pins

I've connected same power brick DC output to YwRobot DC in, positive 5v from board (actually pushing 8v) goes to VCC, negative from board goes to common ground.
At this point same ground connects: transmitter, Attiny, RPI, YwRobot.
This setup transmits data some times, still worse results than connecting VCC to RPI 5v.
Am I missing something? Does external power supply has to be something specific? I've thought as long as grounds are connected any power supply can be used on transmitter.
Update:
This 433MHz transmitter with PCB integrated antenna from my thermostat (powered by 2xAA) has no problem penetrating 3 walls and floor in my house. Sorry for my ignorance, but I need to achieve similar form factor and performance. 2.4GHz modules also require a lot of pins limiting what else can be done with Attiny85.

Update:
Attiny is using manchester and software serial (part of Arduino IDE) on attiny core.
RPI is using serial, not sure which version, installed using sudo apt-get install python-serial

Nice powerbank, where did you buy it? It runs about 200USD on amazon. Does it take standard 18650 LiPo cells?

https://www.amazon.co.uk/gp/product/B01DLRGY8A it's enclosed unit

That’s an impressive 433 module, I can’t seem to find it on google however. Link?

Have you got an SDR dongle to verify that data is being transmitted at all? Can you attach an oscilloscope probe to the datapin going to the 433 module? Have you tried receiving on an arduino 168/328p? Have you verified that the attiny has enough RAM free? Are all the pins okay - what does ‘really pushing 8V’ mean? 8V to attiny?

Data is being transmitted - I connect transmitter and receiver wire directly as they all share same ground. There are no issues with receiver, because by changing power supply to transmitter, receiver starts to receive data. Basically 5v power of GPIO to VCC (transmitter) all good, 8v power of breakout power module to VCC spotty receiving, 12v power of power brick to VCC nothing received. All of them share GND so I'am just switching power cable while module is constant transmitting.

I have those 5V/3V boards, they are unsafe. Firstly, the FET will fail open if you pull too much current, secondly they output very noisy signal. Try a 7805/lm317 (and/or lm1117), esp. for radio stuff.

OK - I'm not concerned about 5V/3V board, but when I use my power brick directly to transmitter, is that the same thing? Power coming to transmitter is being too noisy? I'll look into voltage regulator, but could using voltage booster (5v -> 12v) be a better idea for transmitter VCC? I will have 5v power supply for RPI, so I would take v5 from power supply directly to voltage booster and from voltage booster to VCC.

If it uses a step-down, it will have a certain frequency for 5V signal - you can use a 7805 with 0.22 and 0.1uF caps to smoothe this out. Be careful, it will surge to 6-7V for a millisecond if fed from 12V. You can look at this: http://www.electronicdesign.com/power/select-right-varistors-overvoltage-circuit-protection . Usually my arduinos don’t die from this momentary surge:) P.S.: Google best cap values for your design; .22 and .1uF are not mandatory.

Those 433MHz modules are tricky. I got the best results with 3V3 on the receiver, and 5V on transmitter. You should add an external antenna.
While it would be prudent to remove the little loop antenna, you don’t need to. I got an okay signal at 25 meters with line-of-sight. Metal, or brick will block the signal even at a meter or so - there’s no penetration. Consider a 2.4GHz module for high penetration at low range, or a LoRa module for high range (up to 10km).
A 433MHz antenna I’ve used with good results (can be cut for any frequency really)

Use the same material for both antenna and radials - copper is good - and optionally stiffen the radials with bicycle spokes on the inside ... make sure there is no electrical contact between the radials and the spokes; tape or heatshrink tube. I found coax cable to suck hard for this application, so I recommend using shielded headphone wire or something similar... just connect the shield to 0V/GND.
As for your breakout power module, I’ve had the same issue. Those modules are dangerous, avoid them. Use 7805 and LM1117 instead. Or just one 5V source (your powerbank?) and a TO-92 LM317 set to 3V3 output (max 100mA). Tiny 3V step-down converters like this can supply 800mA.
https://m.banggood.com/5V-To-3_3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-800MA-p-933674.html
( you can find them a lot cheaper )

My project is home automation setup, so 433MHz is preferred as 2.4GHz is so crowded and adding another 4 low-powered devices wouldn't improve situation. I've ordered these https://www.ebay.co.uk/itm/172936544379 to try out, but thing is, my current 433MHz still should work with very small antenna within the house. I've dissembled my current thermostat and it has similar 433MHz transmitter with tiny coiled antenna and have no problem connecting to boiler across whole house. I already have external antennas from multi-thread cable, but will try to get some solid copper wire for testing.

@goodevil You will not penetrate even a finger with these modules... the 2.4GHz modules have ways to mitigate band saturation - else look at 860/900MHz.

I've update my question - as similar size device is able to achieve what I need

With my current setup I am ALREADY penetrating wall and floor, adding another wall makes receiving spotty and taking receiver even further, prevents it from receiving anything.
I've update my question - as similar size device is able to achieve what I need, I assume I just missing something in my setup. nRF24L01 would leave my Attiny with no available pins, or in best case with 2 pins, which is my plan B if I can't replicate performance of current thermostat.

@goodevil What library are you using?

@goodevil ... on the pi and attiny85?

updated main question with list of libraries


text:
ATmega328 is not recognized by software
I installed the required drivers for the board. But I cannot still upload a program to the board. It says that
avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch
     System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : usb
     Using Programmer              : stk500v2

avrdude: usbdev_open(): did not find any USB device "usb" (0x03eb:0x2104)
avrdude done.  Thank you.
An error occurred while uploading the sketch

Please explain exactly what you're trying to accomplish. The error indicates you're doing either an Upload Using Programmer or Burn Bootloader rather than a standard upload over serial. Turn on File > Preferences > Show verbose output during: > upload, do an upload, when it fails you will see a button on the right side of the orange bar "Copy error messages". Click that button. Edit your question and paste in the full verbose upload output.

Can be many causes since you did not provide more info (like what circuit, what application). But in general:

Wrong software installation
Try another similar chip/device, maybe this one is broken
Is it recognized by USB at all?
Bad USB cable
Did you select the right board in the IDE (Arduino IDE?)

Possible solution:

Reinstall IDE
Change chip
Change Arduino
Use different cable

It was not recognized at all. The error message is
avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2014 Joerg Wunsch
System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"
Using Port                    : usb
Using Programmer              : stk500v2
avrdude: usbdev_open(): did not find any USB device "usb" (0x03eb:0x2104)
avrdude done.  Thank you.
An error occurred while uploading the sketch

In that case, try reinstalling the software, checking the USB (system) software, check if other avr's work, or check on another computer.


text:
How to change the default SPI pin used in SPI and Ethernet library
Hello i have a custom board of the RP2040 and would like to use the ethernet library. But the ethernet example webClient uses the default SPI pins of whatever board it is being used, but what if im going to use a board (such as the RP20400 with multiple SPI channels or have alternate pins for the spi chanels, How do i set the SPI mosi,miso,cs of the SPI in the ethernet library?
So i have found a way to make it work, i Edited the file under
\AppData\Local\Arduino15\packages\arduino\hardware\mbed_rp2040\2.4.1\variants\RASPBERRY_PI_PICO\pins_arduino.h

change the number to the pin you like.
// SPI
#define PIN_SPI_MISO  (0u)
#define PIN_SPI_MOSI  (3u)
#define PIN_SPI_SCK   (2u)
#define PIN_SPI_SS    (1u)

But problem with this now is every RP2040 board will now make it their default SPI pins,
Is there anything i can do to keep the modification to my own sketch only?

the Arduino Ethernet library uses the SPI object from the SPI library

@Juraj I could not find any SPI macros or declerations on ethernet.h which makes it tricky to trace

https://github.com/arduino/ArduinoCore-mbed/blob/master/libraries/SPI/SPI.cpp#L117

@Juraj Oh ! so its initialized at the inside the SPI.h and not ethernet.h. So as mentioned in my edit changing pin.arduino.h changes the setting for all the boards, in my sketch can i override that decleration. So maybe redeclare it after the SPI.h include, something like #include <spi.h>;  arduino::MbedSPI SPI(0, 3, 2); #include <ethernet.h>. I will try this out right away

https://arduino.stackexchange.com/questions/54484/adding-a-custom-board-to-the-arduino-ide/60660#60660

It would be a hasle if another PC will be used as i have to port the new variant every single time. For now im looking for ways to override that decleration, with my own. I think its easier that way plus, it makes the sketch portable as everything is done on the sketch

you can't do it in the sketch. the library files are compiled without knowing about the sketch. you can put the variant files on github as I do

@Juraj yes, thats why the redifinition must happen at compile time not at runtime, via a macro or some other means (not sure if C/C++ allows it, still looking for ways)

it is not possible. custom variant files or changing the library are your only options to change what pins will the SPI library use

@Juraj you are right the definition was not in the .h but the .cpp so that mean there is no way to access it in my sketch. a bit off topic quesiton, why do i not see what frequency the spi is set at? which file was the spi frequency set at?

the frequency is set for SPI transaction in the Ethernet library. https://github.com/arduino-libraries/Ethernet/blob/7c32bbe146bbe762093e4f021c3b12d7bf8d1629/src/utility/w5100.h#L21

Nice its using the default 14MHz , im using the w5500 and can go to 30Mhz

@Juraj there is way !! but sadly i cannot post it because question has been closed, we can reassign the pin as mentioned here https://github.com/arduino/ArduinoCore-mbed/issues/339. For i2c  MbedI2C myWire(6, 7); for SPI MbedSPI mySPI(4, 3, 2); and for uart UART mySerial(0, 1);

and how do you tell the Ethernet library to use mySPI?


text:
Infra Red sketch "not declared in this scope"
I'm pretty new at Arduino and I'm trying to upload a sketch with IR sensor to control LED-s.
I copy the code from internet,download library,I put my infrared codes for TV remote where I want and it says:"not declared in this scope"
Code and error:
#include <IRremote.h>

const int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
const int redPin = 6;
const int greenPin = 9;

void setup(){
  irrecv.enableIRIn();
  irrecv.blink13(true);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
}

void loop(){
    if (irrecv.decode(&results)){

        switch(results.value){
          case E0E036C9: //Keypad button "5"
          digitalWrite(redPin, HIGH);
          delay(2000);
          digitalWrite(redPin, LOW);
          }

        switch(results.value){
          case E0E028D7: //Keypad button "2"
          digitalWrite(greenPin, HIGH);
          delay(2000);
          digitalWrite(greenPin, LOW);
          }

        irrecv.resume();
    }
}

Error:
C:\Users\Kandzija\Desktop\saneta\saneta.ino: In function 'void loop()':
saneta:21: error: 'E0E036C9' was not declared in this scope
           case E0E036C9: //Keypad button "5"
                ^
saneta:28: error: 'E0E028D7' was not declared in this scope
           case E0E028D7: //Keypad button "2"
                ^
exit status 1
'E0E036C9' was not declared in this scope

Can you help me guys pls?
Thank You!

Numeric values in HEX need to be prefixed with 0x:
case 0xE0E036C9: //Keypad button "5"

and
case 0xE0E028D7: //Keypad button "2"


text:
Combining codes for 3 sensors
I am trying to combine codes for my 3 sensors: GSR, Pulse sensor, and ECG but I keep getting errors. I have a poor background in coding. I have the 3 codes separately and I'm not the one who wrote them.
Here are the new Sketch after Combining the loops and the setups.I didn't get any error after uploading and verifying but I am not getting values in my Serial Monitor
Combined sketch:
<!-- language-all: lang-cpp -->

#include <Wire.h>
#include "rgb_lcd.h"
#define ANALOG_IN 2   // analog input pin to display
#define OUTPUT_PIN 10 // test signal output pin
#define PULSE_MS 250  // pulse width in ms

int PulseSensorPurplePin = 1;        // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED13 = 13;   //  The on-board Arduion LED
int Signal;                // holds the incoming raw data. Signal value can range from 0-1024
int Threshold = 550;            // Determine which Signal to "count as a beat", and which to ingore.

const int BUZZER=3;
    const int GSR=A0;
    int threshold=0;
    int sensorValue;
    rgb_lcd lcd;

long ms;        // timer in ms
int out = HIGH;     // output level

void setup() {
   pinMode(LED13,OUTPUT);         // pin that will blink to your heartbeat!
   Serial.begin(9600);         // Set's up Serial Communication at certain speed.

   long sum=0;
      //VERIFY VALUE
      lcd.begin(16, 2);
      Serial.begin(9600);
      pinMode(BUZZER,OUTPUT);
      digitalWrite(BUZZER,LOW);
      delay(1000);
//VERIFY VALUE
      for(int i=0;i<500;i++)
      {
      sensorValue=analogRead(GSR);
      sum += sensorValue;
      delay(5);
      }
      threshold = sum/500;
       Serial.print("threshold =");
       Serial.println(threshold);

       pinMode(OUTPUT_PIN, OUTPUT);    // set output pin mode
       Serial.begin(19200);        // initiate serial communication
       digitalWrite(OUTPUT_PIN, out);  // set initial digital output
       ms = millis();          // query current time (in ms)

}

void loop() {
  Signal = analogRead(PulseSensorPurplePin);  // Read the PulseSensor's value.
                                              // Assign this value to the "Signal" variable.

   Serial.println(Signal);                    // Send the Signal value to Serial Plotter.

   if(Signal > Threshold){                          // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
     digitalWrite(LED13,HIGH);
   } else {
     digitalWrite(LED13,LOW);                //  Else, the sigal must be below "550", so "turn-off" this LED.
   }

delay(100);

   int temp;
      sensorValue=analogRead(GSR);
      Serial.print("sensorValue=");
      Serial.println(sensorValue);
      lcd.setCursor(0, 0);
      lcd.print("GSR Value: ");
      lcd.print(sensorValue);
      temp = threshold - sensorValue;
      if(abs(temp)>50)
      {
        sensorValue=analogRead(GSR);
        temp = threshold - sensorValue;
        if(abs(temp)>50){
       digitalWrite(BUZZER,HIGH);
        Serial.println("YES!");
        delay(3000);
        digitalWrite(BUZZER,LOW);
        delay(1000);}
      }

      int val = analogRead(ANALOG_IN);    // read voltage at input pin
  Serial.write( 0xff );         // write value to serial port
  Serial.write( (val >> 8) & 0xff );
  Serial.write( val & 0xff );

  if (millis() >= ms+PULSE_MS) {    // check if pulse width has elapsed
    ms = millis();            // query current time (in ms)
    out = !out;             // invert output value
    digitalWrite(OUTPUT_PIN, out);    // update digital output
  }
}

you can have only one setup() and one loop() subroutine ... you will have to merge the three subroutines into one for each of those .... first, you need to figure out what the code does

-1 for messing up code formatting after it was corrected. i will remove the downvote if you correct the formatting

@jsotola - isn't that blackmail :)

In general:

There can be only one setup, in most cases you can put the code from all three setup's together, but checkout the code does not interfere, i.e. does not use the same pins. In that case, change the pin numbers if possible (and change the circuit accordingly).
For the loops it can be more tricky:

Check how often each loop should be called. If one loop costs e.g. 500 ms that means the other loops will be called less often, which can affect the precision or even good readout of the sensor.
If all loops are relatively small and the duration do not matter, you can just call them after each other (rename the loops and call them one by one).
If there is a time constraint, than split the lengthy loop in a small part, and call it whenever needed. There is no clear rule for this.

What you can try is:

Check for reach loop how long it takes
Than for each loop add a delay with same time as the other loops, thus:

Test the duration (average) of loop 1, than of loop 2, than of loop 3. Assume loop1 takes 100, loop2 200 and loop3 300 ms.
Test loop1 without calling loop2 and loop3, but just add the delay (200+300=500 ms).
Check if it works, if so, it means you can call the other loops without problems.
Do the same for loop2 (with 100+300ms delay) and loop3 (100+200ms).
If all loops work correctly, than you can call the loop1, loop2, loop3 in sequence.
If not, you have to call the loop(s) that do not work either more often or in a different way.

Yep all that and use functions to break down you code into manageable chunks.  If its longer than 10 lines, or you do it more than once maybe it ought to be a separate function

@CodeGorilla good addition ... it also will make readability, efficiency, maintainability and testing easier to have small functions.


text:
Arduino IDE Can't find the USB Port
I'm on a Mac, running 10.11.6 and Arduino IDE 1.8.1.
I've been prototyping some projects using an Adafruit Trinket. I was not having any problems, until at some point my Mac stopped recognizing the trinket. Somewhere within that time, I installed the Digispark board and tested that as well. I also may have made some updates to the OS version.
I've tried many things to fix it including installing the FTDI drivers, plugging and unplugging. Restarts etc. Nothing seems to fix the issue. The board shows up in the system profiler, as well as USB Prober, but does not show as an option in the Arduino IDE. I've also tried using several different cables but no dice.
It's really frustrating, I'm not sure what else I can do to track the issue down.

Try changing your USB cable and sometimes cables can be charge only. You can check this by plugging in another board. If you change cables make sure that cable works with at least one other board.

Did you ensure the board is in Bootloader mode? https://learn.adafruit.com/introducing-trinket/starting-the-bootloader

This probably isn't relevant but: There was an issue with the FDTI chip that converts USB to serial.  The manufacturer enabled something in the drivers that prevented the Chinese clone chips from working.  Is it possible you were using an old version of the drivers that didn't have this feature and you have upgraded to the new version?  (That said I would have though Adafruit would have been using real chips, unless its an Adafruit copy)


text:
How can I reference an object from another file?
I am trying to write some code to make it easy to add different buttons to a touch screen. I need each object to be a different object of class 'touchButton'. I'd like to be able to run a touchButton.Draw function, which in turn will run LCD library commands. Is there a way I could do that? Here is my source code:
TouchScreen.ino:
#include "touchButton.h"
#include <UTFT.h>
#include <UTouch.h>
#include <avr/pgmspace.h>
UTFT    myGLCD(ITDB32S, 38, 39, 40, 41);
UTouch  myTouch( 6, 5, 4, 3, 2);
extern uint8_t SmallFont[];

void setup() {
  myGLCD.InitLCD();
  myGLCD.setFont(SmallFont);
  myGLCD.clrScr();
  myTouch.InitTouch();
  myTouch.setPrecision(PREC_MEDIUM);
  myGLCD.fillScr(51, 51, 51);
  //what I want to be able to do:
  //touchButton Button1 (10, 10, 20, 20, 'p');
  //Button1.Draw();
}

void loop() {
}

touchButton.h
#ifndef touchButton_h
#define touchButton_h
#include "Arduino.h"
class touchButton {
  public:
    touchButton(int x, int y, int xs, int ys, char use);
    void Draw();
    int x1;
    int y1;
    int xsize;
    int ysize;
    char use;
    boolean toggle = false;
};
#endif

touchButton.cpp
  #include "Arduino.h"
  #include "touchButton.h"
  touchButton::touchButton(int x, int y, int xs, int ys, char myuse) {
    x1 = x;
    y1 = y;
    xsize = xs;
    ysize = ys;
    use = myuse;
  }

  void touchButton::Draw() {
    switch (use) {
      case 'p':
      //this is what I would like to have called from the main file.
      //myGLCD.drawRoundRect(x1, y1, x1+xsize, y1+ysize);
        break;

       default:
        break;
    }
  }

The simplest solution (ignoring possible improvements) is to add the following to touchButton.cpp.
#include "Arduino.h"
#include "touchButton.h"

// Extern reference to the LCD instance
#include <UTFT.h>
extern UTFT myGLCD;

touchButton::touchButton(int x, int y, int xs, int ys, char myuse) {
  x1 = x;
  y1 = y;
  xsize = xs;
  ysize = ys;
  use = myuse;
}

void touchButton::Draw() {
  switch (use) {
    case 'p':
      myGLCD.drawRoundRect(x1, y1, x1+xsize, y1+ysize);
    break;

   default:
    break;
  }
}

There are several improvements such as passing the UTFT instance reference as parameter, moving myGLCD to a separate .h/.cpp file, etc.
An example of "extern" object reference may be found in HardwareSerial.h.
Cheers!

The best way is to provide the myGLCD object as a parameter to the constructor:
touchButton::touchButton(UTFT &glcddev, int x, int y, int xs, int ys, char myuse) {
  x1 = x;
  y1 = y;
  xsize = xs;
  ysize = ys;
  use = myuse;
  glcd = &glcddev;
}

Then in your header you provide a:
private:
  UTFT *glcd;

Your library code then uses the glcd pointer to the object:
glcd->drawRoundedRectangle(...);

Note the use of -> since glcd is a pointer to the object (as created by the & operator when it was assigned in the constructor).
Of course, as Miagma mentions, you need to ensure that anywhere that references any UTFT functions or objects has the UTFT.h header included or it won't know what you're talking about.
You can also do the same with the UTouch class - pass that object as a parameter, then each widget can have its own routine to deal with the touch events.
You can see all this kind of thing in action in the same context in the Widget class of my DisplayCore system for chipKIT boards:

https://github.com/MajenkoLibraries/DisplayCore/blob/master/DisplayCore/DisplayCore.h#L464
https://github.com/MajenkoLibraries/DisplayCore/blob/master/DisplayCore/DisplayCore.cpp#L1587

You are asking a question that can be considered as the classical:
"is a" vs. "has a"
If you want, you can find more details here.
On this specific case, I sort of agree with Majenko, that proposes to pass the address of the LCD object to each button, but I would prefer a different implementation where the pointer is stored in a static field shared by all the instances of touchButton, because you are always referring to the same object. That will of course change if you have more than 1 LCD.

I'm not 100% certain I understand what you mean. It's clear that you understand object-oriented code and some of the murkier aspects of c++, judging from what you wrote.
I apologize if you already know this (and I'm guessing you do) or if this is completely off base, but your code should already work. That is, you defined your class in your header, implemented it in the .cpp file, and then instantiated it in the .ino file. If you want to operate on it in another file, you could declare the variable as an "extern" data type, which is rather dangerous, or pass it as a reference to a function in another file.
However, I don't believe this is what you mean. From reading your code, I feel that you're asking how you can execute function "x" from another object every time you create a button.
If this is the case, it's definitely possible. myGLCD looks like it's an object (can't read it at the moment), which is good. What you can do is declare your touchLCD class as a derived class of whomever myGLCD belongs to -adding the appropriate header of course:
#include <Parent Class Name.h>

class touchLCD : public <Parent Class Name>.

If the functions you want are public or protected, then you can access them without restriction. Here you have a few options. The easiest would probably be calling the function from within the constructor. If you don't have access to the desired function, you'll have to define your class as a friend class.
Hope this helps.


text:
Arduino Uno + Jaguar Speed Controller + CIM Motor (12V DC)
I have connected a CIM motor to a Jaguar speed controller, powered by a 12V battery. The Jaguar is connected to an Arduino Uno via the signal and ground. Also, I have two switches connected to the Arduino, for forward and reverse of the motor.
In the code, for speed of the motor, I have set 90 as the mid point and 100 for forward and 80 for reverse. When I push the reverse button, the motor runs smoothly in the reverse direction at the set speed. However, the problem is, when I press the forward button, the motor runs seemingly slower in the forward direction than the set speed.
My logic here was, if I have set speeds in forward and reverse at +/- 10 from the mid-point, the motor should run at the same speed in the forward and reverse direction, but this is not happening.
I am pasting my code below. Any help would be much appreciated. Thank you!
#include <Servo.h>

int forwardPin = 2;
int reversePin = 4;
int motorPin = 10;
int fwdReading = 0;
int revReading = 0;

Servo myservo;

void setup() {
  TCCR1B = TCCR1B & 0b11111000 | 0x04; // PWM Freq. at 122Hz
  pinMode (forwardPin, INPUT);
  pinMode (reversePin, INPUT);
  myservo.attach(motorPin);
  myservo.write(90);  // set servo to mid-point
}

void loop() {
  fwdReading = digitalRead(forwardPin);
  revReading = digitalRead(reversePin);
  if (fwdReading == HIGH) {
    myservo.write(100); // forward
  } else if (revReading == HIGH) {
    myservo.write(80); // reverse
  } else
    myservo.write(90); // neutral
}

When I read Jaguar speed controller I imagined you were mounting this on a Jaguar XD anyway how do you detect that the motor is slower? How much slower? Did you get quantitative measures (e.g. with an encoder)?

@frarugi87 Haha...
Btw, no I haven't measured it, but by eyeballing one can tell that it is slower than the other direction.

Is there anything attached to it? And.. It would be better to test it using an encoder. And, in the end, remember that the controller board does not control speed directly, but just the voltage (and so the speed will not be controlled very well). I don't know if that controller board supports a speed feedback, but if you require a precise speed then you'd better switch to a closed loop design (either integrated - but I don't know them) or build one yourself

I searched for the library you're using and the arduino website mentions :

0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement

From this we can take that the value 90 is not perfectly in the middle of the speed range therefore 10 points under 90 won't necessarily be equivalent to 10 points above 90.
My only advice is to try and find the equivalence point yourself by trail and error.
Even though 90 seems to cause no movement, try 89 or 91 see if they also have the result and so on.
Or simply try different values to get same speeds in different directions, it's ok if you use different values (away from 90) for the two different directions :P.
Gd Luck