Four Fast PWM outputs, in parallel I need four Fast PWM signals for four different transistors.

I want to use timers 1+2 (pins 3, 11, 9, 10) so it wouldn't interfere with delay(...).

I tried setting the timers to Fast PWM mode, and applied different OCRnA/OCRnB values, but nothing really worked - at most, I managed to get two good PWM signals, one from each timer.

How should I deal with TCCRnA/TCCRnB, OCRnA/OCRnB to achieve 4 parallel PWM signals?

My latest attempt:

// Timer 1 Fast PWM setup: TOP=0x00FF, Update of OCRx at BOTTOM (0), TOV Flag Set on TOP
pinMode(9, OUTPUT); pinMode(10, OUTPUT);
TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
TCCR1B = _BV(WGM12) | _BV(CS11) | _BV(CS10); // Divisor 64
// Timer 2 Fast PWM setup: TOP=0xFF, Update of OCRx at BOTTOM (0), TOV Flag Set on MAX (0xFF)
pinMode(3, OUTPUT); pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS22); // Divisor 64
// ...
int val = 200; // Desired PWM output
OCR1A = val;
OCR1B = val;
OCR2A = val;
OCR2B = val;

Basically, your question comes down to this:

"How to generate two PWM signals with only one timer."

(Once you've got that figured out, you could set up 6 PWM channels)

Keep in mind that there also are PWM generator IC's, if you don't want to use up all your timers, which can be usefull for other things.

IF you really want to set all outputs to toggle at the same time (based on your code example) why won't you just use one PWM signal, and drive all the 4 devices with the same signal? (Given you're not going to change it)
IF you're going to drive motors, why would you need 4 different PWM signals? It's often enough to only use one PWM signal for the right tires/tracks and one PWM signal for the left tires/tracks.

Setting the max

Since we want to generate different PWM signals from one timer, we can't just make the timer overrun (and generate a pulse or switch polarity at that point).
We want to let the timer run to completion over and over, and only change the signal when it reaches a set value.

The datasheet tells us this:

  The TOP value can be assigned to be the fixed value 0xFF
  (MAX) or the value stored in the OCR0A Register. (328P datasheet 15.2.1 Definitions)

Setting a limit per pin

We want to set 2 limits on one timer, each timer has an output compare register (OCR), the action will be generated when the timer hits this value.

  The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt
  request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR0).
  All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). (328P datasheet 15.2.2 Registers)

Extra info on compare

Below you can read some extra info on the signaling.
What actually will happen, depends on how the WGM

  15.5 Output Compare Unit
  The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and
  OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the
  Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is
  enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is
  automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing
  a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output
  according to operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The max
  and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in
  some modes of operation (”Modes of Operation” on page 98).

Fast PWM
The actual settings are different per mode/modus, but for fast PWM we have:

Table 15-3. Compare Output Mode, Fast PWM Mode(1)
COM0A1 COM0A0 Description
0      0      Normal port operation, OC0A disconnected.
0      1      WGM02 = 0: Normal Port Operation, OC0A Disconnected.
              WGM02 = 1: Toggle OC0A on Compare Match.
1      0      Clear OC0A on Compare Match, set OC0A at BOTTOM, (non-inverting mode).
1      1      Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).

The table tells us we need to set COM0A1 and COM0A0 to 1.

COM0B1 COM0B0 Description
0      0      Normal port operation, OC0B disconnected.
0      1      Reserved
1      0      Clear OC0B on Compare Match, set OC0B at BOTTOM, (non-inverting mode)

This table tells us we need to set COM0B1 and COM0B0 to 1.

WGM mode

If it's all set up, we only need to put the PWM in the right mode.

Mode WGM02 WGM01 WGM00 Timer/Counter TOP  Update-OCRx TOV-on
0    0     0     0     Normal        0xFF Immediate   MAX
1    0     0     1     PWM,P-Correct 0xFF TOP         BOTTOM
2    0     1     0     CTC           OCRA Immediate   MAX
3    0     1     1     Fast PWM      0xFF BOTTOM      MAX

So we'll need to set WGM02 to 0 and WGM01 and WGM00 to 1, to use fast PWM.F

Succes?

You should now be able to change the PWM's of these pins by setting the output compare registers of these.
Getting the double PWM of the other timer ready, shouldn't be much more different.
Be sure to set the right prescaler. Though it depends on a lot of external things.


Distributing power evenly to multiple pins It's an arduino board, model UNO R3. I have 3 5cmx10cm heating pad power required 5V DC up to 1A and can withstand up to 12V DC. These 3 heating pad are wired up onto arduino board with red wires connected to pin 8 pin 9 and pin 10 on the digital side of the arduino and the black wire connected to GND (ground). Lastly I have a toggle on and off switch connected to the arduino with the red wire attached to digital pin 2 and the black wire to 5V. The arduino uno R3 withstand 20voltage and the 5V heating pads can withstand 12V. I would like my 20V external power to heat up all 3 heating pads evenly, how can I do this? Is it possible? Thank you!

Yes, of course it is possible.  But if all you need to do it to turn these heat pads on and off, an Arduino is perhaps not the most suitable technology.

But presuming these heat pads are a component of some more complex system that responds to other inputs or outputs to/from the Arduino, you will need a few more components.  You need to accomplish two things that the UNO R3 cannot accomplish by itself, because your heat pads are very much too large a load for your UNO to power directly.  (The power for a single LED bulb is about the most that you can draw from an output pin.)

You need to reduce your 20-V external power source down to something less than 12 volts to supply your heating pads.
You need to switch on and off up to 1 amp of current to flow to each of the three heating pads.  The UNO cannot do this directly.

There are a lot of ways to reduce your 20-volt supply down to less than 12 volts.  Some are much more efficient than others.  Probably the lowest cost efficient way is to use your 20-V source as the input a small DC to DC voltage down stepping converter.  These are available online from Chinese vendors for very low cost.  Just search for "DC-DC converter down".  A quick search finds one rated at 20 amps, with adjustable voltage output can be purchased for less than $10.  These are pretty efficient devices that don't waste the power that a simple voltage dropping resistor would waste.

Then you need either one or three 5-volt relays of some type to switch the power on to the heat pads.  The UNO pins output of 5-volts would not provide current to heat pads, put only enough current to energize the relay(s).  The relay(s) can be either solid state, or coil energized.  Just be sure the relay "contacts" are rated to handle well more than 1 amp if there are three of them, and more than 3-amps if only one.   An Arduino relay shield with four relays, each rated for 10 amps, can be purchased for less than $5.

If you only every want all three heat pads energized at the same time, you only need one relay, and one Arduino output to energize it.

The very simplest solution, if you only want all the pads heating simultaneously, would be to wire the three heat pads in series.  Then you could apply your 20-volts directly across all three heat pads, and you would not need any device to reduce your supply voltage.  Each heat pad would have 1/3 of 20 volts across it, which is well under their 12 volt tolerance.  And you would only need one relay.


Strange phenomenon when declaring double Consider this question closed, found my answer through the answers I had

I am trying to make a position profile curve depending on Looptime, accelerationloops,Setposition,Currentposition(position) and velocity.
The curve should look like this:

Is someone able to check what is wrong with my code?

float array[30];

struct Formula {
  int LoopTime = 1000;
  int AccelerationLoops = 11;
  float VelocityLoop = 0;
  float VelocityFactor = 0;
  int TotalLoops = 0;
  float DeltaPosition = 0;
  int Setpoint = 0;
  int Iteration = -1;
  float EndOne = 1.25;
}Formula;

float SetPosition = 1404;
float Position = 0;
float Velocity = 36;

void setup() {
  Serial.begin(115200);
  for(Formula.Iteration ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    ProgFormula();
    Serial.println(Formula.Iteration);
    if(Formula.Iteration >= 0) {array[Formula.Iteration] = Formula.Setpoint;}
  }
  for(Formula.Iteration = 0 ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    //Serial.println(array[Formula.Iteration]);
  }
}

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

}

void ProgFormula(){
  if(Formula.Iteration == -1) {
    Formula.DeltaPosition = SetPosition - Position;
    Formula.VelocityLoop = Velocity / (1000 / Formula.LoopTime);
    Formula.TotalLoops = Formula.DeltaPosition / Formula.VelocityLoop + Formula.AccelerationLoops;
    Formula.VelocityFactor = Formula.VelocityLoop * 0.5 / Formula.AccelerationLoops;
    Formula.EndOne = (Formula.VelocityFactor*pow(Formula.AccelerationLoops,2));
  }
  else if (Formula.Iteration >= 0 && Formula.Iteration <= Formula.AccelerationLoops) {
    Formula.Setpoint = Formula.VelocityFactor * pow(Formula.Iteration,2);
  }
  else if (Formula.Iteration > Formula.AccelerationLoops && Formula.Iteration <= (Formula.TotalLoops - Formula.AccelerationLoops)) {
    Formula.Setpoint = Formula.VelocityLoop * Formula.Iteration - Formula.EndOne;
  }
  else if (Formula.Iteration >= (Formula.TotalLoops - Formula.AccelerationLoops) && Formula.Iteration <= Formula.TotalLoops) {
    Formula.Setpoint = -Formula.VelocityFactor * pow((Formula.TotalLoops - Formula.Iteration),2) + Formula.DeltaPosition;
  }
  else {
    Formula.Setpoint = Formula.Setpoint;
  }
}

OK, this may not be a proper answer. I'm just having a hard time reading
your code, and I cannot understand why you make it so complicated. If
you know the acceleration profile, computing the position profile is
just a matter of integrating twice. Here is an example, not for Arduino
but for a PC. It should not be very different on an Arduino, you just
wouldn't use printf():

/* Compute position for any acceleration profile. */
void compute_profile(float (*acceleration)(int), int max)
{
    float x = 0, v = 0;

    for (int t = 0; t <= max; t++) {
        v += acceleration(t);
        x += v;
        printf("%d\t%f\n", t, x);
    }
}

/* Your particular acceleration profile. */
float VttgJ(int t)
{
    if (t <  7) return t;
    if (t < 13) return 12 - t;
    if (t < 40) return 0;
    if (t < 46) return 39 - t;
    else        return t - 51;
}

int main(void)
{
    compute_profile(VttgJ, 50);
    return 0;
}


Can a WiFi enabled Arduino make a HTTPS request to my Web Server? I need my Arduino to connect to my web server through HTTPS, can the Arduino handle it?

It only has to act as a client.

It sounds like a better way to do it would be to have a PHP script act as handoff server (maybe protected by originating IP address) to access the HTTPS site and provide the data over a less processor-intensive protocol.

How to get HTTPS on Arduino?

However, another answer suggests that we are working towards a solution to your issue, but it's not quite there yet (~12 seconds to encrypt a packet).

https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/


Inductive spikes upset Interrupts I am using an Arduino Uno to create a kinetic sculpture with magnets and electromagnets (EMs). I have a setup with two externally debounced buttons using resistors,capacitor and CMOS 4584 hex inverter. All non-used inputs of the 4584 are grounded. These buttons deliver a clean signal to the board and trigger the two interrupts which set flags to turn LEDs on or off and trigger one or both optoisolators (OIs).
These connect to another board with a separate 12V supply. One of the OIs turns a BUZ71 power mosfet on and the other triggers a relay which can reverse the polarity of the power to a small 30 ohm EM coil. This can make the magnet suspended above like a pendulum fly away from the coil...

This works perfectly well with the buttons,  the LEDs and the two inputs to the OIs  But when I connect the relay/mosfet board  to the output of the OIs it stops working properly. button 2 turns off button 1  as well as itself. Button one always turns off and on cleanly But button two triggers ISR2 about 10 times and ISR1 a couple of times, leaving both off. If I disconnect the EM coil the buttons work properly. It seems that switching the polarity is somehow interfering with the Uno maybe due to a fairly hefty inductive spike generated by switching the relay. I have tried using shielded coax to the coil. I have 47000 uF caps on both boards. I tried a crude faraday cage around the relay board - no luck. Could the spike be coming through the household power supply somehow even though the Uno board and the relay board have different power supplies and are fully seperated by the OIs?
Here is the sketch I am using:

    //  Coding by Jeremy 070520
//  development for ricochet module

const int coilButton = 2;
const int directionButton = 3;
const int coilPin = 8; //coil driver
const int directionPin = 9; //direction driver
volatile bool coilFlag;
volatile bool directionFlag;
int coilLedState = LOW;
int directionLedState = LOW;

void setup()
{
  pinMode(coilButton,INPUT);
  pinMode(directionButton, INPUT);
  pinMode(coilPin, OUTPUT);
  pinMode(directionPin, OUTPUT);
  digitalWrite(coilPin,LOW);
  digitalWrite(directionPin, LOW);
  attachInterrupt(digitalPinToInterrupt(coilButton), ISR1, FALLING);
  attachInterrupt(digitalPinToInterrupt(directionButton), ISR2, FALLING);
  Serial.begin(9600);
  }

void loop(){
  if(coilFlag)
  {
    coilFlag = false;
    coilLedState = !coilLedState;
    digitalWrite(coilPin, coilLedState);
  }
 if(directionFlag)
  {
    directionFlag = false;
    directionLedState = !directionLedState;
    digitalWrite(directionPin, directionLedState);
  }
delay(1);   //I'm desperate I will try anything ....
} //end loop

void ISR1()
{
  Serial.println("ISR1");
  coilFlag = true;
  }

void ISR2()
{
  Serial.println("ISR2");
  directionFlag = true;
  }

I'd suggest building a Faraday cage around the inductive coil. It's probably inducing enough current in all the wires around it to trigger logic level voltages in your signal wires, in the board, etc.

It sounds like the goal is for the coil to fling a magnet away, so you might have to settle for a "Faraday bowl" (an open-topped Faraday cage). Some magnetic field would leak out the top of the bowl, but if you place the control board below the bottom and several feet away it might be enough.

You might need to shield everything separately: Faraday cage around the Arduino. "Faraday Bowl" around the coil. Coax cables for everything, where the power to the coil is in a coax cable that's grounded separately, etc.


String array length in function I know this question has been asked a thousand times, but I can't find a solution for my case.
I what to get the length of a string array in a given function. This is for an arduino board.
#define LEN(x) sizeof(x)/sizeof(x[0])
const char* mainMenu[] = {"FirstWord", "SecondWord", " "};

void myFunction(const char** m) {
  int a = LEN(m);

  /* Do something */
};

void setup(){
   myFunction(mainMenu);
};

The LEN(m) works fine in the setup() function. But in myFunction() it either gives me 1 (i guess the length of the pointer) or 9 (length of the 0th element of the array)

The problem is that LEN is evaluated locally for each usage replacing it with the content. In myFunction the parameter being passed to it is a pointer, not the array.
You need to evaluate the size once and once only in the context where the array hasn't collapsed into a pointer. That is usually done immediately where the array is defined:
const char* mainMenu[] = {"FirstWord", "SecondWord", " "};
#define MAINMENU_LEN (sizeof(mainMenu) / sizeof(mainMenu[0]))

Because mainMenu is a global it's always available, and when you require the length you get the length of the global array.
If you want to keep things local you will have to pass the number of elements in the array as a parameter to the function that uses that information.
myFunction(mainMenu, MAINMENU_LEN);

Another common alternative is to have some "end of array" marker and you loop through your array until you find that marker (that's how strings work - with \0 for the end of array marker):
const char* mainMenu[] = {"FirstWord", "SecondWord", " ", 0};

Then:
for (int i = 0; m[i] != 0; i++) {
    ...
}


How to use Multipile millis() I've a exhaust fan that runs when the humidity is high. When the exhaust fan is on it should work for 3 minutes and should wait another 5 minutes to on. I am a beginner to this struggling for almost 2 days now. with this code the led just blink and off
int ledPin =  2;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis2 = 0;
unsigned long previousMillis = 0;
long interval = 10000;           // in
long OnTime = 1000;           // milliseconds of on-time
long OffTime = 2000;          // milliseconds of off-time

void setup()
{

  Serial.begin(9600);
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{

  unsigned long currentMillis2 = millis();

  if (currentMillis2 - previousMillis2 > interval) {
    // save the last time you blinked the LED

    // check to see if it's time to change the state of the LED
    Serial.print("hellohh ");
    unsigned long currentMillis = millis();

    if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      Serial.print("hellohh2 ");
      ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      Serial.print("hellohh 3");
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;
      previousMillis2 = 0; // Remember the time
      digitalWrite(ledPin, ledState);    // Update the actual LED

    }
  }
}

If I understand correctly, you wrote an example code that switches an
LED between two states (on and off), and you are stuck because the
actual problem you want to solve is more complex than that. And indeed,
it seems to me that you want to manage a system with three possible
states: it can be on or off but, when it is off, it can be ready to turn
on if the humidity is high, or it can be in the five minute wait.
The most natural way to think about this kind of systems is a finite
state machine, or FSM. An FSM is defined by the set of states it
can be in, the conditions that make it switch states, and the actions
performed when doing so. If I correctly understood your specification,
your system can be either READY, RUNNING or WAITING, and the transitions
are:

when READY, if the humidity is too high it switches to RUNNING; it
turns the fan on when doing so
when RUNNING, if it has been running for 3 minutes, it switches
to WAITING and turns the fan off
when WAITING, if it has been waiting for 5 minutes, it switches
to READY

This can be illustrated by the following state diagram:

You should correct me at this stage if I did not fully understand your
specification. Otherwise, if the state diagram matches your
requirements, converting it to code is quite straightforward:
const uint32_t MINUTE = 60000;

void loop() {
    static enum {READY, RUNNING, WAITING} state;
    static uint32_t last_change;
    uint32_t now = millis();
    switch (state) {
        case READY:
            if (humidity_is_high()) {
                turn_fan_on();
                state = RUNNING;
                last_change = now;
            }
            break;
        case RUNNING:
            if (now - last_change >= 3 * MINUTE) {
                turn_fan_off();
                state = WAITING;
                last_change = now;
            }
            break;
        case WAITING:
            if (now - last_change >= 5 * MINUTE) {
                state = READY;
            }
            break;
    }
}


How to Implement Simple, Quick HMAC on Arduino Hi I am a research student working on securing the communications in Controlled Area Networks (CANs), and I am using Arduinos to simulate one of these CANs.

My goal is to use HMAC to implement message authentication of packets, and the algorithm must be very fast (I was originally thinking of using FNV1a). However, there are no Arduino libraries for this (I found one, but it uses SHA which will most likely be too slow for CAN). I don't have a lot of practice with cryptography and hash algorithms, only usage of them.

So basically, I need help writing a FNV or FNV1a function in C. The message for input will be a key (obviously) concatenated with a string (char array). Also, I need the hash to be between 128 and 256 bits for sufficient security.

Just as a side note: A CAN message/packet looks like 7df#02010d and the actual data part, 010d (two bytes) is the char array I will be using. For example, as integers, the array for 010d would be {1, 13}.

--

I also know this message applies more to cryptography than Arduino, but I figured someone from this community might have more experience with my particular task, or even have/know of a library I can use that I hadn't found.

-Thanks

EDIT: I found this FNV1a implementation in C/C++ that might work. But I have not tested it yet.

I ended finding a Arduino library called Spritz which can be found here:
https://github.com/abderraouf-adjal/ArduinoSpritzCipher

Also, for anyone else who comes across this task, here is a very simple Hashed Message Authentication Code (HMAC) example I scrapped together:
https://github.com/zach-king/ArduinoStash/blob/master/src/Spritz_HMAC/Spritz_HMAC.ino

This library supports encryption as well, which is nice, but not needed in my case.

--EDIT--
The SpritzCipher library was actually too slow (about a 50% reduction in network speed) so I must try a different approach. I have found a MD5 library for Arduino which I will try next:
https://github.com/tzikis/ArduinoMD5


Uno pin connection: Atmega16u2 & ATmega328P On my Uno, I set up the HoodLoader2 (link below) so I can program both the ATMega16u2 and the ATmega328P. I can communicate between the two using the serial port. However, I need the serial port to communicate between the Uno and the PC. Can I communicate between the 328 and 16u2 using a common digital pin? All I need to communicate is a simple yes/no state, preferably in both directions. In other words: can I connect a digital pin (say 12) on the Uno to, say, PB1 pin on the 16u2's ICSP header, set pin 12 value to HIGH on the 328P, then read that state on the 16u2 via PB1? And vice versa, via another pair of pins? There's a Q that's close to what I want (link below) and the user there (@jsotola) seems to have the knowledge, but I can't comment under his comment, as I don't have 50 reputation.

HoodLoader2

Accessing digital pins from the ATMega16u2

You could use from PB1 to PB3 from 16u2 (SCK, MOSI, MISO) wich are exposed to its ICSP.
Add a wire from one of them to your atmega328 :)


split reading sensors values from stream after it via xbee I'm trying to make project to monitor my home. I am using some gas sensors and temperature and humidity sensors. I want to do this wirelessly and I think the
best thing to do that is XBee.

I use this code for the transmitter Arduino:

char dataPacket[64];

int gx = 1;
int gy = 321;
int gz = 456;
int ax = 654;
int ay = 789;
int az = 987;
int mx = 147;
int my = 258;
int mz = 369;

void setup(){

 Serial.begin(9600);

}

void loop(){

   sprintf(dataPacket, "X%d" ,gx);
    //  sprintf(dataPacket, "A%dB%dC%dD%dE%dF%dG%dH%dI%d", gx, gy, gz, ax, ay, az, mx,     my, mz);
Serial.println(dataPacket);

    }

gx gy gz .... these are the sensor reading variables

and in the receiving Arduino I use this code

void setup(){
    // Start up our serial port, we configured our XBEE devices for 9600 bps.
    Serial.begin(9600);
}

void loop()
{

    if(Serial.available() > 0)
{
     while(Serial.available() > 0)
 {
        char dataPacket[64];

for (int i = 0; i < 64; i++)
{
  dataPacket[i] = Serial.read();
 Serial.print(dataPacket[0]);

}

String show = Serial.readStringUntil('C') ;
delay(500);

}
}
}

but i can't split the values from the stream and put them into their variables (gx gy ...)

Does anyone have idea how to split it?

Try a communication protocol with a , as a delimiter like:

messageId,data1,data2,data3,....,dataN\n

And use the Messenger library to parse it.

See my answer on comms protocols here:

Communication Protocol Best Practices and Patterns

An how to use the Messenger library here:

Send Processing color data into Arduino


Combining code for two sensors in one programming We need to read two readings of Humidity and Temperature from 2 different locations. We can run each of them separately but we don't know how we can make them work simultaneously in one program. We are using a TH02 sensor that we connect to I2C and DHT11 that is connected to one of the Analog port.

We are connecting them to Grove base shield V2, which is on top of Arduino uno wifi.

TH02 Code:

 void setup()
{
Serial.begin(9600);        // start serial for output

Serial.println("****TH02_dev demo by seeed studio****\n");
/* Power up,delay 150ms,until voltage is stable */
delay(150);
/* Reset HP20x_dev */
TH02.begin();
delay(100);

/* Determine TH02_dev is available or not */
Serial.println("TH02_dev is available.\n");
}

void loop()
{
float temper = TH02.ReadTemperature();
Serial.println("Temperature: ");
Serial.print(temper);
Serial.println("C\r\n");

float humidity = TH02.ReadHumidity();
Serial.println("Humidity: ");
Serial.print(humidity);
Serial.println("%\r\n");
delay(1000);
}

DHT11 Code:

byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

    while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
    delayMicroseconds(30);

    if(PINC & _BV(DHT11_PIN))
    result |=(1<<(7-i));
    while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
}
return result;
}

void setup()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("Ready");
}

void loop()
{
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);
delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
    Serial.println("dht11 start condition 1 not met");
    return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
    Serial.println("dht11 start condition 2 not met");
    return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();

DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
    Serial.println("DHT11 checksum error");
}

Serial.print("Current humdity = ");
Serial.print(dht11_dat[0], DEC);
Serial.print(".");
Serial.print(dht11_dat[1], DEC);
Serial.print("%  ");
Serial.print("temperature = ");
Serial.print(dht11_dat[2], DEC);
Serial.print(".");
Serial.print(dht11_dat[3], DEC);
Serial.println("C  ");

delay(2000);
}

This example combines both codes but uses a single delay. If you want readings at two different times you should use two unsigned long global variables to store the millis() of the last time the functions were called. Then you use an if statement to only call readTH02() or readDHT11() when the last millis is less than the <= current-interval.

It is better to use millis interval checking instead of delays but I have not made significant changes to your code to implement that. Take a look at the Arduino IDE example called BlinkWithoutDelay to understand how to use intervals instead of delay()

void setup()
{
  setupTH02();
  setupDHT11();
}

void loop()
{
  readTH02();
  readDHT11();

  delay(1000);
}

void setupTH02()
{
Serial.begin(9600);        // start serial for output

Serial.println("****TH02_dev demo by seeed studio****\n");
/* Power up,delay 150ms,until voltage is stable */
delay(150);
/* Reset HP20x_dev */
TH02.begin();
delay(100);

/* Determine TH02_dev is available or not */
Serial.println("TH02_dev is available.\n");
}

void readTH02()
{
float temper = TH02.ReadTemperature();
Serial.println("Temperature: ");
Serial.print(temper);
Serial.println("C\r\n");

float humidity = TH02.ReadHumidity();
Serial.println("Humidity: ");
Serial.print(humidity);
Serial.println("%\r\n");
//delay(1000);
}

byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

    while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
    delayMicroseconds(30);

    if(PINC & _BV(DHT11_PIN))
    result |=(1<<(7-i));
    while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
}
return result;
}

void setupDHT11()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("Ready");
}

void readDHT11()
{
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);
delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
    Serial.println("dht11 start condition 1 not met");
    return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
    Serial.println("dht11 start condition 2 not met");
    return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();

DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
    Serial.println("DHT11 checksum error");
}

Serial.print("Current humdity = ");
Serial.print(dht11_dat[0], DEC);
Serial.print(".");
Serial.print(dht11_dat[1], DEC);
Serial.print("%  ");
Serial.print("temperature = ");
Serial.print(dht11_dat[2], DEC);
Serial.print(".");
Serial.print(dht11_dat[3], DEC);
Serial.println("C  ");

//delay(2000);
}


What is the best type of Arduino board for simple delivery robot? I'm new to arduino, and I want to design a Simple Delivery Robot for Data Center, which has an arm to move items, and it follows line while moving.

I have no idea if there is a special arduino board for these types of robot or I can buy any arduino board.

ANWSER

I would suggest you to use the Arduino UNO for all the shields that it has. Most Arduinos are so similar that it wont make a difference but the UNO has many shields to it, including a motor/servo shield which is going to be great for your project.

But at the end of the day, it's your project and you can pretty much use any of the boards listed below. They are just advantages and disadvantages of many popular board. Hope it helped you!

The summary has been removed for the sake of respecting Stack Exchanges rules.


Motor Shield not giving full power, LED DIMS I have an Adafruit Motor Shield, the V1. I have been using this thing with my OPSEPP Uno and a stepper motor with no issues. (Powered by 12v DC wall wart [CASIO]).

My question, or issue, not sure yet, is this:

Why when I connect my motor directly to the 12v power supply it operates efficiently (for my purposes) and when I run it through my Arduino with the Adafruit Motor.h library does it not power the same.

Basically on direct connection it works fine, but I want to be able to regulate the connection and reverse it, change the speed, etc.

It is possible I am utilizing the library or the board wrong.

Can someone indicate why the power or, torque seems to drop when through the board. I have tried all KHZ all speeds etc, no way to get the same 12v power directly and modulate it?

According to the Adafruit page the V1 version of the shield is not as powerful as their V2 version.

Where is the 12V coming from to get to the shield? There isn't really 12V broken out on the Uno anywhere. If it comes from Vin then there is a 0.7V drop through the reverse polarity protection diode. Plus, the tracks on the Arduino board may not be thick enough to provide enough current.

It looks like the shield may take an external power source (it is hard to tell because they discontinued it). You could try using that.


Writing "theremin" outputs to a MIDI file on an SD card I am making a musical instrument (theremin simulator). I want there to be a "record" capability which stores the volume and note the user is playing, into a MIDI file. Note this doesn't actually record audio, just data for the frequency and volume at a certain point in time.

So far I've done some research and have found how to play MIDI files (which is useful and I plan to take this on as well) and read/write to SD cards. However I haven't found a source which allows me to create and produce MIDI files.

How should I accomplish this feature?

Specs:

I am using an Arduino Nano, I have an Uno too if needed
The SD card is a 64GB micro SD, inserted into an SD adapter, with header pins soldered onto it. (I am too cheap to buy an actual shield)
It was previously XCSD, I formatted it to FAT32 to be compatible with Arduino

Also: I am recording from a self built replica of a theremin, which is basically two ultrasonic sensor readings for volume and pitch. Is this "too basic" for a MIDI file type? (Edit: I guess this is too advanced)

EDIT: This project has been abandoned because of no good way to play between semitones (i.e. at specific frequencies), which is what I need for my theremin. Although there is the pitch bend functionality, the amount of pitch bend translates to different frequency changes based on the receiver.

Instead, I will create my own custom file to achieve the record/playback, because using the pitch bend + note method using MIDI is just too much work and it won't be compatible with other devices anyway.

Nick Gammon's answer is really thorough for those who only need to record/play specific tones and semitones in MIDI format.

Thanks

The short answer would be "yes, it is possible". There are lots of gadgets around that record MIDI. They would have microprocessors in them, and they would have something like an SD card, which itself is like EEPROM in concept.
You may possibly have problems with storing the notes in RAM, and then writing them to the SD card fast enough not to lose some. Knowing the rate at which notes would arrive, the speed of the SD card, and the type of Arduino would help to answer if your specific case was likely to work.
I wrote a sketch that reads MIDI which shows that it is certainly possible to receive MIDI data and display it. Video of it running is here.
I don't personally know the format of MIDI files, but it is well documented.
(Edit) I do now - see further down.
Writing to SD cards is well documented. Making your idea work would be a case of taking stuff (like my code to decode MIDI), code to write to SD cards, and knowing the correct format.

(Edited to add)
See Standard MIDI-File Format Spec. 1.1 for an example of producing MIDI data. Also see The MIDI File Format and the Standard MIDI File (SMF) Format
Your basic technique would need to be (as suggested by gabonator):

Write a header chunk to the file, for example:
  4D 54 68 64   // MThd
  00 00 00 06   // chunk length
  00 00         // format 0
  00 01         // one track
  00 60         // 96 pulses per quarter-note

Write a track chunk to the file (the length will be updated later)
  4D 54 72 6B   // MTrk
  00 00 00 00   // <-- length to be updated later

Write instrument configurations (with time delta values of zero), as an example from that page:
  00  FF 58 04  04 02 18 08  // 4 bytes; 4/4 time; 24 MIDI clocks/click,
                             // 8 32nd notes/ 24 MIDI clocks
                             // (24 MIDI clocks = 1 crotchet = 1 beat)
  00  FF 51 03  07 A1 20     // 3 bytes: 500,000 µsec/ quarter note
                             // = 120 beats/minute (500000 in hex is 0x07A120)
  00  C0 05                  // Ch.1 Program Change 5 = GM
                             // Patch 6 = Electric Piano 2

When the player plays something, subtract the time that s/he last did something from the time now. This will give you the delta time.

Convert the time difference to ticks. From the header line above we have 96 pulses per quarter note (PPQ), and 500,000 µs (500 ms) per quarter note. Thus one second would be two quarter notes (2 beats per second, and therefore 120 beats per minute) and one second is therefore 192 ticks). Therefore the number of ticks, based on the time difference in milliseconds, would be:
  unsigned long ticks = (time_difference * 192) / 1000

Output the delta time as a variable length number, where the high order bit is set for each byte, as necessary, until what is left is <= 0x7F. The page above gives sample code for that. For example, for a delta time of 199 ticks:
  Decimal time of 199 ticks -> 0xC7
  0xC7 -> 0b11000111
  Since that exceeds 127, split into two bytes:

  10000001  (the high order bits)
   ^^^^^^^  <- high order bits (the MSB must be one)
  01000111  (the low-order 7 bits)
   ^^^^^^^  <- low order bits (the MSB must be zero)

  Result is 0x81 0x47

Longer times may require even more bytes.
Something like this should do it (adapted from the linked page). Just change the Serial.write line to output to your disk file.
  void WriteVarLen (unsigned long value)
    {
    unsigned long buffer;

    buffer = value & 0x7f;
    while ((value >>= 7) > 0)
      {
      buffer <<= 8;
      buffer |= 0x80;
      buffer |= value & 0x7f;
      }

    while (true)
      {
      Serial.write (buffer & 0xFF);
      if (buffer & 0x80)
        buffer >>= 8;
      else
        break;
      }
    }   // end of WriteVarLen

Follow the delta time immediately by the "note on" or "note off" byte (depending on whether they started or stopped playing a note). For example, "note on" for channel 1 would be 0x90 because 0x9n is a note on command and n is the channel number, zero relative. A "note off" for channel 1 would be 0x80.

Follow the "note on" or "note off" by the note number (in other words, which note was just played or released) - one byte.
  Octave #  Note Numbers in decimal
            C   C#  D   D#  E   F   F#  G   G#  A   A#  B
  -1         0   1   2   3   4   5   6   7   8   9  10  11
  0         12  13  14  15  16  17  18  19  20  21  22  23
  1         24  25  26  27  28  29  30  31  32  33  34  35
  2         36  37  38  39  40  41  42  43  44  45  46  47
  3         48  49  50  51  52  53  54  55  56  57  58  59
  4         60  61  62  63  64  65  66  67  68  69  70  71
  5         72  73  74  75  76  77  78  79  80  81  82  83
  6         84  85  86  87  88  89  90  91  92  93  94  95
  7         96  97  98  99 100 101 102 103 104 105 106 107
  8        108 109 110 111 112 113 114 115 116 117 118 119
  9        120 121 122 123 124 125 126 127

Typically middle C is considered to be C4 (C in the 4th octave), however apparently that can vary between devices.

Then output the velocity (one byte). A velocity of (decimal) 32 would be soft, 64 would be medium, 96 would be loud. The range for velocities is 0 to 127.

Repeat the above (except for writing the chunks and the configuration) until the player decides to stop playing.

Write an "end of track" marker:
  00  FF 2F 00    // Delta time zero, end of track

Then seek back to the start of the file + where the length bytes are (18 bytes into the file by the looks of it) and update the length bytes (4 bytes).

Example of producing a MIDI file
This example code writes out a MIDI file. As an input device I used a 16-key keypad like this:

The columns were connected to pins 0, 1, 2, 3 of the Arduino Uno, and the rows to pins 4, 5, 6, 7. This makes the ribbon cable from the keypad keep the pins in a natural order. If you use different pins just change the keys array in the sketch.
The library for keypads that I used is available at https://github.com/nickgammon/Keypad_Matrix
This particular library supports n-key rollover and key-down and key-up events. That is particularly useful for music, because it lets you hold multiple keys down at once, and the appropriate events will be generated. Obviously you need a key-down event to generate "note on" and a key-up event to generate "note-off".
I laid out the keys like this:
C     C#    D     D#
E     F     F#    G
G#    A     A#    B
Down  Soft  Up    Record

There is a "recording" LED connected to A0 which lights up when you start recording (by pressing the Record button).

Press the Record button again to stop recording and finalize the file. It is important to stop recording properly and not just power off the device, because the length of the file needs to be written near the start.

Press (and hold) Down alongside with another note to play an octave lower. Press (and hold) Up alongside with another note to play an octave higher.

Press (and hold) Soft alongside with another note to play at a softer velocity.

Using a keypad matrix is logical, because most keyboard devices would use a matrix, to reduce the number of wires you have to run.
Note that the matrix needs diodes wired for each switch as described here because otherwise if you press 3 or more keys at once you will get "ghost" keys.
In my case I opened up the commercial keypad and soldered in the diodes.

I also used a Micro-SD breakout adapter, connected to the SPI pins of the Arduino, like this:

The SDFat library was an archived one that I keep here: http://gammon.com.au/Arduino/SdFat-master.zip (2.2 Mb)
Unzip that file, and from within the folders inside it, copy the SdFat folder into your "libraries" folder (which is under your Arduino sketchbook folder - not inside the Arduino application folder). Then restart the Arduino IDE.
The code definitely compiles with that (with a handful of warnings). The later library from https://github.com/greiman/SdFat may be an improvement but I haven't tested that.

To keep track of file numbers I used the EEPROMAnything library, a copy of which can be found at http://gammon.com.au/Arduino/EEPROMAnything.zip
Each time you start a new recording it adds one to the file number, which wraps around to 0000 once it reaches 9999.

If there is an error initializing the file system (eg. no SD card) then the LED blinks slowly. If the file can't be created the LED blinks rapidly.

You can choose a MIDI instrument by changing the line:
const byte PATCH_NUMBER = 4;   // electric piano 1

Code
/*
 Sketch to write to a MIDI file from an instrument.
 Author: Nick Gammon
 Date:   10th May 2018

 Copyright 2018 Nick Gammon.

 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

*/

#include <Keypad_Matrix.h>
#include <SdFat.h>
#include <EEPROM.h>
#include <EEPROMAnything.h>

// For MIDI numbers see: http://www.pjb.com.au/muscript/gm.html
const byte PATCH_NUMBER = 4;   // electric piano 1

const byte RECORDING_LED = A0;

// bottom row changes things
const char DOWN_OCTAVE  = '-';
const char SOFT         = 's';
const char UP_OCTAVE    = '+';
const char RECORD       = 'r';

// how the keypad has its keys laid out
// capital letters are for sharps
const byte ROWS = 4;
const byte COLS = 4;
const char keys[ROWS][COLS] = {
  {'c', 'C', 'd', 'D'},
  {'e', 'f', 'F', 'g'},
  {'G', 'a', 'A', 'b'},
  {DOWN_OCTAVE, SOFT, UP_OCTAVE, RECORD},  // - = down octave, s = soft, + = up octave, r = start/stop record
};

const byte colPins[COLS] = {0, 1, 2, 3}; //connect to the column pinouts of the keypad
const byte rowPins[ROWS] = {4, 5, 6, 7}; //connect to the row pinouts of the keypad

// Create the Keypad
Keypad_Matrix kpd = Keypad_Matrix( makeKeymap (keys), rowPins, colPins, ROWS, COLS );

// file system object
SdFat sd;
const byte chipSelect = SS;

// the current file we are recording to
SdFile myFile;
// are we recording right now?
bool recording = false;

const byte MIDI_META_EVENT = 0xFF;
const byte MIDI_SET_TEMPO  = 0x51;
const byte MIDI_TIME_SIGNATURE = 0x58;
const byte MIDI_END_OF_TRACK = 0x2F;
const byte MIDI_PROGRAM_CHANGE = 0xC0;
const byte MIDI_NOTE_ON = 0x90;   // channel 1
const byte MIDI_NOTE_OFF = 0x80;  // channel 1

struct
  {
  char magic [4]; // MThd
  uint32_t length;
  uint16_t format;
  uint16_t tracks;
  uint16_t PPQ;    // pulses per quarter note
  } chunkHeader;

struct
  {
  char magic [4]; // MTrk
  uint32_t length;
  } trackHeader;

unsigned long trackHeaderPosition;
unsigned long timeLastAction;
int           nextFileNumber;

uint32_t changeEndianness32(uint32_t val)
{
  return (val << 24) |
        ((val <<  8) & 0x00ff0000) |
        ((val >>  8) & 0x0000ff00) |
        ((val >> 24) & 0x000000ff);
} // end of changeEndianness32

uint16_t changeEndianness16(uint16_t val)
{
  return (val << 8) | ((val >> 8) & 0x00ff);
} // end of changeEndianness16

void showError (const int delayTime)
  {
  while (true)
    {
    digitalWrite (RECORDING_LED, HIGH);
    delay (delayTime);
    digitalWrite (RECORDING_LED, LOW);
    delay (delayTime);
    }

  } // end of showError

void startRecording ()
  {
  EEPROM_readAnything (0, nextFileNumber);
  if (nextFileNumber > 9999 || nextFileNumber < 0)
    nextFileNumber = 0;

  char name[15];
  sprintf (name, "SONG%04d.MID", nextFileNumber++);

  // open the file for writing
  if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
    showError (100);  // fast flash - never returns

  // update EEPROM for next time
  EEPROM_writeAnything (0, nextFileNumber);

  recording = true;
  digitalWrite (RECORDING_LED, HIGH);
  memcpy (chunkHeader.magic, "MThd", sizeof (chunkHeader.magic));
  chunkHeader.length = changeEndianness32 (
                       sizeof (chunkHeader.format) +
                       sizeof (chunkHeader.tracks) +
                       sizeof (chunkHeader.PPQ));

  chunkHeader.format = changeEndianness16 (0);
  chunkHeader.tracks = changeEndianness16 (1);
  chunkHeader.PPQ = changeEndianness16 (96);
  myFile.write (&chunkHeader, sizeof (chunkHeader));
  memcpy (trackHeader.magic, "MTrk", sizeof (trackHeader.magic));
  trackHeader.length = 0;   // to be filled in later
  trackHeaderPosition = myFile.curPosition ();
  myFile.write (&trackHeader, sizeof (trackHeader));

  struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_TIME_SIGNATURE };
    byte length = 4;
    byte sig [2] = { 4, 2 };  // 4/4 time (denominator of 2 is 2^2)
    byte clocksPerClick = 24;  // MIDI clocks/click
    byte clocksPerBeat  = 8;
    }  timeSignature;

 struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_SET_TEMPO };
    byte length = 3;
    byte usPerQuarterNote [3] = { 0x07, 0xA1, 0x20 };  // that is: 500000 µs per beat
    }  tempo;

 struct
    {
    byte deltaTime = 0;
    byte message =   MIDI_PROGRAM_CHANGE;
    byte patchNumber = PATCH_NUMBER;
    }  programChange;

  myFile.write (&timeSignature, sizeof timeSignature);
  myFile.write (&tempo, sizeof tempo);
  myFile.write (&programChange, sizeof programChange);
  timeLastAction = millis ();
  } // end of startRecording

void stopRecording ()
  {
  struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_END_OF_TRACK };
    byte length = 0;
    }  endOfTrack;

  // write out "end of track" message
  myFile.write (&endOfTrack, sizeof endOfTrack);
  // find where we are
  unsigned long finalPosition = myFile.curPosition ();
  // go back to where the track header is
  myFile.seekSet (trackHeaderPosition);
  // work out how long the data was (excluding the headers)
  trackHeader.length = changeEndianness32 (finalPosition - trackHeaderPosition - sizeof (trackHeader));
  // update the file length
  myFile.write (&trackHeader, sizeof (trackHeader));

  myFile.close ();
  // ensure flushed to disk
  myFile.SdBaseFile::sync();

  // no longer recording, turn off recording LED
  recording = false;
  digitalWrite (RECORDING_LED, LOW);
  } // end of stopRecording

void writeVarLen(unsigned long value)
{
  unsigned long buffer;

  buffer = value & 0x7f;
  while ((value >>= 7) > 0)
  {
    buffer <<= 8;
    buffer |= 0x80;
    buffer |= value & 0x7f;
  } // end of while

  while (true)
  {
    myFile.write ((byte) (buffer & 0xFF));
    if (buffer & 0x80)
      buffer >>= 8;
    else
      break;
  } // end of while

}   // end of writeVarLen

// turn the keypad code into a note number
byte codeToNote (const char which)
{
  char notes [] = "cCdDefFgGaAb";
  char * pos = strchr (notes, which);
  if (pos == NULL)
    return 0;
  return pos - notes + 60;  // start at middle C (C4)
} // end of codeToNote

// do a note on or note off
void doNoteAction (const char which, const byte action)
{
  // we need to work out how many milliseconds have elapsed
  unsigned long now = millis ();
  unsigned long deltaTime = now - timeLastAction;
  // remember when we did this
  timeLastAction = now;
  // write out the delta time
  writeVarLen ((deltaTime * 192) / 1000);

  // note information
  struct
    {
    byte noteOn;
    byte whichNote;
    byte velocity;
    } playNote;

  playNote.noteOn = action;
  playNote.whichNote = codeToNote (which);
  if (kpd.isKeyDown (DOWN_OCTAVE))
    playNote.whichNote -= 12;  // one octave down
  else if (kpd.isKeyDown (UP_OCTAVE))
    playNote.whichNote += 12;  // one octave up

  playNote.velocity = 64;      // medium velocity
  if (kpd.isKeyDown (SOFT))
    playNote.velocity = 32;    // softer

  myFile.write (&playNote, sizeof (playNote));
} // end of doNoteAction

void startPlaying (const char which)
  {
  doNoteAction (which, MIDI_NOTE_ON);
  } // end of startPlaying

void stopPlaying (const char which)
  {
  doNoteAction (which, MIDI_NOTE_OFF);
  } // end of stopPlaying

void keyDown (const char which)
  {
  switch (which)
    {
    case 'c':
    case 'C':
    case 'd':
    case 'D':
    case 'e':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case 'a':
    case 'A':
    case 'b':
      startPlaying (which);
      break;

    default:
      break;
    } // end of switch on which key
  } // end of keyDown

void keyUp (const char which)
  {
  switch (which)
    {
    case RECORD:
      if (recording)
        stopRecording ();
      else
        startRecording ();
      break;

    case 'c':
    case 'C':
    case 'd':
    case 'D':
    case 'e':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case 'a':
    case 'A':
    case 'b':
      stopPlaying (which);
      break;

    default:
      break;
    } // end of switch on which key
  } // end of keyUp

void setup()
{
  kpd.begin ();
  kpd.setKeyDownHandler (keyDown);
  kpd.setKeyUpHandler   (keyUp);
  pinMode (RECORDING_LED, OUTPUT);

  if (!sd.begin (chipSelect, SPI_HALF_SPEED))
     showError (500);  // never returns

} // end of setup

void loop()
{
  kpd.scan ();
} // end of loop

I am recording from a self built replica of a theremin, which is basically two ultrasonic sensor readings for volume and pitch. Is this "too basic" for a MIDI file type?

It looks like this could be possible by using the MIDI "pitch bend" message. You would need to determine where your note value was (presumably most of the time between the natural notes like C and C#) and then send a bend message or "Pitch Wheel Change" (0xE0 for channel 1) to modify the main note. The main note would need to be updated if you moved more than a couple of semitones away.
See:

https://en.wikipedia.org/wiki/Pitch_wheel
http://sites.uci.edu/camp2014/2014/04/30/managing-midi-pitchbend-messages/


ATTiny85 Serial communication with Bluetooth Module For a simple project I would like to use a ATTiny85 connected to a HC-06 Bluetooth Module so it can talk to my Android phone.
I wrote a code for my Arduino Uno and worked as expected. When I changed the code to use on my ATTiny85 I got an error saying that 'Serial' was not declared in this scope and assumed that the ATTiny does not support Hardware Serial.
I need to read a String when received and sleep the MCU when not receiving. I went to use SoftwareSerial and was not able to get a String, just the first char.
I approached it in some was, like defining a char string[10]; as global and string[i] = mySerial.read(); i++; inside the loop, but it keeps not working. Whether it is the sleep, or my work to read data, I couldn't make it work.
Can someone provide a way to put a ATTiny85 to sleep, wake up to receive a String through Serial and sleep til the next data through Serial, please?

To sleep I'm using

void sleep() {
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  // woke up
  cli();                                  // Disable interrupts
  PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear Sleep Enable bit

  sei();                                  // Enable interrupts
}

ISR(PCINT3_vect) {

}

And my loop is something like

char inputString[10];
int i = 0;

void loop() {
  sleep();

  if (serial.available() > 0) {
    char inputChar = serial.read();
    if (inputChar == '2') {    //Char to break
      //Do something and reset i
    } else {
      inputString[i] = inputChar;
    }
    i++;
  }
}

Thanks to all.

Hello,

I think you should do this:

char inputChar = '';    //this in global
while (serial.available()) {
    inputChar = serial.read();
    if (inputChar == '2') {    //Char to break
        //Do something and reset i
    } else {
        inputString[i] += inputChar;    //= to +=
    }
    i++;
}


How do I connect a LED strip to a Multiwii SE 2.5? https://www.m.nu/neopixel/mini-skinny-neopixel-digital-rgb-led-strip-60-led-m-black-pcb-1m

I just purchased this led-strip that I plan to use with my Multiwii SE 2.5.

I power the Multiwii itself via a power distribution board where I connect a 3s LiPo battery. Now I wonder how I would wire my LED strip in order to use it with my Multiwii. I have a few smaller LiPo batteries if I need to power the LED itself (not via the 3s LiPo that powers the Multiwii) but the best solution would of course be to power them together.

I appreciate all help I can get.

The led strips I've used with my Naze32 have three connection, +5VDC, GND and DATA. I'm not familiar with your FC but based on the image you provided it looks like you would use one of the two I2C ports. As long as you don't try to run too many LEDs (I've maxed out my FC with 32 LEDs no problem) the +5VDC connection should be able to power the LEDs. Obviously connect LED GND to the FC GND. You'll need to check the docs for you FC to confirm but it would make the most sense to me to connect the FC SDA to the LED DATA. The FC SCL would not be used.

NOTE: If your PDB has a +5VDC output you'd be better off using that one to power the LEDs.

In the picture with the Arduino one of the leads is providing +5VDC. I've read the suggestion for LED strips to place a capacitor across the +5VDC and GND to make it more stable but I don't and I've not had any issues. FYI, the lead to the Arduino is for GND and DATA (being driven by one of the Arduino Digital I/O Pins.


Simple memory chip for Arduino? My basic question is: What is a good alternative to EEPROM chips for external memory on the Arduino Unor R3?

I know that there are EEPROM chips when one would like an external memory chip. It, in fact, seems like this is the standard choice. I am wondering if there are any other good ways to work with external memory. Are there, for example, memory chips that work a bis simpler? Like, a chip that doesn't require any specific libraries in the Arduino?

(I do not have extensive experience working with the Arduino.)

There is no DRAM, SRAM nor flash interface in ATmega, so you can't extend your chip memory. You can only connect serial (SPI, I2C) or parallel memory (usind GPIO).

Neither SPI nor I2C require any specific libraries.
SPI is much simpler to program than I2C and much faster, but require more wires.

Instead of using rather slow EEPROM, you can try FRAM (non-volatile) or SRAM (volatile, but may be battery-sustained). They are usually available with the same interface as EEPROM, but don't suffer from limited number of erase cycles. FRAM can withstand ridiculous number of erasures, SRAM is virtually indestructible.


how to switch more 230v with arduino? i am working on a project automatic street lighting with arduino.i am done with the code and the circuit.i am able to switch the AC voltage in my house which is 230v,50hz with a 230v relay but when its comes to implementation there are 30 to 40 street lights are connected and the voltage is very high I think around 415 volts.what should I use to control that? need help

You have to use a relay that can handle minimum 415 volts (and keep some reserve).

Also take the current/amperage into account (possibly use multiple relays).


What is the maximum prescaler you can set for an ATtiny85 Timer Interrupt? I'm having trouble understanding the datasheets for the ATtiny and I need to know what is the largest prescaler that can be set for an ATtiny Timer Interupt? I'm new to hardware so can someone tell me if this is correct:

void setupInterupt()
{
  noInterrupts();
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = PERIOD - 1;
  TIMSK2 = _BV(OCIE2A);
  TCCR2B |= _BV(CS13) | _BV(CS12) | _BV(CS12) | _BV(CS10);
  interrupts();
}

Will this set a prescaler of 16384? Am I understanding the chart on page 89 correctly and is my syntax okay? This is my first Arduino Project.

I don't know the objectives of your project, or its constraints and requirements.  Thus, portions of the following might not apply.

If I were using an ATtiny85 in an application that needed to “maximize the amount of power saved” and also needed to wake up about every 33 ms, I'd use the factory-calibrated 8 MHz clock (rather than attaching a 20 MHz external crystal), and use system clock prescaling [see §6.3, System Clock Prescaler, on page 31 of the ATtiny85 specs, and Table 6-15. Clock Prescaler Select, p. 33] to scale that 8 MHz down to 250 KHz.  As implied by Table 21-1, DC Characteristics, page 162 of specs, this will drop CPU current draw down to under 0.1 mA if powered by 2 V, or under 0.35 mA if powered by 3 V.

With the system clock running at 250 KHz, you can use timer 0 prescaled by a factor of 1024 [see §11.3.1, Internal Clock Source with Prescaler, p. 166 of specs] to get an interrupt every 33 ms or so.

If 250 KHz is too slow to get done with whatever computation needs to be done every 33 ms, upon waking I would change the system clock prescale factor per §6.3.1, Switching Time, to 8 MHz or 4 MHz or whatever it needs to be to get the computation done at lowest power cost.  That might or might not be the same as getting the computation done most quickly.

Then, after the periodic computation is done, I'd revert the system clock to 250 KHz, and go to sleep in Idle mode (Ref §7.1.1, Idle Mode) with almost everything except timer 0 shut down via the PRR. (Ref §7.3, Power Reduction Register.)


Where should a modified "pins_arduino.h" be stored for Arduino IDE compile? Our PCB uses an ATmega2560 chip and uses most of the pins, including some that are not defined in the standard pins_arduino.h module, since that module only provides for the pins that are brought out to headers on the Arduino Mega2560 PCB.

We have a modified pins_arduino.h module that has all pins defined, but it doesn't get included in the Arduino IDE compile.  It was cataloged in the same directory as the standard module (that we renamed original).  The path where the modified module is stored is C:/Arduino/hardware/arduino/avr/variants/mega, where the original was also located.

In the sketch, we added #include "pins_arduino.h" as well as #include <pins_arduino.h>, but neither seemed to have included the modified module, so the extra pins are not accessible.  Putting the module in the same library as the sketch didn't help either.

Any suggestions?

Now have 2560 “full pin definition” working.  This is what I think I did:

1) Download IDE with "Windows ZIP file for non admin install " from https://www.arduino.cc/en/Main/Software

2) Download pins.arduino.h from https://forum.arduino.cc/index.php?action=dlattach;topic=200887.0;attach=60348

3) Open the IDE distribution zip file and extract all files into the location where you want the IDE files and your sketches to reside.  Could be anywhere.

4) Before starting arduino.exe from the extracted files, replace the pins.arduino.h file that came with the IDE, with the "all pins defined" version.  It is replaced in folder path: .../arduino-1.8.5/hardware/arduino/avr/variants/mega/pins.arduino.h

5) Place sketch within the same path as everything else (e.g. create a folder like “12.My_Sketches” inside “examples”). For example, I put my test sketch Blinky-2560 in folder path: .../arduino-1.8.5/examples/12.My_Sketches/Blinky-2560/Blinky-2560.ino

Why it worked this time?  The only difference I can see is I got the new pins file inserted in the right place before running the IDE.  It is also possible the sketch has to be in the same path as the rest of the IDE (saw that somewhere!?!?).  Otherwise I don’t think there was anything else different from what I was doing with the previously installed IDE.

Since the “all pins defined” file is a superset of the standard mega pins.arduino.h file, there is full compatibility with the Arduino ATmega2560 PCB.  It would be great if Arduino would make this fully defined pins file the standard that comes with the IDE.

Never did get MegaCore to upload the sketch after the compile.


433 MHZ connection between two Arduino (nano,uno) fails after some time The goal of this part of my project is to establish a wireless connection between an Arduino nano and an Arduino uno. For this I use 433 MHZ receiver and sender. The nano sends, the uno receives and prints. I have working code and the connection works and I can send, receive and print my message.
But at some point the Uno receives just a part of the message and after this point always receives (or prints) just this part of the message:

Nano (sender):

#include <VirtualWire.h>
char *msg = "123456789123456789";

It is not always 2 digits, sometimes more are received.

I searched for errors. The nano is constantly sending and the uno flips to not receiving the whole message. So I reupload the code to the uno without modification and it works again for a few seconds/minutes, so I guess it's a problem at the receiving end.

Here is my code:

Sender(nano):

#include <VirtualWire.h>
char *msg = "123456789123456789"

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

 pinMode(7,OUTPUT);
 pinMode(5,OUTPUT);
 digitalWrite(5,LOW); //GND
 pinMode(6,OUTPUT)
 digitalWrite(6,HIGH); //5V
 vw_setup(5000);
 vw_set_tx_pin(7);
}

void loop()     {
 vw_send((uint8_t*)msg, strlen(msg));
 vw_wait_tx();
 delay(500);
}

Receiver(Uno):

#include <VirtualWire.h>

int i;
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

void setup() {

 Serial.begin(9600);
 pinMode(5,INPUT);
 pinMode(6,INPUT); // two data inputs, we use just one
 pinMode(7,OUTPUT);
 digitalWrite(7,LOW); //GND
 pinMode(4,OUTPUT);
 digitalWrite(4,HIGH); // 5V VCC
 vw_setup(5000);
 vw_set_rx_pin(6);
 vw_rx_start();
 Serial.println("Starting up");

}

void loop() {

 if(vw_get_message(buf,&buflen)) {
   for(i=0;i<buflen; i++) {
    Serial.print((char)buf[i]);
   }
 }
}

It doesn't happen after a certain time or number of messages. I have no clue what could be the problem.

Thanks in advance,
Niklas

Edit: Problem seems solved. Changing bitrate from 5000 to 2000 solved the problem, but I don't actually know why.

Regarding the hardware problem, there are some advices in the comments.
As you wrote, the solution is to reduce the bitrate at 2000 bps.

The remaining question is why the receiver always truncates the message (after a receiving error occurs). The answer is in the definition of the buflen parameter of the vw_get_message function. The page https://www.pjrc.com/teensy/td_libs_VirtualWire.html says:

  "buflen" should have the array's maximum size upon input, and upon return the number of bytes actually copied is retured.

Therefore, when a transmission error occurs, the buflen variable returns a smaller number to inform you how many characters are received. If you do not reset the buflen variable to VW_MAX_MESSAGE_LEN before calling vw_get_message again, you are telling the library that you expect a smaller number of characters and the function respects that size (thinking that you have a smaller buffer).

In other words, if you want try to receive the full message after a transmission error occured, set the buflen variable to VW_MAX_MESSAGE_LEN before each call of the vw_get_message function.


Is it possible to use the same power source for the arduino and a high current I've need to control some leds which draw 300mA with an arduino (actually an atmega) and after some searching I think the following is the circuit I need, but I'm not really sure if the power source for the LEDs can be the same as for the arduino.
R1 = 1k

If the power supply has sufficient power and voltage stability, you can use it to power the LED and Arduino. However, the circuit is not entirely correct on the LED side, a current limiting resistor should be used in series with the LED. I would also recommend using a more powerful bipolar transistor or field effect transistor.


Fail to retrieve the value from gsm sim 900A by using AT Command to PHP script I am currently trying to establish a connection between my gsm sim900A to one of my test server. The connection seems pretty good so far, though I'm a little bit confused why there are no values retrieved by my php file. Even so, the insert query works although it insert empty value into the database. So my question is how to retrieve it properly? I already change the method in php script to POST, both of it doesn't return any good signs.

Arduino Code:

void postData()
{
  sim900a.println("AT+HTTPINIT");
  delay(1000);
  printSerialData();

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

  sim900a.println("AT+HTTPPARA=\"URL\",\"test.my/demo/writedata.php\"");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPDATA=12,10000");
  delay(1000);
  printSerialData();

  sim900a.println("strBoton=999");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPACTION=1");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPREAD");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPTERM");
  delay(1000);
  printSerialData();
}

PHP Code:

<?php
$servername = "test.my";
$username = "****";
$password = "****";
$dbname = "test";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$Boton = $_GET["strBoton"];

$sql = "INSERT INTO test VALUES ('$Boton')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Output:

AT+HTTPINIT
OK

AT+HTTPPARA="CID",1
OK

AT+HTTPPARA="URL","test.my/demo/writedata.php"
OK

AT+HTTPDATA=12,10000
DOWNLOAD
OK

AT+HTTPACTION=1
OK

AT+HTTPREAD
OK

AT+HTTPTERM
+CME ERROR: operation not allowed

AT+SAPBR=0,1
OK

I am not sure but, in this tutorial at page 8, it does almost the same code pattern like yours. You might want to check it. Sorry but I don't know PHP, I can't help you with it.

But I am confused with AT+HTTPACTION, since AT+HTTPACTION=0 is the read and AT+HTTPACTION=1 is the post. Check the tutorial and optimize your commands.

Also check this one. It writes WAIT=6 after AT+HTTPREAD before terminating it.


data type error on sensor data to ethernet client I'm having a hard time debugging this piece of code, and i'm hoping someone can point out where i am making the mistake.

My serial output is:

connected
GetData()
got data...
next stage...

I've tested with a simple network client that loops sending a hello world, and it works fine. Every time this code halts after attempting to send a value to the client. I know that  getData() is causing the issue, but i cannot work out why, or how to best resolve it.
(apologies for the code dump, i want to be thorough)

#include <LiquidCrystal.h>
#include <dht11.h>
#include <SPI.h>
#include <Ethernet.h>
dht11 DHT11;
#define DHT11PIN 8

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server(192,168,1,100);
IPAddress ip(192,168,1,50);
EthernetClient client;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int trigPin = 6;
const int echoPinOne = 7;
const int echoPinTwo = 8;
const int echoPinThree = 9;
const int echoPinFour = 10;

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
  delay(1000);

  //Network
 if (Ethernet.begin(mac) == 0) {
    Serial.println("DHCP FAIL");
    Ethernet.begin(mac, ip);
  }
  delay(1000);
  Serial.println("connecting...");
  lcd.setCursor(0, 0);
  lcd.print("connecting");
  connect();
}

void connect(){

    if (client.connect(server, 8080)) {
    Serial.println("connected");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("connected");

    client.println("hello server");
    client.println();
    delay(500);
    lcd.clear();
  }
  else {
    Serial.println("connection failed");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Connection Failure");
  }
  delay(500);
}

void loop() {

   //network
  if(!client.available()){
    Serial.println("lost connection!-restart");
    lcd.println("Disconnection");
    client.stop();
    connect();
  }
  else {

    int inp[5];
    getData(inp);
    Serial.println("next stage...");
    char *output = (char *) &inp[0];
    client.println(output);

    client.println("first");

    Serial.println("sent first...");

    //here repeats the same process for the other sensors - omitted for clear reading

  }
   //end network

   delay(500);
}

void getData(){

Serial.println("GetData()");
long durationThree, inchesThree, cmThree = 0;
long durationOne, inchesOne, cmOne = 0;
long durationTwo, inchesTwo, cmTwo = 0;
long durationFour, inchesFour, cmFour = 0;

//SENSOR ONE
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinOne, INPUT);
durationOne = pulseIn(echoPinOne, HIGH);

delay(100);

//SENSOR TWO
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinTwo, INPUT);
durationTwo = pulseIn(echoPinTwo, HIGH);

delay(100);

//SENSOR THREE
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinThree, INPUT);
durationThree = pulseIn(echoPinThree, HIGH);

delay(100);

//SENSOR FOUR
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinFour, INPUT);
durationFour = pulseIn(echoPinFour, HIGH);

//DISTANCE CALCULATION
cmOne = microsecondsToCentimeters(durationOne);
cmTwo = microsecondsToCentimeters(durationTwo);
cmThree = microsecondsToCentimeters(durationThree);
cmFour = microsecondsToCentimeters(durationFour);
//Serial.println("sending...");
//char *out = (char *) &cmOne;
//Serial.println(out);
//client.println(out);
//Serial.println("sent!");      used this to test - same issue

Serial.println("got data...");
inputBuf[0] = cmOne;
inputBuf[1] = cmTwo;
inputBuf[2] = cmThree;
inputBuf[3] = cmFour;

}

long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}

The code you posted is performing incompatible casts and by thus is sending garbage to client.println.

There is no automatic conversion in C/C++ from an array of integers (int inp[]) or longs, to a C style string char *. A C Style string should end with null terminator \0, and the one in your code doesn't. For example, in this line:

char *output = (char *) &inp[0];

The inp[0] contains the first integer. The expression &inp[0] contains the address of that integer in memory.

Thus the cast to (char *) will yield a malformed C style string, since it will not end with a null terminator, and more important, will not contain the data you expect it would (this cast is saying - "hey, compiler, note that the address of that int is actually the address of a C style string").

You can, however, utilize the String type constructor that receives int/long, and send the duration in order, something similar to:

        void getData()
        {
            ... // rest of the code here
            client.println(String(cmOne));
            client.println(String(cmTwo));
            ... // etc.
        }


Is my TFT screen defective? I bought the standard 1.77" TFT screen months ago and It has never worked. I follow the wiring diagram shown for Uno on the guide on the Arduino website and the best result I have ever got is it seeming like the screen itself is broken. I must have rewired the whole thing many times now and quadruple checked each time.
As I have never used this screen before I do not know what is correct any further than the tutorial.

I say that because it seems to understand instructions but does not display them correctly.
I have tried multiple examples and tests on it that all yield weird results.
The tests I have tried are:

The SD demo that loads the Arduino icon off SD and fills the screen
with it. The serial connection says that it has successfully read the
image but just displays black lines
Setting the background colour with random colours which seems to work fine apart from the black bars
Drawing random colour, positioned and sized rectangles. Result is image below. Colours seems to prefer pink, purple and white.

As you can see it looks like the image is 1D, no rectangles stop across the x axis so I did a test for that, it just draws a 1x1 pixel red dot going down the screen's left side, if it drew a red line moving down then my thought that it was stretching the first column would be correct, it didn't, just white and black bars still, so I modified it to test every column in case it wasn't column 0, same result...weirdly only when I made the 1x1px rectangle 5x5 my idea was correct.

As you can see on both the images, the black bars are a persistent factor, their colour cannot be changed and they appear once TFT.begin has been called.

After looking around the only help I could find is someone mentioned that Arduino the company updated the TFT library but not the software but he/she didn't provide a download link. In the time I've had this I'm sure I'm redownloaded/updated the Arduino software a few times too.

Are the glitches normal for wrong pin connections? Is there some pin wrong on the website?

It's pretty hard to see the wiring for sure in the photo, but you have an extra red wire looped from one side to the other, what is that for? It's not in the tutorial. Other than that, your wiring looks ok to me, as far as I can see from the photo. So probably it's broken, I hope you can return it.


Arduino Data to Cloud without shield [] I am performing basic analogue read like temperature and LDR, reading the data serially, but I would like to deploy it online to cloud platforms like (Plotly, Xively, ThingSpeak, or DataSparkFun). Is that feasible? Thank you in advance.

Without a shield? Yes, it's possible.

You send it serially to your computer as you are doing now. Then you write some software for your computer to read that data serially and send it on to your chosen web service.

Can the Arduino magically send data to the internet by itself without you investing in a network connection of some form (WiFi shield, Ethernet Shield, etc)? No, of course not. If it could there would be no market for the network shields, and so they wouldn't exist.


Can I use TCS34725 Color Sensor with Lilypad? I have been trying to get TCS34725 color sensor working with LilyPad Arduino USB - ATmega32U4 Board but with no success. I am wondering if it possible? I have been using the following Sketch to try and get a reading but nothing appears in the monitor:

#include <Wire.h>
#include "Adafruit_TCS34725.h"

/* Example code for the Adafruit TCS34725 breakout library */

/* Connect SCL    to analog 5
   Connect SDA    to analog 4
   Connect VDD    to 3.3V DC
   Connect GROUND to common ground */

/* Initialise with default values (int time = 2.4ms, gain = 1x) */
// Adafruit_TCS34725 tcs = Adafruit_TCS34725();

/* Initialise with specific int time and gain values */
Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);

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

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1);
  }

  // Now we're ready to get readings!
}

void loop(void) {
  uint16_t r, g, b, c, colorTemp, lux;

  tcs.getRawData(&r, &g, &b, &c);
  // colorTemp = tcs.calculateColorTemperature(r, g, b);
  colorTemp = tcs.calculateColorTemperature_dn40(r, g, b, c);
  lux = tcs.calculateLux(r, g, b);

  Serial.print("Color Temp: "); Serial.print(colorTemp, DEC); Serial.print(" K - ");
  Serial.print("Lux: "); Serial.print(lux, DEC); Serial.print(" - ");
  Serial.print("R: "); Serial.print(r, DEC); Serial.print(" ");
  Serial.print("G: "); Serial.print(g, DEC); Serial.print(" ");
  Serial.print("B: "); Serial.print(b, DEC); Serial.print(" ");
  Serial.print("C: "); Serial.print(c, DEC); Serial.print(" ");
  Serial.println(" ");
}

Can I use TCS34725 Color Sensor with Lilypad?

Yes but please note that the I2C pins are D2 (SDA) and D3 (SCL). No extra components are required when connecting to the Adafruit TCS34725 breakout board. It contains pull-up resistors, and voltage/signal level converters (if needed).

Cheers!

Ref. https://cdn.sparkfun.com/datasheets/E-Textiles/Lilypad/Lilypad_Arduino_USB_v12.pdf


Uploading .hex to ATTiny13 using Arduino I would like to upload a .hex to ATTiny13V (or '13A) using Arduino Uno R3.
I think I know everything to do, but ATTiny13 ISP support and Arduino IDE is a bit search-and-find, and I have some grey-areas in my understanding of how this all works together.

I got here by:

-Finding an Instructable that did something I liked, and there's a ATTiny13V used, a .hex to upload, and C source if I want to modify the source.  Right now I do not need to modify the source, the available .hex is fine.

-I then looked for a way to have AVR programing from OS X.  This seems a little problem, many AVR programmer hardware work great under Windows but seem to have mixed results under OS X.  I saw Arduino could be used for this under OS X.

-I looked on local craigslist for Arduino, someone was selling a Uno R3 with some extras for a great price, and here we are.   And now I have a lot more projects I wish to complete!

I am using Arduino 1.6.10 (from the .cc not the .org).

I read on stackexchange and other places that smeezekitty's core13 works for the ATTiny13.
elabz.com/arduino-shrunk-how-to-use-attiny13-with-arduino-ide/

That's great, but: If I am not using any of the Arduino-specific commands, I don't think I need the bootloader, correct?  I think it is not really a bootloader but builds support for some of the Arduino-specific higher-level commands used by sketch files.

Do I even need the ATTiny13 core files if I hook the pins up properly between the '13 on a breadboard and the Arduino (as per here:  https://create.arduino.cc/projecthub/arjun/programming-attiny85-with-arduino-uno-afb829 ).

I really do not understand what the Arduino IDE/bootloader is doing for me as an abstraction layer.  Do I need the bootloader if I'm not using any of the higher-level Arduino-specific commands on the chip?  HOw about the core files for ATTinyanything vs specifically ATTiny13?

The hex file and C source I will be using are here:
http://www.instructables.com/id/Programmable-LED/
My nextstep will be to modify the source. The C source looks like it references some AVR-specific header files.  I see that the ArduinoIDE uses avrdude so maybe things will compile anyway?

I feel like I'm close but not 100% in my understanding of what I need to do, with the tools I have on hand.

Thanks for your help- I am not above a step-by-step.

Main question 1:  I have a .hex file, an Arduino and IDE 1.6.10, OS X, and breadboard and useful components.  What do I need to do to put the hex on this ATTiny13?

Main question 2: Jumping-off points for taking the C source I linked, tweaking it a bit, building a hex, and uploading that.  I am not against moving it to a sketch if I have to, but it would be good for me to learn how this works before I mode to the IDE.

I have a small software background, am comfortable taking that C source and making changes and compiling (assuming I can find the needed .h files), but this is my first time working with any multiprocessors.

Your computer cannot talk directly to the ATtiny. You need some piece of
interfacing hardware between them. This is called an ICSP (or ISP)
programmer. You also need software to drive the programmer, typically
avrdude.

If you do not have a programmer, you can buy one (I had success with
some very cheap USBASPs), or you can program an Arduino Uno to behave
like an ISP programmer. You do this by uploading into the Arduino a
program called ArduinoISP, like explained in the tutorial Using an
Arduino as an AVR ISP (In-System
Programmer). You will
typically use the Arduino IDE and the Arduino core for the Uno to
compile and load ArduinoISP into your Uno. Once this is done, you can
use the Arduino as a programmer and burn your .hex into your ATtiny.

If you want to compile your own programs for the ATtiny, you will need
the avr-gcc compiler and the avr-libc. These are bundled with the
Arduino IDE, so you already have them. You will need an Arduino core for
the ATtiny only if you want to use the Arduino APIs and libraries.
Otherwise you can write plain C programs with noting else than the
avr-libc and avr-gcc.

Edit: To compile a plain C program, you can type something like
this:

avr-gcc -mmcu=attiny13a -DF_CPU=1200000 -Os -Wall -Wextra flickled.c -o flickled.elf
avr-objcopy -O ihex flickled.elf flickled.hex

This assumes your source file is called flickled.c and your ATtiny
runs at 1.2 MHz.


Code for determining beats per min when timing a wooden clock I'm new to Arduino and coding but I build wooden clocks.  The biggest problem is timing the clock to the correct beats per min when adjusting pendulum length.  I'm thinking Arduino and an IR sensor?? to detect when the pendulum breaks the beam, then displaying the beats per min real time would be possible.  If not real time then just beats in a variable time period, ie 1 min or 2 or 5 or 10 min.  I've looked for this type of code and circuit but haven't been able to find one.  Any help would sincerely be appreciated.

If the accuracy you require is about 1%, that should be doable with any
Arduino. Much higher accuracies would be hard to achieve because most
Arduinos are clocked off a ceramic resonator, and these have a frequency
tolerance of about 0.5%.

Given that your signal is very slow, the simplest approach may be to
poll the pin connected to the sensor and record the time (using
micros()) of the low → high transition. Then you can compute the
beat frequency as the inverse of the time between consecutive
transitions.

There is, however, the possibility that the sensor is not exactly in
the middle of the swing. Then, for better accuracy, I would measure the
time taken by two beats, i.e. a full swing. This way the pssible
asymmetry will not affect the accuracy.


Arduino DC motor causes disturbance. What can cause it? I tried to fix this problem the whole weekend but, after no success I decided to post it here. I would really appreciate any help.

The problem

The Wi-Fi module activates the DC motor and lets it run for 3 seconds, but when the DC motor stops after that 3 seconds, the Wi-Fi module and display don't respond anymore.  It only works once.  (After I push the reset button the same thing happens.)

Question

What causes this disturbance? Any advice on my circuit? (I included a Fritzing Diagram because I am bad at drawing schematics)

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
SoftwareSerial ESP8266(9, 8); // RX = 8 en TX = 9

#define DEBUG true

boolean FAIL_8266 = false;
int LED = 13; // led op 13

int secondeAan = 3000;

String my_AP_SSID = "myID";
String my_AP_Pass = "myPass";

void setup()
{
  // -- stel led in --
  pinMode(LED, OUTPUT);

  // -- lcd scherm --
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 1);

  do {
    ESP8266.begin(115200); // start communicatie met esp8266

    //Wait Serial Monitor to start
    while (!Serial);

    lcd.clear();
    lcd.print("--- Start ---");

    ESP8266.print("AT\r\n");
    delay(500);

    if (ESP8266.find("OK"))
    {
      FAIL_8266 = false;
      sendData("AT+RST\r\n", 4000, DEBUG);
      sendData("AT+CWMODE=3\r\n", 2000, DEBUG);
      sendData("AT+CWJAP=\"" + my_AP_SSID + "\",\"" + my_AP_Pass + "\",9,4\r\n", 2000, DEBUG);
      sendData("AT+CIFSR\r\n", 2000, DEBUG);
      sendData("AT+CIPMUX=1\r\n", 2000, DEBUG);
      sendData("AT+CIPSERVER=1,80\r\n", 2000, DEBUG);

    } else {
      lcd.clear();
      lcd.setCursor(0, 1);
      lcd.print("Module have no response.");
      delay(500);
      FAIL_8266 = true;
    }
  } while (FAIL_8266);
}

void loop()
{
  // Get the number of bytes (characters) available for reading from the serial port
  if (ESP8266.find("+IPD,"))
  {
    lcd.clear();
    lcd.print("Nieuwe connectie");
    // -- sluit connectie --
    motorToggle();
    sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);
    sendData("AT+CIPCLOSE=1\r\n", 100, DEBUG);
    sendData("AT+CIPCLOSE=2\r\n", 100, DEBUG);
  }
}

void motorToggle () {
  digitalWrite(LED, HIGH);
  lcd.clear();
  lcd.print("eten gegeven");
  delay(secondeAan);
  digitalWrite(LED, LOW);
  delay(200);
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  ESP8266.print(command); // send the read character to the esp8266

  long int time = millis();

  while ( (time + timeout) > millis())
  {
    while (ESP8266.available())
    {
      char c = ESP8266.read();
      response += c;
    }
  }

  if (debug)
  { lcd.clear();
    lcd.print(response);
  }

  return response;
}

Thanks for the help everyone. I fixed it by using Capacitors. They suppress the noise that the dc motor produces. I found my information  here


Arduino ultrasonic distance meter doesn't display correct distance The Arduino distance meter that I made doesn't display the correct distance. It just displays "0.0 inches".

Here's the code I used:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int pingPin = 7;
int inPin = 6;
long duration, inches, cm;
int indec, cmdec;
int inchconv = 147;
int cmconv = 59;
String s1, s2;

void setup() {
  lcd.begin(16, 2);
  pinMode(pingPin, OUTPUT);
  pinMode(inPin, INPUT);
}

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

  duration = pulseIn(inPin, HIGH);

  inches = microsecondsToInches(duration);
  indec = (duration - inches * inchconv) * 10 / inchconv;
  cm = microsecondsToCentimeters(duration);
  cmdec = (duration - cm * cmconv) * 10 / cmconv;
  s1 = String(inches) + "." + String(indec) + "in" + "     ";
  s2 = String(cm) + "." + String(cmdec) + "cm" + "     ";
  lcd.setCursor(0, 0);
  lcd.print(s1);
  lcd.setCursor(0,1);
  lcd.print(s2);

  delay(100);
}

long microsecondsToInches(long microseconds)
{
  return microseconds / inchconv;
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / cmconv;
}

Here's the wiring diagram:

Might there be a problem in my code, or in my wiring?

To solve a problem like this you need to break it down into smaller pieces so that you can build up some confidence about what is working and what is not. When you share a problem like this as a question it helps if you can give us some idea of your experience level and of what you've already done to debug the problem – that helps with avoiding telling you what you already know and makes it easier to focus in on where the problem might be.

From what you've said it appears that you have things working well enough that you get a display on the LCD but it does not represent a meaningful distance.

Looking at your schematic the first thing that comes to my mind is that you have the ultrasonic sensor at the opposite end of the breadboard from the LCD. Many breadboards split their power rails at the middle. So start by confirming that you have power to the sensor.

After that, double-check the rest of your wiring.

The next step for me would be to confirm that I understood the sensor and to try and prove that it was working as I expected. Look for some sample code that is known to work (often the site you bought the sensor from will have links to beginning tutorials or code samples). Try that to see if the sensor works with the sample code.

If that doesn't work then check to see what you can do to prove the sensor is good (or bad). You might also contact the vendor to see if they can give you advice on proving that the sensor works.

Basically, break the problem down into "bite sized" chunks and work through it one step at a time, doing the simple stuff first. Try not to assume anything…


Arduino uno shift register I have shift register 74HC595. I added 7 push buttons from Q1-7 and the 8th to ground. On the other side which pin of the register will go to Arduino pin 2? And wich one to the 5v pin?

How can I read one button at a time in the code because on the Arduino it is just 1 pin?

A shift register is an output device. You won't be able to "Read" 7 push buttons in this way.

A shift register like that is for taking a "series" of bits on one wire and parallelizing them onto 8 wires.

It does not work in reverse. The reverse is called a multiplexer.


Use terminal command to verify software I've seen that it is possible to use terminal command to verify software instead of using the IDE. Something like arduino --verify lab.ino.
Is there a way to do so on Mac OS?

Thank you

I managed to verify code from terminal by invoking /Applications/Arduino.app/Contents/MacOS/Arduino --verify lab.ino BUT this command automatically starts the IDE and exits it afterwards. Even with an IDE instance open it will start a new one. This is annoying since it will switch the active workspace away, but it kinda works. See arduino manpage.


Why is my interrupt code not working? Background
I'm trying to write code to read signals from a six-channel RC receiver on an Arduino Mega 2560. Currently I am keeping the code to just read one channel to make things easy to troubleshoot. The problem is my shared variable is not updating, leading me to believe that my interrupt service routine is not detecting any rising edges.
I thought my receiver was broken, so I tested it using the standard Arduino attach interrupt function. It worked perfectly, so my receiver is fine.
I used Serial.print() to see if my volatile channel variable was updating (that is, change its value to the channel 1 flag value). It was not updating, so my ISR must be wrong. You can find the original code in the blog post.
What's wrong? I'm out of ideas.
#include <PinChangeInt.h>

//Pin assignment
#define channel1PIN 10

//Bit flags
#define Channel1FLAG 1

//Flag holder
volatile uint8_t bFLAGUPDATESHARED;

//Shared variables: Accessed by the interrupt service routine and read in 'void loop'.
volatile uint16_t unCHANNEL1SHARED;

//Start time variables: These are used to set the start time of the rising edge of
//a pulse. They are only accessed by the ISR, and thus they are unsigned integers and
//not volatiles.

uint32_t ulCHANNEL1START;

void setup()
{
  Serial.begin(9600);
  Serial.print("RC Channel PWM Read Interrupt Test");

  //PinChangInt library function. Used to set attach interrupts.
  PCintPort::attachInterrupt(channel1PIN, calcCHANNEL1, CHANGE);
}

void loop()
{
  //In-loop variables to hold local copies of channel inputs.
  //This is static so it retains values between call loops.
  static uint16_t unCHANNEL1IN;

  //The in-loop copy of the bSHAREDFLAGUPDATE volatile flag holder
  static uint8_t bFLAGUPDATELOCAL;

  //Check to see if any channels have received signals. If so, copy
  //shared variables to local in loop variables.
  if (bFLAGUPDATESHARED)
  {
    //Switch off interrupts when I copy shared variables to local variables
    noInterrupts();

    bFLAGUPDATELOCAL = bFLAGUPDATESHARED;

    if (bFLAGUPDATELOCAL & Channel1FLAG)
    {
      unCHANNEL1IN = unCHANNEL1SHARED;
    }

    bFLAGUPDATESHARED = 0;
    interrupts();
  }

  Serial.println(unCHANNEL1IN);

  //Clear local update flags copy as all values have been copied to local variables
  bFLAGUPDATELOCAL = 0;
}

void calcCHANNEL1()
{
  if (digitalRead(channel1PIN) == HIGH)
  {
    //If pin goes high, start timer and set ulCHANNEL1START to timer start
    ulCHANNEL1START = micros();
  }
  else
  {
    //If it is not rising, it must be falling so set shared
    //variable to current time-start time
    unCHANNEL1SHARED = (uint16_t)(micros() - ulCHANNEL1START);

    //Tell that channel 1 has received a signal
    bFLAGUPDATESHARED |= Channel1FLAG;
  }
}

Only some ports on the Atmega2560 support pin-change interrupts, specifically ports B, E (bit 0), J (bits 0 to 6) and K.

Looking at the reference schematic that means that these pins on the board are supported:

     Chip
Name  Pin  Pin on board
-----------------------

Port B

PB0 - 19 - D53 (SS)
PB1 - 20 - D52 (SCK)
PB2 - 21 - D51 (MOSI)
PB3 - 22 - D50 (MISO)
PB4 - 23 - D10
PB5 - 24 - D11
PB6 - 25 - D12
PB7 - 26 - D13

Port E

PE0 - 2 - D0 (RXD0)

Port J

PJ0 - 63 - D15 (RXD3)
PJ1 - 64 - D14 (TXD3)
PJ2 to PJ6 - not connected on board

Port K

PK0 - PK7 - (89 - 82)  - A8 - A15

Thus you can see that D10 to D12, which you say works, are in that list. Other random ones would not be.

SoftwareSerial

You can see confirmation on the page for SoftwareSerial where it says:

  Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

This is because SoftwareSerial uses pin-change interrupts to detect incoming serial data, and thus the disclaimer on that page about which pins it will work with.

Atmega2560 pin-outs

  PinchangeInt should work on any digital pin

Note that the Atmega328P (as used in the Uno) has less ports, and all are available for pin-change interrupts on that board.