text:
Motor Control Help
Here is my objective:
If the value of EMGv is at or above 900, start moving the motors left. The motors should continue to move left for a maximum of one second, provided EMGv stays at or above 900. If during this time EMGv goes below 900, the motors should move right for one second. Then the motors should stop. At any time after this should EMGv go above 900 again, the process should repeat.
In simpler terms, the project is a robotic hand, wired to an EMG circuit. When the EMG signal gets above 900 the hand should close by the motors all turning left for one second and when the signal goes below 900 the hand should open by the motors turning right for one second.
Here is my loop atm when move(motor #, speed, direction (1 for left, 0 for right)) is the function to move the motors and stop() stops all motors
void loop(){

  unsigned long starttime; //time limit for hand movement
  int EMGv = analogRead(EMG);
  starttime=millis();
  while(EMGv >= 900){
    if (millis()-starttime < 1000) //limit on 1000ms
    {
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left
    } else {
      stop();
    }
  }
}

Perhaps you can edit this question to incorporate some examples and the specification you wrote for a later question.

I suspect you would do well to first write (in English) the exact set of rules you want it to follow -- don't worry about the code to begin with - get it clear in your head what you want the code to do.  (If this is already clear to you, then just write it :-) )
Here's what I think you might mean -- although it's not exactly what you wrote.
If EMG is at or above 900, start moving the motors left.  The motors should continue to move left for a maximum of one second, provided EMG stays at or above 900.  If during this time EMG goes below 900, the motors should move right for one second.  Then the motors should stop.
Once you have that, turning it into code looks well within your ability, judging by the code you've posted.  Here's my attempt - note that it'll only be correct if I have correctly stated your desired rules.  (And if I've correctly guessed how the move API works - I guess it starts the motor moving, that you need to cancel it to stop it moving.  Please say if this is wrong.)
I've used LEFT and RIGHT instead of 1 and whatever, for clarity.
void loop(){
  // If EMG is at or above 900
  int EMGv = analogRead(EMG);
  if (EMGv >= 900)
  {
    unsigned long starttime = millis();

    // Start the motors moving left
    move(0, 255, LEFT); //motor 1, full speed, left
    ...and the other motors...

    // Continue for a maximum of one second, and while EMG stays at or above 900
    while ( (millis()-starttime < 1000) && ((EMGv = analogRead(EMG)) >= 900)) {
      // Just wait
      delay(1);
    }

    // If during this time EMG goes below one second...
    if (EMGv < 900) {
      // ...the motors should move right for one second
      move(0, 255, RIGHT); //motor 1, full speed, right
      ...and the other motors...
    }

    // Then the motors should stop.
    move(0, 0, LEFT); //motor 1, stop, left
    ...and the other motors...
  }

// More stuff here, otherwise it will immediately go round the loop again and start moving again
}

If you want to know what exactly he is trying to do, look at his previous question.

I did, and I get the gist of it, but I still wasn't confident I understood exactly what was wanted.

Thank you for your help! Ive uploaded this code and what it seems to do at the moment is turn the motors forward when the value is above 900 but it does not limit that to one second nor does it reverse them when the value falls below 900. I'm gonna work on debugging but if you have any idea why please let me know! Thanks.

My suspicion is that I incorrectly guessed how to switch the motors off.  My guess was move(0,0,LEFT);.  Is that correct?  Also, I just fixed a bug which would have prevented the reverse from working.

ok ill try it thank you. I suspect an easy way to run the reverse would be: If EMG goes from above 900 to below 900, run reverse for one second. Im just not sure what the Arduino code for that is.

also ive written a function to stop the motors that is simply stop()

Currently, the loop you have provided successfully turns the motors but does not limit them to one second or reverse them when the value goes below 900. Thank you again for your help.

Are you saying that you don't know how to make the motor run in reverse? If that's the case, find that out before getting bogged down with whether the loop is working. (I strongly suspect it is.)

Also, have you done something to stop the main loop() from going round immediately? If not, it'll do just that, meaning it will immediately start turning again (if value >900).

Let us continue this discussion in chat.


text:
Serial Port greyed out Ubuntu 16.04
I am running Ubuntu Mate 16.04 LTS, with an Arduino Uno R3 clone. I am having the dreaded serial port graying out problem, and have not found a solution for fixing it. Currently, The serial port will grey out sometimes, and sometimes it will be not grayed out, and I can see that I have selected ttyUSB0. Usually when it is not grayed out, uploading a sketch will not work, and I get the error like it is grayed out:

avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
  An error occurred while uploading the sketch

chmod a+rw /dev/ttyUSB0

doesn't solve the issue, with log out included
gpasswd -a aaron dialout

doesn't solve the issue, with log out included
I searched preferences.txt and serial.debug rate is set to 9600
I have tried entering preferences.txt and deleting all of the serial entries. They are recreated the same after deletion, and this doesn't solve anything.
I tried running as sudo, doesn't work.
I tried solving this originally on Arduino IDE 1.0, didn't work.
I have upgraded to Arduino IDE 1.6.10, still not working.
running lsusb in terminal yields this while Arduino is plugged in:
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0a5c:21e6 Broadcom Corp. BCM20702 Bluetooth 4.0 [ThinkPad]
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Checking var/log/syslog after plugging in Arduino:

kernel: [42043.787178] usb 3-2: new full-speed USB device number 109 using xhci_hcd
kernel: [42043.916241] usb 3-2: New USB device found, idVendor=1a86, idProduct=7523
kernel: [42043.916249] usb 3-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
kernel: [42043.916253] usb 3-2: Product: USB2.0-Serial
kernel: [42043.916964] ch341 3-2:1.0: ch341-uart converter detected
kernel: [42043.918199] usb 3-2: ch341-uart converter now attached to ttyUSB0
mtp-probe: checking bus 3, device 109: "/sys/devices/pci0000:00/0000:00:14.0
  /usb3/3-2"
mtp-probe: bus: 3, device: 109 was not an MTP device

Ran to add to dialout group, then logged out
sudo usermod -a -G dialout aaron

No solution.
So it looks like Arduino board is not being recognized. Not sure what to try next. It is important that I have uploaded sketches before, but am not sure if there is a pattern to when it does not work. It does not work 95% of the time.
Thanks for the help!

How's about showing us what gets logged in /var/log/syslog when you plug in the arduino usb cable.

The magic word in your question is "clone". You're very much on your own unless you can identify just what components are in use on your board, especially the USB interface chip. The smart money is on it being a CH340 chip, and those are notoriously unstable and break very easily.

They break under Windows, not Linux. Is your user in the dialout group, Aaron? You must be to use serial ports.

@Avamander They break in two ways - one is shoddy drivers in windows, the other is a complete disregard for any form of ESD protection. They die horribly and never work again.

I have the same problem,
I believe that the problem is related to the 4.x kernel, since I have already tried another distribution with the kernel mermo and the problem persists. Using a windows virtual machine as guest works, which excludes communications and hardware issues.

Hi Ronaldo and welcome to SE Arduino. While your answer is good, and maybe correct, do you happen to have tried another version of the kernel (which is not 4.x) that works? I only ask, as it would help to back up your claim. Also, any links to documented evidence that also backs up your claim would be great. In addition, what is "kernel mermo"? I can find no reference to it on the web.

source: Stack Exchange

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

sort: votes


text:
Is there a way to keep a program on the Arduino after uploading new sketches?
I am looking for a way to keep a program on my Arduino Nano 3.0, after uploading new sketches on it. I would like to have a program on it that will control th screen and buttons at it. The user will choose one of the programs displayed on the screen and execute/pause/stop them. These programs will be uploaded on the Arduino, while the previous programmes stay.
If you are familliar with the Lego Mindsdorm microcontroller, you probably know waht I am looking for.
Is there a way to do that.

You want something like a dual boot arduino

looks to me like you just need one massive program which you flash onto the arduino, and theres a simple display and buttons that when it starts up allows you to select which "program" to run. Each time you add new programs its still the same big single program, but with more functions and you'd have to add more options to the GUI list.

@Gerben, you continue to astound me.  I thought you were just joshin' until I read that Hackaday.  +1

I have something similar - a text-to-Morse routine - that I use sometimes.  While it might be fun to have it always-resident it was just as easy to make it a function and then append it to my sketches as-needed.  The heavy lifting is finished, and I don't need it for every program, but can bolt it on quite quickly.

I'm not familiar with Lego Mindstorm, but I think I understand what you want and I am certain there is a way to do it, but I don't think it will be easy or even practical and I can't tell you exactly how to do it.
I'm pretty certain there will be a way to load a 'module' into memory and then make the program call that address.  I haven't got a clue how you would do it though, sorry.  GCC doesn't have a concept of DLLs like window does, but it does have shared libraries.  Or you might look at just reading a block of memory in.
Other approaches might be to have all the 'programs' as functions within you main program and call them depending on the user's input.  You can only do this if the 'programs' are small enough.
If you can refactor your 'programs' to extract the common code into functions and then have a data file (which could be read at runtime) that called the functions for each of your programming.  Basically  invent your own higher level programming language.  This wouldn't work if your code was very different and you could factor it down to a small enough number of functions.
Would it be possible to just have a number of hex files (compiled programs?) all of which have the common screen/button handler in and then have the special code for the appropriate program.  These could all be stored on an SD card and then loaded into memory by a second Arduino (sounds plausible to me, I'm sure someone will tell me whats wrong with that idea.)
An alternative based on the inverse of the above solution would be to have one Arduino to control the screen/buttons and it programs a second Arduino with the specialist code that is connected to the rest of your kit.

You cannot load code into RAM and then call that address: the AVR's Harvard architecture makes it impossible to run code from RAM. You need to load the code into flash, which is quite involved, and normally considered a bootloader's job. You will essentially have to write a custom bootloader. BTW, gcc doesn't support shared (aka dynamically linked) libraries on the AVR platform, only statically linked libs.

A special bootloader and a jump-list to functions in a seperate part of the flash is possible. But it is very impractical. Adding a .h include file to the project with binary compiled code as PROGMEM data (and a jump-list to the functions) might be a challenging job for programmers. That is also very impractical.
Perhaps the best way is to combine a number of normal libraries into a single .zip file which can be installed in the Arduino IDE.

You want something like this using the serial monitor:
if((homeMenuActivated) == true)
{
  Serial.println ("Program Number 1");
}

I am kind of glad you asked this, as I am working on a similar program with arduinos that can do the same thing you want.

The Arduino paradigm uses two programs on the target.  The boot loader and the application.  The processor is agnostic WRT this differentiation and runs the entire code set as one large application.
To put a 2nd application on an embedded processor is feasible. However, you would have to be intimately knowledgeable about how Arduino SDK works as well as the boot loader as you would have to create new features to relocate code normally found at fixed locations.  A rather involved task.
Instead, consider simply adding your utility code to your application code in the Arduino SDK and replace the utility code already on the processor with the new image.

Is there a way to do that.

sure.
one way to do it is to use a pin to indicate which program you want to execute.
uint8_t execution_switch=0;  //execution switch. 0->run setup0()/loop0(), 1->run setup1()/loop1()

void setup(void) {
  pinMode(EXECUTION_SWITCH, INPUT_PULLUP); //execution switch as input + pullup
  execution_switch=(digitalRead(EXECUTION_SWITCH)==LOW)?0:1;
  if (execution_switch==0) setup0(); else setup1();
}

void loop(void) {
  if (execution_switch==0) loop0(); else loop1();
}

you can easily change it to accommodate multiple programs / multiple switch pins, or real time switch, ....

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


text:
Thermosensor Error - 'Wire' does not name type?
Here is the code I am using:
#define D6T_ID 0x0A
#define D6T_CMD 0x4C

int ReadBuffer[35];
float ptat;
float tdata[16];

#include <Wire.h>
void setup() {
  Wire.begin();
  Serial.begin(9600);
  delay(500);

}

void loop() {

}
  int i;
  Wire.beginTransmission(D6T_ID);
  Wire.write(D6T_CMD);
  Wire.endTransmission();

  Wire.requestFrom(D6T_ID,35);

  for (i=0; i<35; ++i) {
    ReadBuffer[i] = Wire.read();
  }

  ptat = (ReadBuffer[0]+(ReadBuffer[1]*256))*0.1; //Reference Temp

  for (i=0; i<16; ++i) {
    tdata[i] = (ReadBuffer[(i*2+2)]+(ReadBuffer[(i*2+3)]*256))*0.1;
  }

  float tempF;

  if ( ((tdata[0]*9.0/5.0)+32.0)>0 )
  {
    for (i=0; i<16; ++i)
    {
      tempF = (tdata[i]*9.0/5.0)+32.0;
      Serial.print(tempF);
      Serial.print(',');
    }
    Serial.print((ptat*9.0/5.0)+32.0;
    Serial.print(',');
    Serial.println();
  }

    }
  }

This is the error I am getting:
exit status 1
'Wire' does not name a type
And it highlights this area of code:
Wire.requestFrom(D6T_ID,35);

I am completely new to using the arduino and coding so I am not sure if I already have the wire library that this code requires but when I look at the libraries in the Tools menu it is there. Do I need to download another library? If so can someone send me the link? Can someone explain what the error means? This is all foreign to me.
Thank you

***** It should say #include <Wire.h>

Your braces are not right. For example, for the loop function you have an open brace and then a close brace before you code starts.

You've goofed up your braces and none of that code is in loop(). Look at the braces in the code and make the appropriate corrections.

The reason for the error message is that your braces do not properly match, and the code that was meant to be inside loop() is not, but instead looks to the compiler like some new global declarations. Fix the syntax errors and your code will compile:

Remove the brace in line 18 that closes the loop() function prematurely,
Fix the missing ')' in line 46,
Remove line 52, an extraneous '}',


text:
Keep References Between Objects
I'm trying to recreate a small tween engine so I can interpolate values, leds hue, saturation and brightness in a easy way.
I'm having trouble to reference the value to interpolate into my tween object. If you look at the very last block, you'll see what i'm trying to achieve.
I've poor knowledge in pointers and references and it's driving me mad. Thanks for your help !

Pixel.h
class Pixel {
  public:
    Pixel(float a = 180, float b = 100, float c = 100);

    float hue;
    float saturation;
    float brightness;

    uint16_t toRGB();
}

Tween.h
class Tween {
  public:
    Tween(int fps = 60);

    float& target;
    float fps;

    void to(float& target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d));

    void tick();
    float apply();
    bool active = false;

  private:
    float a = 0;
    float b = 1;
    float (* ease)(float t, float b, float c, float d);

    float increment = 1;
    float progress  = 0;
};

Tween.cpp
#include <Arduino.h>
#include "Tween.h"

int const ITERATIONS = 1000;

Tween::Tween(int f)
{
  this->fps = f;
  this->active = false;
}

void Tween::to(float& target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d)) {
  if (this->active == true) {
    return;
  }

  this->target = target;
  this->active = true;

  this->a = from;
  this->b = to;

  this->ease = ease;

  int frame = 1000 / this->fps;
  int ms = duration * 1000;

  this->progress = 0;
  this->increment = ITERATIONS / (float)(ms / frame);
}

void Tween::tick() {
  if (this->progress >= ITERATIONS) {
    this->progress = 0;
    this->active = false;
  }

  if (this->active == false) {
    return;
  }

  this->progress += this->increment;
}

float Tween::apply() {
  if (this->active == false) {
    return 0;
  }

  float value = this->ease(this->progress, 0, this->b, ITERATIONS);
  this->target = value;

  return value;
}

The use of those will be :
Pixel pixel = Pixel();
Tween tween = Tween(40);

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

  // reset the values of the pixel
  pixel.hue = 200;
  pixel.saturation = 100;
  pixel.brightness = 0;

  // setup the tween object
  tween.to(pixel.l, 0, 100, 3, Easing::linearTween);
}

void loop() {
  // progress
  tween.tick();

  // set pixel.l = tween value (this is where it's not working)
  tween.apply();

  Serial.println(pixel.brightness);

  // we defined 40fps in the tween so the delay should be 1000/40 => 25ms
  delay(25);
}

The easing library is actually Robert Penner's work translated to Arduino (https://github.com/tobiastoft/ArduinoEasing)

The variable reference must be known and initialized in constructor (in its initializer list). If you need later initialization use pointers.

And that Easing library is pretty nasty one. So many sequence-point warnings...

may i ask why you downvoted this ? thank you for your feedback regarding the easing library tho. also, is it only that i need to initialize the reference holder or did you mean the reference variable ?

What is pixel.l? there is no "l" member (or function) in your PIxel class.

You don't need to use this->blah to access class member variables, just blah is enough.  e.g.: this->hue = 47.96; can just be hue = 47.96;  I guess you did this because you have the same parameter name as class member.

Please reduce your code to simply show what you need, rather than obliging everyone to read a lot of code that is unnecessary to provide a real answer to your question.

thank you @kingsley for this. i haf few parameters the same and coming from javascript putting "this" everywhere became a habit. i'll cut it down.

@jfpoilpret thank you for your feedback. i reduced the code already to make it what i thought the bare minimum not to be asked to put more code to understand fully the question. sorry for that.

From your question alone I am unsure what you are asking. Please edit your question so that it is clear what you are asking.

The member variable target does not need to be passed by reference at all.
void Tween::to(float target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d))
{
  if (this->active == true)
    return;

  this->target = target;
  this->active = true;

  // etc...
}

And then just call it without any sort of address or reference operator.
// setup the tween object
tween.to(pixel.l, 0, 100, 3, Easing::linearTween);

(but you still need to sort out what you mean by "pixel.l")
If you wanted to pass a Pixel object to the Tween::to() function, I would use a pointer to the object (although you could use a reference too).
void Tween::to(Pixel *pixel, /* ... etc*/))
{
    target = pixel->hue;
    other  = pixel->saturation;
    foo    = pixel->brightness;

    // etc.
}

Calling it like:
// setup the tween object
tween.to(&pixel, 0, 100, 3, Easing::linearTween);

It's not really clear exactly what you're trying to achieve just reading the code sample.

i'm sorry if the sample code didn't really show my goal. i guess my lack of knowledge in C confused people more than anything else ; but you guessed right with your 2 answers. Thank you very much for your patience.


text:
USB mini type B port on Arduino Uno
I bought today an Arduino Uno R3, and I'm looking forward to make it an HID device. I have seen many projects using a serial USB type B port. As I want to build a little gamepad, I would like to use the smaller USB mini type B port to achieve similar results. Looking it up did not seem to bring significant results.
Am I missing anything? Do I have to use a serial port similar to the one used by Arduino or can I reproduce the project using the aforementioned port?

Is it an Uno or an Uno R3?

The connector is just a connector. They carry the same signals - 5V, GND, D+ and D-.  By the way, how do you intend to make your Uno a HID device? And what does the connector (which is soldered to the board) have to do with it?

According to this video - https://www.youtube.com/watch?v=RoG_-9lAnSI - it can be done with the use of a serial port and a few other components
It is an Uno R3

Ah - software bit-banged USB.  Nasty.  Much better off re-programming the 32U4 chip to do proper USB.

I could be interested in such a method, what could it mean? Would i still be able to program it like a normal Arduino?

Just use a Mini type B to Standard type B adapter, if so required. It will pass the data lines through correctly.

It sounds like you are going to be attempting software "bit-banged" USB.  That, while possible, is severely frowned upon, especially when you have the resources to do it properly at your fingertips.
In answer to your question, yes, you can use a USB mini B connector.  It is no different to a USB B connector except it is much smaller and contains one extra pin - USBID - which you can completely ignore (it's only used on USB On-The-Go devices).
USB is quite a heavy protocol to do in pure software - it won't leave much "room" for you to do much else.  Better would be to re-program the ATMega16U2 chip that is used for the current USB interface.  You will need some form of hardware programmer for it - you can use another Arduino Uno, and once done you won't be able to directly program the ATMega328P chip through the USB, so you would need some other method for connecting that (external USB serial adapter cable, or another Arduino), but the ATMega16U2 chip is specifically designed to work with the USB.  Offloading the USB portion of your project onto that chip and using the serial interface that is already wired up to communicate commands and instructions to/from the ATMega328P would be a much more powerful (and reliable) system.  There's plenty of tutorials and links around to show you how to reprogram that chip.

i actually only wanted to know if it was possible to use the USB mini connector. I can see now that this setup is not the best solution for sending keypresses (or input in general) to a computer, but i'm okay with it for now. I am still a newbie so reprogramming the chip may be a bit over my capabilities, so for a better implementation of my project i will look into buying an Arduino Due, Leonardo, or something else, depending on my needs. The answer is therefore accepted.

It's an ATmega16U2 on the Uno, @Majenko. See Arduino / Genuino UNO.

@Nick I always get them mixed up. I know it changed from the R2 to the R3 and I never remember which it changed from / to. I though it went from 16U2 to 32U4 but maybe it went from 8U2 to 16U2.

Yep I think it went from a 8U2 to a 16U2. I can never remember, either, I always have to look it up. :)

As an alternative to Majenko's suggestion you can implement Virtual USB as described at Virtual USB Keyboard. You just need:

3 resistors
2 zener diodes
a bit of wire
a suitable USB socket

The advantage is you haven't modified your Uno's USB chip (the ATMega16U2) so you can continue to upload sketches in the normal way.
The disadvantage is that the software USB may be more flaky than a hardware-implemented one.
Personally I don't like reprogramming my ATMega16U2 because I may as well have used one of the chips with a ATmega32U4 chip on it in the first place (like the Micro) which is designed for easy reprogramming.

That solution is the one i found to be the easier. I already linked to a video in one of my comments above.


text:
Using TMRpcm library, the audio does not play
I'm using the https://github.com/TMRh20/TMRpcm/wiki library to play wav files from an SD card to a speaker I have attached to my Arduino.
I have run separate tests/programs that ensures:

my speaker is connected properly and can play sound
my SD file is connected properly as it can read and files, text files.

However, I'm trying to use the tmrpcm.play("example.wav") command and nothing is happening. I used wav files that for sure works (from a demo I found online) so it's not the wav file problem.
Anyone have any clue on what is going on and how I can fix this?

This is now 5 months later - but I recently had the same problem.
Because the TMRpcm library plays through pulse width modulation, make sure your speakers are hooked up to a PWM capable pin.
That caused me no end of headaches trying to figure out.


text:
Graph plotting on Processing from Arduino sensor data
I am trying to plot a graph on processing but I'm having challenges going about it. The processing sketch below does work for plotting only one axis, and I'm trying to plot all three axis on the same sketch. Does anyone have an idea on how I could go about it. Below are the Arduino and Processing sketches.
Arduino
AcceleroMMA7361 ski;
int x;
int y;
int z;

void setup()
{
   Serial.begin(115200);
   ski.begin(13, 12,11,10, A0, A1, A2);
   ski.setARefVoltage(3.3);
   ski.setSensitivity(HIGH);
   ski.calibrate();
}

void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
   //Serial.print("\nx: ");
     Serial.println(x);
   //Serial.print("\ty: ");
   //Serial.print(y);
   //Serial.print("\tz: ");
   //Serial.print(z);
   delay(10);                                     //(make it readable)
}//End of Arduino Sketch

Processing
import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph

float fValue;
boolean newVal = false;

void setup () {
   size(800, 630);
   println(Serial.list());
   myPort = new Serial(this, Serial.list()[0], 115200);
   myPort.bufferUntil('\n');
   background(2);
   stroke(127, 34, 255);
}

void draw () {
    if (newVal) {
       line(xPos, height, xPos, height - fValue);
       if (++xPos >= width) {
         xPos = 0;
         background(2);
       }
       newVal = false;
    }
}

void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');
   if (inString != null) {
       inString = trim(inString);
       fValue = float(inString);
       fValue = map(fValue, 0, 1023, 0, height);
       newVal = true;
     }
}

I have edited your serialEvent() method a little bit, so it could handle the data from the Arduino, when split by a tab.
void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');

   if (inString != null) {
     values=split(inString,"\t");  //Splitting the output of the arduino into a String Array
     for(int i=0;i<values.length;i++){
       values[i]=trim(values[i]); //deleting the whitespaces as before
       float_values[i]=float(values[i]); //cast the string to a float as before
     }
       x = map(float_values[0], 0, 1023, 0, height); //map the value as before
       y = map(float_values[1], 0, 1023, 0, height);//map the value as before
       z = map(float_values[2], 0, 1023, 0, height);//map the value as before
       newVal = true;
     }
}

so your sending on the Arduino has to look like this:
void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
    Serial.print("\n");
    Serial.print(x);
    Serial.print("\t");
    Serial.print(y);
    Serial.print("\t");
    Serial.print(z);
    delay(10);                                     //(make it readable)
}

You still have to make the drawing in the draw() method of processing, but I think that this is not the problem.
For the 3d draw you should have a look on the Processing reference or at this special topic, P3D by Daniel Shiffman.
I have not tested the code, but I think that it should work.
If you have questions, feel free to ask ;D

+1 - for taking the time to make the correction - however, you should test your code before posting it, as some people may just copy and paste the code without even thinking of testing it, which may have some unforeseen outcome.

There are two problems, why I have not tested my code: the first is, that I have no arduino avaible, because i have lend all of mine to the school for a group of robots acting together and the second reason is, that I have the final exams (i am from germany) in next tuesday


text:
Is the SIM900 3G? Or is the SIM900A able to connect to 3G?
I would like to state that I am not familiar with the whole cellular connection thing. But I was wondering if the SIM900/or/SIM900A is 3G and will work with PTel Mobile.
I need this Arduino to be able to travel and needs to connect to every PTel's tower. Will I be able to connect to 3G or only the 2G and the 1G networks?

Do you need 3G, or do you just need Data? Arduinos don't run fast enough to even saturate 2G.

It's GPRS only (GPRS class 10: max. 85.6 kbps) according to the datasheet

I don't have enough reputation to post a comment, but this is a comment for both your answers, TP Ap and Ralph. What is the source for your answers? I'm trying to find out the answer to this question myself and I've seen a lot of claims like yours which aren't backed up by sources. I haven't found a single source which confirms this one way or another. I read the datasheet for the chip and couldn't find the answer there either.

Find the proper SIMCom module here.

First of all if you are in USA you cannot use SIM 900A since it supports only Dual frequency bands.(900,1800 MHz)it supports only Asian region countries.
According to Wikipedia, PTel Mobile supports only GSM 850/1900 frequencies.
so SIM 900 supports( 850,900,1800,1900 MHz ) you must use SIM900
Considering about the speed you cannot obtain 3g, 4g speed since GSM Shield(SIM900) provides maximum of GPRS class 10: max. 85.6 kbps (downlink) so,
It will able to connect but cannot get such speed in 3g and 4g.

It will not be able to connect to a 3G or 4G network. There has to be a 2G network / support and that support is getting less.

Source citation?

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


text:
STM32 VGA Output - don't understand why lines are jagged
I am using "blue-pill" STM32F103C8 (http://wiki.stm32duino.com/index.php?title=Blue_Pill) to create VGA output. I am connecting PB6 to VSync, PB0 to HSync, and PA0 to red using 278 Ohm resistor.
I don't understand why the lines are "jagged", like in the picture:
I would appreciate any input.
By the way, my real code is more complex and can display 256x192 with 64 colors. Since this board has 20K memory, I am using separate areas for pixels and colors, like Sinclair ZX (https://en.wikipedia.org/wiki/ZX_Spectrum_graphic_modes).
This is my code:
// interrupt handlers
void EndVBackPorch();
void ShockAbsorber();

volatile uint8 *GPIO_ODR;
volatile int vflag = 0; /* When 1, can draw on the screen */

void setup()
{
  pinMode(PB6, PWM); // VSync
  pinMode(PB0, PWM); // HSync

  // PA0..PA5 set to OUTPUT with max speed 50 MHz
  GPIOA->regs->CRL = 0x88333333;
  GPIO_ODR = (volatile uint8_t *)&GPIOA->regs->ODR;

  // 640 x 480 @ 60 Hz (Standard, pixel clock frequency 25.17 MHz)
  //InitHSync(false, 2287, 275, 400);
  //InitVSync(false, 525, 2, 35 + 48);

  // 640 x 480 @ 60 Hz (non-standard, pixel clock frequency 24.0 MHz)
  InitHSync(true, 2376, 264, 370);
  InitVSync(true, 505, 5, 10 + 74);
}

void loop()
{
    // Everything happens in the interrupts
}

void InitVSync(
  bool isNegative,
  int wholeFrame,
  int syncPulse,
  int startDraw)
{
  HardwareTimer timerVSync(4);

  timerVSync.pause();
  timerVSync.setPrescaleFactor(1);
  timerVSync.setOverflow(wholeFrame); /* Vertical lines */

  // VSync on pin PB6
  timer_oc_set_mode(timerVSync.c_dev(), TIMER_CH1,
            isNegative ? TIMER_OC_MODE_PWM_2 : TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
  timerVSync.setCompare(TIMER_CH1, syncPulse);

  timerVSync.setChannelMode(TIMER_CH4, TIMER_OUTPUT_COMPARE);
  timerVSync.setCompare(TIMER_CH4, startDraw);
  timerVSync.attachInterrupt(TIMER_CH4, EndVBackPorch);

  // Slave mode Gated, triggered by TIM3
  timerVSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_SMS);
  timerVSync.c_dev()->regs.adv->SMCR |= ((uint16_t)TIMER_SMCR_SMS_GATED);
  timerVSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_TS);
  timerVSync.c_dev()->regs.adv->SMCR |= (uint16_t)TIMER_SMCR_TS_ITR2;

  //nvic_irq_set_priority(NVIC_TIMER4, 1);

  timerVSync.refresh();
  timerVSync.resume();
}

void InitHSync(
  bool isNegative,
  int wholeLine,
  int syncPulse,
  int startDraw)
{
  HardwareTimer timerShockAbsorber(2);
  timerShockAbsorber.pause();
  timerShockAbsorber.setPrescaleFactor(1);
  timerShockAbsorber.setOverflow(wholeLine);

  timerShockAbsorber.setChannelMode(TIMER_CH1, TIMER_OUTPUT_COMPARE);
  timerShockAbsorber.setCompare(TIMER_CH1, 0);

  timerShockAbsorber.setChannelMode(TIMER_CH2, TIMER_OUTPUT_COMPARE);
  timerShockAbsorber.setCompare(TIMER_CH2, startDraw - 12);
  timerShockAbsorber.attachInterrupt(TIMER_CH2, ShockAbsorber);

  // Master mode, TIM_TRGOSource_Enable
  bitSet(timerShockAbsorber.c_dev()->regs.adv->SMCR, TIMER_SMCR_MSM_BIT);
  timerShockAbsorber.setMasterModeTrGo(TIMER_CR2_MMS_ENABLE);

  timerShockAbsorber.refresh();

  HardwareTimer timerHSync(3);
  timerHSync.pause();
  timerHSync.setPrescaleFactor(1);
  timerHSync.setOverflow(wholeLine);

  // HSYNC on pin PB0
  timer_oc_set_mode(timerHSync.c_dev(), TIMER_CH3,
            isNegative ? TIMER_OC_MODE_PWM_2 : TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
  timerHSync.setCompare(TIMER_CH3, syncPulse);

  timerHSync.setChannelMode(TIMER_CH4, TIMER_OUTPUT_COMPARE);
  timerHSync.setCompare(TIMER_CH4, startDraw);
  timerHSync.attachInterrupt(TIMER_CH4, Draw);

  // Slave mode Trigger, triggered by TIM2
  timerHSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_SMS);
  timerHSync.c_dev()->regs.adv->SMCR |= ((uint16_t)TIMER_SMCR_SMS_TRIGGER);
  timerHSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_TS);
  timerHSync.c_dev()->regs.adv->SMCR |= (uint16_t)TIMER_SMCR_TS_ITR1;

  // Master mode, TIM_TRGOSource_Update
  bitSet(timerHSync.c_dev()->regs.adv->SMCR, TIMER_SMCR_MSM_BIT);
  timerHSync.setMasterModeTrGo(TIMER_CR2_MMS_UPDATE);

  nvic_irq_set_priority(NVIC_TIMER3, 0);

  timerHSync.refresh();

  // Starts timerHSync as well
  timerShockAbsorber.resume();
}

void EndVBackPorch()
{
  vflag = 1;
}

void ShockAbsorber()
{
  // Wait for interrupt
  __asm__ volatile("wfi \n\t" :::);
}

void Draw()
{
  if (!vflag)
  {
    return;
  }

  noInterrupts();

  __asm__ volatile(

    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"

    :
    : [odr] "r"(GPIO_ODR)
    : "r0");

  interrupts();
}

You haven't said which Arduino you are using, which would help inform the answers.

I found a similar issue when I developed code to display on a VGA monitor.
The reason for the slight jitter is that when an interrupt fires, it can't stop in the middle of an instruction. So there are potentially one or two extra clock cycles before the interrupt is processed.
Those clock cycles would account for the slight jaggedness on the right. The way to avoid that is to go to sleep between horizontal lines (idle sleep mode). This wakes up instantly, but the important thing is it wakes up at the start of an instruction cycle, so you don't get a one or two cycle delay.
I can't see any sleeping in your code, and I'm not sure if your STM32F103C8 would compensate for that, but certainly it is worth trying.
I can't see a "main" loop, presumably it doesn't do much until an interrupt fires.
My main loop is this:
void loop()
  {
  // sleep to ensure we start up in a predictable way
  sleep_mode ();
  doOneScanLine ();
 }  // end of loop

Note the sleep which ensures that it starts the drawing at the same time each time (of course the interrupt will take time, but at least it takes the same time every scan line).

Thank you for your quick response! I will try your idea as soon as I get home.

I can't see any sleeping in your code, and I'm not sure if your STM32F103C8 would compensate for that, but certainly it is worth trying<< I am using "shock absorber" idea (on NVIC_TIMER3) as described here: http://cliffle.com/article/2015/06/11/matrix/.
I can't see a "main" loop, presumably it doesn't do much until an interrupt fires. << Sorry, missed it, it actually doesn't do anything

It must do something, or nothing would execute. Does it call some other function which loops? The main loop (or should I say, main function?) is where code starts executing.

I updated the source, added empty loop. It is empty because everything happens in the interrupts. There are 3 interrupts: EndVBackPorch - updates "vertical" flag; ShockAbsorber - happens a little before Draw, its goal to reduce random delays; and Draw - that draws horizontal line (in this example, just 6 "dots"). Each "dot" is actually at least 2 real "dots", however my resolution is 256, and real resolution is 640, so it is OK.

The objective is to be sleeping before the interrupt occurs so that the interrupt wakes in a predictable way.


text:
#include<ESP8266WiFi.h> showing error message
i was trying to send some data to a webpage via esp8266wifi module connected to arduino uno. My sketch contains a header file .After searching online I could get the library Arduino-master.zip from github. I extracted the files and put it in inside the directory arduino->hardware->arduino->avr->libraries.but even then it was showing me the error message like this:

 fatal error: ESP8266WiFi.h: No such file or directory

 #include

                         ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

How can I remove this error. please refrain from technical words as i am new to this language. Thank you.
EDIT: After adding esp8266WiFi.h in the library i got out from that error message .But it showed me a new one

C:\Program Files (x86)\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

I dont know how to come out of this error. some websites give a solution but it didn't worked for me.

That library is part of the ESP8266 core. It's not for the Arduino, but for programming the ESP8266 as a standalone unit without an Arduino connected to it.

ESP8266WiFi part of the project Arduino Core here: https://github.com/esp8266/Arduino Arduino Core provides support for the ESP8266 to be used with Arduino IDE through the boards manager facility. So its libraries are for the ESP8266 not the Uno.
If you are interested in communicating with the ESP8266 over serial using its AT+ command firmware then you just send them as strings over serial.
Serial1.println("AT+GMR");
while(Serial1.available() == 0) {
  delay(1);
}
while(Serial1.available() > 0) {
  Serial.write(Serial1.read());
}

That's a terrible serial routine there...

@Majenko It's an example. Edit in a better one if you want.


text:
Wemos D1 won't work with MH-Z19B (CO2 sensor)
I would like to connect a CO2 sensor to the Wemos D1. I would like it to work via UART (RX, TX) and not the PWM pin. I've encountered numerous libraries on Github, but I can't seem to get it working. I've connected the following things:

I've tried a lot of snippets from all over the internet, and a lot of libraries on Github, but I can't seem to get it working. For the sake of this question, I am going to use this advanced library.
This is my code:
#include <Arduino.h>
#include "MHZ19.h"                                         // include main library
#include <SoftwareSerial.h>                                // Remove if using HardwareSerial or non-uno library compatable device

#define RX_PIN D1                                          // Rx pin which the MHZ19 Tx pin is attached to
#define TX_PIN D2                                          // Tx pin which the MHZ19 Rx pin is attached to
#define BAUDRATE 9600                                      // Native to the sensor (do not change)

MHZ19 myMHZ19;                                             // Constructor for MH-Z19 class
SoftwareSerial mySerial(RX_PIN, TX_PIN);                   // Uno example
//HardwareSerial mySerial(1);                              // ESP32 Example

unsigned long getDataTimer = 0;                             // Variable to store timer interval

void setup()
{
    Serial.begin(9600);                                     // For ESP32 baudarte is 115200 etc.
    mySerial.begin(BAUDRATE);                               // Uno example: Begin Stream with MHZ19 baudrate
    //mySerial.begin(BAUDRATE, SERIAL_8N1, RX_PIN, TX_PIN); // ESP32 Example
    myMHZ19.begin(mySerial);                                // *Important, Pass your Stream reference
    myMHZ19.autoCalibration();                              // Turn auto calibration ON (disable with autoCalibration(false))
}

void loop(){
    if (millis() - getDataTimer >= 2000)                    // Check if interval has elapsed (non-blocking delay() equivilant)
    {
        int CO2;                                            // Buffer for CO2

        /* note: getCO2() default is command "CO2 Unlimited". This returns the correct CO2 reading even
        if below background CO2 levels or above range (useful to validate sensor). You can use the
        usual documented command with getCO2(false) */

        CO2 = myMHZ19.getCO2();                             // Request CO2 (as ppm)
        Serial.print("CO2 (ppm): ");
        Serial.println(CO2);

        int8_t Temp;                                         // Buffer for temperature
        Temp = myMHZ19.getTemperature();                     // Request Temperature (as Celsius)
        Serial.print("Temperature (C): ");
        Serial.println(Temp);

        getDataTimer = millis();                            // Update interval
    }
}

I am constantly getting this:
19:39:59.750 -> !Error: Timed out waiting for response
19:39:59.784 -> !ERROR: Failed to verify connection(1) to sensor. Failed to stablise
19:39:59.853 -> !ERROR: Initial communication errorCode recieved
19:40:00.272 -> !Error: Timed out waiting for response
19:40:00.758 -> !Error: Timed out waiting for response
19:40:00.792 -> CO2 (ppm): 0
19:40:01.280 -> !Error: Timed out waiting for response
19:40:01.315 -> Temperature (C): -17

Am I connecting something wrong or what am I doing wrong?
EDIT:
Version using only the serial instead of library that also doesn't work:
#include <SoftwareSerial.h>
SoftwareSerial co2Serial(3, 1);
unsigned long startTime = millis();

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

void loop() {
  Serial.println("------------------------------");
  Serial.print("Time from start: ");
  Serial.print((millis() - startTime) / 1000);
  Serial.println(" s");
  int ppm_uart = readCO2UART();
  delay(5000);
}

int readCO2UART(){
  byte cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
  byte response[9]; // for answer

  Serial.println("Sending CO2 request...");
  co2Serial.write(cmd, 9); //request PPM CO2

  // clear the buffer
  memset(response, 0, 9);
  int i = 0;
  while (co2Serial.available() == 0) {
    Serial.print("Waiting for response ");
    Serial.print(i);
    Serial.println(" s");
    delay(1000);
    i++;
  }

  if (co2Serial.available() > 0) {
      co2Serial.readBytes(response, 9);
  }

  // print out the response in hexa
  for (int i = 0; i < 9; i++) {
    Serial.print(String(response[i], HEX));
    Serial.print("   ");
  }
  Serial.println("");

  // checksum
  byte check = getCheckSum(response);
  if (response[8] != check) {
    Serial.println("Checksum not OK!");
    Serial.print("Received: ");
    Serial.println(response[8]);
    Serial.print("Should be: ");
    Serial.println(check);
  }

  // ppm
  int ppm_uart = 256 * (int)response[2] + response[3];
  Serial.print("PPM UART: ");
  Serial.println(ppm_uart);

  // temp
  byte temp = response[4] - 40;
  Serial.print("Temperature? ");
  Serial.println(temp);

  // status
  byte status = response[5];
  Serial.print("Status? ");
  Serial.println(status);
  if (status == 0x40) {
    Serial.println("Status OK");
  }

  return ppm_uart;
}

byte getCheckSum(byte *packet) {
  byte i;
  unsigned char checksum = 0;
  for (i = 1; i < 8; i++) {
    checksum += packet[i];
  }
  checksum = 0xff - checksum;
  checksum += 1;
  return checksum;
}

You do know you need to cross RX and TX with UART communications, don't you?  TX connects to RX, and RX connects to TX.

I know, tried it both ways (drew it wrong in this picture), neither works

did you try to send the commands without using a MHZ19 library?

Yes, also no response, see the edit

I know it is rather late to respond. What worked for me working with a WEMOS D1 mini and  the MH-Z19C was reassigning the Software Pins used SoftwareSerial co2Serial(D1, D2);
In that case the second sketch posted works atleast for me.
The problem might be that the ESP8266 uses the hardware serial lines for connection to the USB-to-Serial bridge (usually a CH340 or CP2102 in most designs) which means you might encounter problems if you want to use the same serial line for more than one device.

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


text:
Output 3.3V when setting pin to high
I would like to pass 3.3V and Ground to an component. How can I achieve such a thing?
I for example would like to let a wire get 3.3V when I for example do digitalWrite(pin, HIGH). It is hard for me to explain this, so I created an illustration in the hope of better clarifying it.
Edit: I have an product that I have dismantled. On the PCB, there is a push button. I would like to solder some wires to the place where the button is so it can be controlled with an arduino (probably wemos d1). When plugging a cable in the 3.3v of the arduino and a cable from the ground, when connecting it to the push button it will cause a boot of the dismantled product. This explains why I would like to give power to a component ONLY when a pin is set high, so I can for example boot the product via a website / app eventually.

Are you trying to supply "power" to a component or just send a "low current" HIGH/LOW signal?

Supply power (3.3v) when a pin is set to high

How much power? 1 mA, 10mA, 500mA?

What is this mystery component?

Doesn't really matter, connecting the 3.3V directly to the component will already work so I guess it won't be too much

I've clarified it a bit more in the edit, sorry for the confusion @Majenko

The normal way is to use a P-channel MOSFET as a "high side" switch.

simulate this circuit – Schematic created using CircuitLab
R1 keeps it switched off under "normal" circumstances.  Driving D4 LOW makes M1 turn on and allow power through to the "component".
Make sure that the MOSFET has a threshold voltage of no more than (less than?) -3V (that is, somewhere between 0V and -3V - note: P-channel MOSFETs have their thresholds quoted as a negative voltage).
You could connect R1 to 3.3V instead of 5V, but since the  GPIO would have 5V on it when HIGH it would be wasting power while idling - so it's better to pull it to 5V instead.

I think I have kind of used the same principle as you described. I simply put a transistor between it, did some configuring and it worked. Thank you for the right answer and the help in the right direction!


text:
millis() function with a button press
I am trying to use the millis() function to turn on a pin for a specified interval then turn off and turn on a second pin. It is intended to power a relay and offer a visual cue to when the cycle is over. Several of these need to eventually be running, most likely three, so using delay() won't work. I plan to add additional "button pins" for each input. The LED lights up but gets stuck in the loop and doesn't cycle out. It seemed like a simple program but I can't crack it for some reason.
Is there a much better method to do this? There will be two optical sensors and one pushbutton switch attached to an air driven crushing machine. The two optical sensors will be used only as time indicators with LEDs and the pushbutton will power the relay. Forgive my shortcomings as a programmer, I am learning the programming language still.
const int ledPin =  2;      // the number of the LED pin
const int buttonPin = 3;    // Button pin number
// Variables will change:
long previousMillis = 0;        // will store last time LED was updated
int buttonState = 0;            // Checks if button is pushed
int buttonPush = 0;             // Toggles between 0 to hold state
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
// set the digital pin as output:
   pinMode(ledPin, OUTPUT);
   pinMode(buttonPin, INPUT);
}
void loop()
{
   unsigned long currentMillis = millis();
   buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH) {
      buttonPush = 1;
      if (buttonPush == 1){
         if(currentMillis - previousMillis > interval) {
            previousMillis = millis();
            digitalWrite(ledPin, HIGH);
         }
         else {
            buttonPush = 0;
         }
      }
      else {
         digitalWrite(ledPin, LOW);
      }
   }
}

Edit: Thank you for looking over the code, you guys are awesome. There were a couple questions regarding clarity of the final application so I will elaborate. I am going to attempt to clean it up. I had a feeling something was wrong with:
if (buttonState == HIGH) {
   buttonPush = 1;

but I couldn't put my finger on it.
Eventually the system will function with two heating elements to soften plastic, which I will either add an optical sensor to since it will probably get triggered a few hundred times a day, or just a pushbutton to start a timer so the plastic isn't left in too long. A green LED will be illuminated to indicate the system is on. When the plastic object is placed in the heating element it triggers the optical sensor (or the operator pushes a pushbutton to start the timer) that will then illuminate a red LED to indicate heating. When the specified time interval has expired, the LED will revert back to green to show the cycle is complete. The plastic object is then removed and placed in a pneumatic crushing device with a green system on LED. The operator then pushes a pushbutton which turns on a red indicator LED and a relay to power the solenoid on the pneumatic press for a specified amount of time to allow the plastic to cool and crystallise. When that interval has expired, the system will revert back to illuminating the green LED and will end power to the relay allowing the press to release.
The pneumatic press and the heating system works awesome, I just need better control of the time intervals used. The end result needs to be consistent.
I am going to try all suggestions and will post what ended up working if I reach that point or find an answer that functions.

An overall word specification or just maybe simple pseudo code will help us see exactly how this is intended to work and help you visualise what needs doing where. You have right general ideas and millis() is gpoing to do what you want. Just needs tidying.

Some code is shown below to illustrate a method for treating three events independently.
This code might not be completely applicable as-is, because the problem description isn't clear about what should happen when a button is pressed and about whether other events to be added to the code are like the one shown there now.  However, if you understand how it works you probably can adjust it to meet any special requirements of your application.
During each pass through the loop() routine, the code does the following for each type of event:

If the event is not currently active (as denoted by states[i] < debounced), the code checks whether the event's button has been pressed (or, if its sensor has turned on).  If so, the code increments a debounce counter.  If the event's counter gets up to debounced, then the output for the event is turned on, and the event's end-time is stored in an array entry.
If the event is currently active (as denoted by states[i] >= debounced), the code tests if the event's end-time has arrived; if so, it turns off the event's output bit and resets its state to 0.

The last statement in loop() busy-waits until milliseconds() returns a different value than before.  This is done so that switch-debouncing samples are taken at least a millisecond apart.  If your inputs don't need debouncing, you can remove debounce code .
/* Process three asynchronous activities: Upon a given input going
true, activate its associated output(s) for specified lengths of time.
*/

enum { nkinds=3, debounced=5 }; // # of activity kinds;  debounce-criterion
const byte outPins[nkinds] = {2, 4, 6}; // Output pin numbers
const byte inPins[nkinds]  = {3, 5, 7}; // Input pin numbers
const unsigned int actLens[nkinds] = {345, 678, 323}; // Activity lengths, ms
byte states[nkinds] = {0, 0, 0};
unsigned long actEnds[nkinds] = {0, 0, 0};

void setup() {
// Set input/output modes of pins
  for (byte i=0; i<nkinds; ++i) {
    pinMode(outPins[i], OUTPUT);
    pinMode(inPins[i], INPUT);
  }
}

// Once per millisecond, for each kind of activity
// check for new beginning or deal with ongoing action
void loop() {
  unsigned long now = millis();
  for (byte i=0; i<nkinds; ++i) {
    if (states[i] < debounced) {  // Is activity off?
      // It's off, look for a turnon
      if (digitalRead(inPins[i])) {
        ++states[i];        // Button is closed at the moment
        // See if button has been debounced
        if (states[i] >= debounced) { // If so, start its action
          digitalWrite(outPins[i], HIGH);
          actEnds[i] = now + actLens[i];
        }
      }
      else {
        states[i] = 0;      // Button is not closed at moment
      }
    }
    else { // It's on, see if end-time has arrived
      if (now >= actEnds[i]) {
        digitalWrite(outPins[i], LOW); // Clear output when done
        states[i] = 0;        // Return to button-seeking state
      }
    }
  }
  while (now == millis()) {};       // Finish current millisecond
}

The code above compiles ok in the Arduino IDE but I haven't tested it on an Arduino device.
Note, larger systems with numerous events will use priority queues to implement lower-overhead versions of the same ideas.

To create a behavior of toggling between two inputs, for example, LED 1 is on and when a button is pressed LED 1 turns off and LED 2 turns on for a specified amount of time then turns off and LED 1 turns on until the button is pressed again, I could specify a second set of outputs to then be able to toggle between the two correct? I am trying to wrap my head around how the code you posted works so I can understand the structure.

My apologies, when I first breadboarded the circuit I accidentally jumpered the pushbuttons which gave me a constant "on". This sketch works well. I am going to set up "outPinsB" and toggle their state on at the point where "outPins" are turned off.

Yes, you can specify sets of other output pins for follow-on actions.  If you need more states and additional time delays, you can add if statements after the last else and detect state values like debounced, debounced+1, etc.

The direct answer to your first question (LED gets stuck) after formatting and summarizing a section of your code:
  buttonPush = 1;
  if (buttonPush == 1){
     ...
  }
  else {
     digitalWrite(ledPin, LOW);
  }

is that there's a logic error. You can see that the else clause, turning off the LED, will never be executed because buttonPush is always 1 before you enter this section. I think this is the point @RussellMcMahon was trying to make.
The answer to your second question, needing several of these running at once, is: Get the first one to work first. Then simplify it as much as you can. Then you can choose between using polling loop (repeatedly reading the clock and deciding whether it's time to do something) or setting interrupts (making the clock interrupt your main program to run the routine that does the "something").

I'm surprised that my statement "When the button is first pressed you set buttonPush and then immediately test to see if it is set. As it always is the LED never gets turned off as the "else" condition is never met." is not considered clear.  | 'Getting the first one running' is good advice. However, having done so he can extend the principle with relative ease - there is no need to eg alter how clock interrupts are used etc.  ie N routines can independently test whether eg: " ( millis() - lastMillisN) > delayN )" and act accordingly. Doing multiple such comparisons with eg case() would work.

I agree, I was trying to keep it simple, I guess I was thinking that the "else { buttonPush = 0;} would reset the state after the "interval" had run out. It may be overcomplicating it? I guess I have a misunderstanding as to how the loop exits an if statement if the condition isn't met. It was an attempt to toggle the state of that button and as @RussellMcMahon had mentioned, then adding additional ones. I know it will all click in my head as to how the codes function, but the gears upstairs are a little rusty.

The simplest way I can think of is something like this:
unsigned long lastPress = 0;
unsigned long stateOneTime = 2000; //runs until two seconds elapse
unsigned long stateTwoTime = 4000; //runs after state one until 4 seconds from first press
...
if(/*input is active*/) lastPress = millis();
...
if(millis() - lastPress < stateOneTime){
    //set output for first state
    //active for 2 seconds
} else if (millis() - lastPress < stateTwoTime){
    //set output for second state
    //active an additional 2 seconds
} else {
    //set output to the "off" state
}

Many improvments could be made, like going more of a state machine route (separating the time checks from the branches) or paramaterizing the state lengths better (durations would make more sense than total time from start, but be slightly more complicated to code).
I think the key to making your life easier while working on this code will be separating the input segment from the output segment. It will help keep the code easy to read and modular.

Summary:
A fatal problem is caused by the two lines of code below.
A variable is set and then the same variable is immediately tested to see if it is set.  This means that the IF test always passes and the ELSE never happens.
As the LED is cleared only when the else occurs, the LED stays lit.
Code:

  buttonPush = 1;
  if (buttonPush == 1){ ...

When the button is pressed you set buttonPush and then immediately test to see if it is set.
As it always is set, the LED never gets turned off as the "else" condition is never met.
Even when that is fixed you have other issues.
I suggest that "expanding" the code along the lines I have shown in (3) below will help you immensely with visualising what your code does.
There are a large number of editors which handle this task in various ways, but just plain tabbing and white space with a basic editor helps muchly.

It seems almost certain that your code will NOT do what you intend when it does work "properly", but there are several issues below that need addressing (one fatal, others less so) - see "ISSUES" below.
Apart from those issues, it's not 100% clear how this is intended to be used.
Options include:

Switch is pressed and released quickly (say 100 mS) - LED lights for one second and then goes out.
Switch is pressed and held - LED lights for one second then turns off even when switch is held on.
Other variants are possible.

At present it will not do any of these.

ISSUES:
(1) You have assigned

long previousMillis = 0;

This should be

unsigned long previousMillis = 0;

Mixing the two types gives an uncertain result. At best, an error will occur when the value returned by millis() exceeds the length of a "long" data type and when types are mixed there is no guarantee that the result will be valid.

(2) I have not checked it, but I'd be wary of the line

if(currentMillis - previousMillis > interval)

as it depend on operator precedence of the "-" being implemented prior to the ">" comparison.
ie this could potentially evaluate as either
" (A-B) > C " .... which is what you intend,
or
" A - (B > C) " .... which, while it is not what is intended, does have a valid if not useful result.
You can rely on operator precedence if you have confidence in yourself and the system or make it explicit as in eg

if( (currentMillis - previousMillis) > interval)

Making things easier for yourself:
This has been edited to match my main conclusion which was already covered above (the problem was not nesting but a test that can never fail - as covered above) but the formatting  comments are relevant.
Your code is written in a standard (or usual) manner. Some are able to handle such without problem, but I (and many others) find such layout hard to read and, importantly, easy to bury errors in. The following is overdone - I used existing tabs and expanded it in Word :-) - but to me the following makes it immensely more readable. Layout and style are a matter of personal preference, and there are many opinions re what is "best", but something which allows ease of visualisation of program structure is liable to be useful.
The two adjacent lines

  buttonPush = 1;
  if (buttonPush == 1){ ...

are logically grouped together when indented like this at make it clearer that the "set then test"   arrangement can never fail so the subsequent "else" where the LED is turned off is never implemented. So the LED must stay on.

buttonPush = 0; is bolded for unrelated reasons.

previousMillis = millis(); should be changed to previousMillis = currentMillis;

@portforwardpodcast - arguably yes - what I show is his original code. As millis() increments at 1 ms intervals, in most systems currentMillis() and millis() will be identical as the time taken from the timer read at the top of the loop to this point will take << 1 mS.(You can be unlucky and have the timer roll over in the few uS involved.) BUT in a system with user interrupts running and heavy background load millis() and currentMillis() may be different. Even then the result is that there is an extra delay in the next timeout equal to the time spent in the interrupt routine.

All of what you said in your comment points to not calling millis() a second time

@portforwardpodcast AGAIN :-) arguably yes. But also, possibly no. It looks in this case as if the decision process is uncertain enough that the differences are not part of the process. But in some cases there may be reasons to do as is done here for overall reasons. Again, I agree with you that that's probably not the case here - we have not yet even got a functionally fully designed system, but just maybe .... :-)

I am gently astounded that this received two downvotes and 0 upvotes. A downvote is meant to indicate "not useful". | The answer explicitly identified the main current problem - the test for buttonPress when buttonPress is always = 1. That seems useful :-). | The answer identifies a millis() variable related type mismatch which will cause random operation. That seems useful. | And a code line that relies on operator precedence when subtraction and comparison are mixed [ if(currentMillis - previousMillis > interval) ] - that is probably useful.  ...

... Reasons for downvoting do not have to be given. But not doing so in cases like this is unlikely to be useful to the original poster - or to encourage other people to spend the time needed to give quality answers.

I had a feeling that it was getting stuck when I toggled on the buttonPush. I am cleaning up the code to see if I can fix it. I will try to format it better as well. I agree it is a lot easier to see what is happening when it is formatted better than my first attempt.


text:
Which library to choose? <Wire.h> or "Wire.h"?
I know that in C++, to include a library, you either put the library name in <x> or "x". Now, I believe that this was because of a major change in the C++ language a some time ago.
Now, in Arduino, there are 2 types of Wire (I2C) library : <Wire.h> and "Wire.h".
Which one is the right one?
I've seem people using both, and they both seem to work.

The proper distinction is exactly what paths are searched for the include files.
<...> searches the "system" paths, while "..." searches both the system an "local" paths.
From the GCC manual:

-I dir
Add the directory dir to the list of directories to be searched for header files.  Directories named by -I are searched before the standard system include directories. If the directory dir is a standard system include directory, the option is ignored to ensure that the default search order for system directories and the special treatment of system headers are not defeated .  If dir begins with =, then the = will be replaced by the sysroot prefix; see --sysroot and -isysroot.
-iquote dir
Search dir only for header files requested with #include "file"; they are not searched for #include <file>, before all directories specified by -I and before the standard system directories.  If dir begins with =, then the = will be replaced by the sysroot prefix; see --sysroot and -isysroot.

Note that the Arduino IDE only uses -I, so there is little to no distinction between <...> and "...".
Commonly the main usage of the distinction is to use <...> to include system or library headers, and "..." to include headers that are part of the actual sketch / application, since the "current directory" is automatically added as a local include path.

So both "Wire.h" and <Wire.h> would work?

Yep. I commonly see both being used, though I for one only ever use <Wire.h>.

Specifically, "file.h" searches the directory containing the current file first. Thus, "file.h" would work for both, finding your local version of file.h before searching the library. However I write "file.h" or <file.h> to explicitly specify - to the reader - which one I mean to include. See [this page describing the gnu compiler's "include" syntax]{https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html)

http://en.cppreference.com/w/cpp/preprocessor/include
#include <filename>

The intent of this syntax is to search for the files under control of the implementation. Typical implementations search only standard include directories. The standard C++ library and the standard C library are implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options.

#include "filename"

The intent of this syntax is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides and, only if the file is not found, search the standard include directories as with (1).

So basically it's intent is to give some idea of where the file should be.
I, myself use "" for files that are inside the directory of my program. And <> for files or libraries that are in my path or other external locations.

This question is also more related to programming in general as Arduino specific.
Also see:
https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename


text:
ATtiny85 AC Phase Control for dimming a light bulb
I'm trying to dim a light bulb via an ATtiny85, which accepts commands sent over I2C. My problem is that the bulb is barely dimming and is flickering quite a bit.
My circuit can be seen here:

The opto-isolator (and thus the triac) is controlled via pin 2 (AKA PB3, AKA PCINT3) and AC zero cross detection is done on pin 3 (AKA PB4, AKA PCINT4) on the ATtiny85.
The code uses Pin Change Interrupt Enable rather than the single External Interrupt Enable, because the External Interrupt pin is pin 7 (aka PB2), which is used as the SCL for the I2C communication.
The 8MHz internal clock is used and the timer/counter prescaler is 1024, which means that I have an effective input range (see level variable in the code) of roughly 0-65. My AC source is USA (60Hz).
#include <avr/interrupt.h>
#include <avr/io.h>
#include <TinyWireS.h>

#define PULSE 4       //trigger pulse width (counts)
#define I2C_SLAVE_ADDR 0x4 // the 7-bit address (remember to change this when adapting this example)

byte trigger = 3;
byte detector = 4;
byte level = 50;
byte maxLevel = 65;
byte minLevel = 0;

void setup() {
    TinyWireS.begin(I2C_SLAVE_ADDR); // join i2c network
    TinyWireS.onRequest(requestEvent); //setup i2c requester
    digitalWrite(detector, HIGH);  //enable pull-up resistor
    pinMode(trigger, OUTPUT);// Set AC Load pin as output
    TCCR1 = 0;     //stop timer
    OCR1A = level;    //initialize the comparator
    TIMSK = _BV(OCIE1A) | _BV(TOIE1); //interrupt on Compare Match A and  enable timer overflow interrupt
    GIMSK = 0b00100000; //Enable pin change interrupt
    PCMSK = 0b00010000; //PB4, physical pin 3 PCINT4
    TCCR1 = B00001011; //Prescale the timer
    sei();  // Turn on interrupts
}

ISR(PCINT0_vect) {
    //interrupt looking for zero crossing
    TCNT1 = 0;   //reset timer - count from zero
    OCR1A = level;
    TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
}
ISR(TIMER1_COMPA_vect) {
    //comparator match
    digitalWrite(trigger,HIGH); //set triac gate to high
    TCNT1 = 255-PULSE;
    //trigger pulse width for a few cycles for triac to latch on. 255 bc the counter can only count up to 255
}

ISR(TIMER1_OVF_vect) {
    //timer1 overflow
    digitalWrite(trigger, LOW); //turn off triac gate
    TCCR1 = 0;  //disable timer stop unintended triggers
}

void loop() {}

void requestEvent() {
    if (TinyWireS.available()) {
        level = TinyWireS.receive();
        if (level > maxLevel) {
            level = maxLevel;
         else if (level < minLevel){
            level = minLevel;
        }
    }
    TinyWireS.send(OCR1A);
}

I have tried a variety of bulbs (incandescent and dimmable LED), with none working any better than another.
Here is a video showing the zero cross detection (yellow) and the ATtiny85 trigger (blue) on an oscilloscope as I send it different dimming levels Bad phone video
I've thought about the snubber, I just don't have the parts on hand right now. I think it will help but I don't think it will correct whatever my larger issue is.
I'd appreciate all and any help. Thanks.
(Note: I also posted this here. Apologies if crossposting is frowned upon).

Are you able to turn the bulb off? Maybe the signal needs to be inverted. The triac circuit looks very minimal to me, but I'm not that into triacs.

Sending the max level does turn it off... But I don't know if it actually doing it the way I want it to.
Hmm What do you mean the signal needs to be inverted?
I was inspired by this

I meant a normally high signal with a short LOW pulse. So the blue trace upside down. But I'm just guessing here.

Are you sure about 47k R1 to the optotriac? Trigger current is 15mA for the MOC3021 and you have less than 0.1mA (with 5V power supply)

It's 0.47K. Poor picture quality . And using a 330ohm doesn't fix anything.

@thread9000 well, it should be about 220R on 5V. It's better to measure it.

Thanks @KIIV  but it still doesn't change the result. Any other thoughts?

This is really an electronics question not an Arduino one, especially as you are configuring the ATtiny hardware directly and not really going through the Arduino framework in more than the most trivial sense.  The snubber situation really can't be ignored.  Ultimately what you need to see is the behavior of the triac, but trying to measure that with a scope has too many dangerous pitfalls to recommend.  Are you sure you need to build this yourself?  It can be done, but it's not something to play with unless you really understand what is going on and how to do it safely.

@Gerben the circuit appears to be driving the Anode of the opto-triac device, so it would be an active high pulse to turn on the triac.   A typical dimmer like this achieves PWM by delaying some time after zero crossing before turning on the TRIAC, which will then remain on (regardless of input) until it shuts itself off at the next zero crossing.

Hi @ChrisStratton. The reason I am posting it here was to verify my code, which is very much using the Arduino API. Any electrical help and verification is a bonus, so I appreciate your input.
I'm currently waiting on a triac with a built-in snubber to be delivered.
I agree it would be nice to see out triac's output. I will reach out to an electrical engineer that I work with.

So I think there were (was?) two issues.
1) Pin change interrupts on the Attiny85 are triggered on rising and falling edges which I think was causing the flickering.
I changed the code to rising edge only triggering:
ISR(PCINT0_vect){ //interrupt looking for zero crossing
        if (digitalRead(4) == HIGH){
                TCNT1 = 0;   //reset timer - count from zero
                OCR1A = level;
                TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
       }
}

2) Attiny85 #reset pin. Pulled that guy high with a resistor.
Anyways, here's the oscilloscope and dimming led blub video: youtube

Also, I switched to BTB08-600BWRG for the triac which helps with inductance (so far I've got five (65watt eq) LED light bulbs running just fine). (Note this didn't actually do anything the solve the original problem)


text:
RF433MhZ - PWM with a motor driver freezes the code
LE: I'm almost certain that the problem is noise from the DC motor. I tried with a spare motor laying around and it had no problem, even if it had no capacitor on it's leads. So I tried adding all kinds of capacitors on the present motors, no improvement. I guess I'll search for another wireless solution.
So I want to build a remote controlled car using a cheap 433MhZ receiver and transmitter. I am using this motor driver. I send the values from the joystick to the receiver and based on that I control the motor's direction. The problem is that when I use PWM (or digitalWrite) the receive data code completely freezes (my guess is receiver fault). Other code in the program works so the only problem is in the communication department. I don't think it's a software problem because when I pull out the PWM pin to the motor driver, code starts running again.
I tried with another driver (TB6612FNG), I tried another receiver, I tried another library for 433MhZ (VirtualWire), I tried using SoftPWM library, I tried using a 220 Ohm resistor in series with the PWM signal, nothing works. I put a LED on the PWM pin, no problem.
I'm using two 3.7V lithium batteries as power. The receiver gets 5V directly from arduino. I also tried using a voltage divider to power the receiver directly from the batteries.
Here's the code, it's the last version that uses RCSwitch library for comms, I send the values from the joystick as 8 byte, read the respective bits and based on them I control the motors. Now it has a workaround that if the receive code is not in use, after a period it stops the motors, gets the data, starts motors again, but this is not acceptable.

#include

RCSwitch mySwitch = RCSwitch();

bool up1, down1;
byte recData;

int AIN1 = 10;
int AIN2 = 9;
int BIN1 = 5;
int BIN2 = 6;
unsigned long resetTime;
unsigned long period = 3000;

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
    pinMode(AIN1, OUTPUT);
    pinMode(BIN1, OUTPUT);
    pinMode(AIN2, OUTPUT);
    pinMode(BIN2, OUTPUT);
}

void loop() {
      resetTime++;
  if (mySwitch.available()) {
    recData = mySwitch.getReceivedValue();
    Serial.println("Received ");
    mySwitch.resetAvailable();
    resetTime = 0;
  }
  if (resetTime > period)
      recData = 0;
   up1 = bitRead(recData, 7);
   down1 = bitRead(recData, 6);
  /*Serial.print(currentMillis);
  Serial.print("  ");
  Serial.print(recData);
  Serial.print("  ");
  Serial.print(up1);
  Serial.print("  ");
  Serial.println(down1);*/
  if (up1) {
      analogWrite(AIN1, 255);
      analogWrite(AIN2, 0);
      analogWrite(BIN1, 255);
      analogWrite(BIN2, 0);
    }
    else if (down1) {
      analogWrite(AIN1, 0);
      analogWrite(AIN2, 255);
      analogWrite(BIN1, 0);
      analogWrite(BIN2, 255);
    }
    else {
      analogWrite(AIN1, 0);
      analogWrite(AIN2, 0);
      analogWrite(BIN1, 0);
      analogWrite(BIN2, 0);
    }

}

perhaps the motor is generating too much RF interference

Yes, I suspected that too. The RC car is a cheap chinese, but the motors have some capacitors on them. Anyway  I ordered some nRF24L01 hoping that 2.4GhZ and spi communication will solve the problem.


text:
A4988 and capacitors
I’m working at a project which involves 3 stepper motors that are driven by A4988 drivers. I have read that I have to connect an 100uf capacitor in parallel with the motor power supply that goes to the driver, but do I have to use a capacitor for every driver, or only 1 capacitor because the drivers are connected in parallel to the same 12v power supply.

I saw the scematic

I saw the schematic in an instructable, it explained why he uses it, but it was only for one stepper

Yoiu have missed to post the url to  what you refere to!

There are two purposes of such capacitor:

first it supply power for short peaks in demand, so effectively enabling the 12V power source supply much more current for short time, than it can support over long time and so the driver have more stable power and works generally better. Also it protects the driver from noise of other parts.
the other is protect all other parts from voltage drops and noise caused by the driver. It is recomended to have capacitors as near as possible to any IC/driven circuit for this reason.

So basically - if you have good power source, you can often get away even without such capacitors. But if you power also logic from the same source, it is already better to have some capacitors on power lines where posssible. Escpecially if you expect some noise around (like having motors near or lines to motors in paralel with other lines ...). Depends how much you care and how critical you see the project. Hobby project just for fun can go even without capacitors and be all good. Good industry projects have capacitors always everywhere.
I had project, where it worked even without capacitors (laser printer), but now I would place some there in any case near each driver, just to be sure. 100uF is really good capacity, enables for lot power. But if you use any other value (which you have more ready), it should not hurt too. It is not about if it would work or not, it is more about if it ensures, that it would work flawlessly even in bad conditions even under unexpected conditions and would not have "sometimes strange problems, which disapear spontaneously during debugging".
Also note, that for improving power are good high capacity electrolytes. For preventing noise are much better ceramic (which are fast, even if they have a lot smaler capacity) and so many people put both there (like 100uF electrolyte and 100nF ceramic in paralel).
Short answer: Do as you want, it would probably work anyway. I personally would place big+small capacitors near each driver.

Thanks for your detailed answer, it clarified my problem.


text:
How can I drive this LCD TFT with an Arduino?
As I understand it, the Arduino comes with a TFT library which uses SPI to drive LCD TFTs. I recently bought a TFT labelled "HY-32.TFT" on the front and "HY-TFT320_262k heyaodz111211" on the back.
It uses an XPT2046 touch screen controller, but I'm more interested in just getting something on the screen currently.
To use the Arduino library, I need to connect pins:

SCLK
MOSI
CS
DC
RESET

But I can't see these apart from some similarly named ones associated with TP (touchpad?) and SD (sd card), as the photo shows:

Is it possible to drive this with my Arduino? If so, how?
UPDATE: It looks like the datasheet for the controller and the board can be downloaded from 3.0" 3" TFT LCD Module Display + Touch Panel + PCB adapter.

http://www.geeetech.com/wiki/index.php/3.2TFT_LCD

From what I'm seeing, the touch screen and card reader use SPI but the LCD uses a bunch of Digital I/O lines. The link in Gerben's comment includes a library for the LCD that might be what you're looking for. I hope you're using a ATMega board as it doesn't look like an Uno or similar board will have enough I/O for the LCD.

If you search for "arduino lcd tft shield" on ebay you should if a few shields for your kind of lcd. But all of them require an Arduino MEGA (or DUE).
You could also use some kind of a shift register to drive this lcd with an Arduino UNO (or other small boards).


text:
Arduino GSM Shield not responding?
I'm trying to get my Arduino GSM shield working with the example "Send SMS" code provided. However, when I upload and compile the program, the serial monitor displays "SMS Messages Sender" and nothing else occurs.
Would greatly appreciate it if someone can tell me where I could have gone wrong.
EDIT : I'm currently using the Arduino Mega. The shield I'm using is the Arduino GSM Shield. I'm following the guide provided by the Arduino's website with the code part of the example that comes with the Arduino program, see Sending a SMS message. Attached is what is shown on the monitor.
I am using both a USB cable and an external power supply. I have performed the jumper wire modification required for the Mega to work with the shield as well.

Could you provide some more information please? It might be useful to have details of exactly which Arduino board and shield you're using, and what code you're trying to run.

Please, also add the code you have uploaded to your MEGA, rather than just saying "the code provided"; try to ease the job of people who want to help you, thus give a chance to your question of being answered!

This is an old post, but for future people:
The shield may have not been switched on — it has its own power button, which is right next to the SIM card. It's tiny, but it's there.


text:
Read car high temperature exhaust pressure sensor
Is it possible to read the exhaust gas pressure of a turbo car with an Arduino, and then control an electric motor based on the pressure?

Probably.  Might be simpler if you could either install a second sensor to use independently, or tap into the CAN or OBD and get the readings that way.  Finding specs on the sensor would be key; is there perhaps a group of car people who hack on those habitually?  Or re-apply them to model aircraft turbines or something like that?

Yes.

Yes, I don't see why it wouldn't be possible.
You would need a sturdy barometer, preferably a digital I2C one because they are typically more accurate. I recently bought this one to measure altitude: BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready.
Be careful about the temperature that the sensor will have to deal with, its maximum temperature is 85°C (185°F).
The motor, I'm assuming, would be fairly large so you would need a beefy motor driver that uses a 5 volt logic level, maybe like this one: L298 Dual H-Bridge Motor Driver.
This is a fairly difficult project, I'd say mostly because of the difficulty you would have mounting the barometer and motor. Never the less, it still is possible.

I don't think the question is asking about replacing the sensor with something generic, but rather reading the sensor already present (or an additional similar one).  Generally, parts actually used on cars are a lot cheaper than generic functional equivalents, due to economies of scale in both manufacturing and distribution.

oh, The question was kind of vague.

Also using that adafruit sensor above would be a bad idea.  It was not designed to withstand the conditions around exhaust.  plus the dirt and oil.

You might want to look at https://github.com/designer2k2/multidisplay they're doing exhaust gas pressure monitoring and a number of other things.

Although this answers the question, it will be useless if the link breaks. For that reason please edit your answer with a summary of key points so that the question is answered on this site. Users can then go to the link for more detailed information. Please edit your answer.


text:
SerialGSM for GSM shield without SoftwareSerial
SerialGSM is a library for simplifying GSM shields.
This is sample code for sending SMS:
#include <SerialGSM.h>
#include <SoftwareSerial.h>
SerialGSM cell(2,3);
void setup(){
 Serial.begin(9600);
 cell.begin(9600);
  cell.Verbose(true);
  cell.Boot();
  cell.FwdSMS2Serial();
  cell.Rcpt("+972123456789");
  cell.Message("hello world");
  cell.SendSMS();
}

void loop(){
  if (cell.ReceiveSMS()){
    Serial.println(cell.Message());
    cell.DeleteAllSMS();
  }

}

As you can see, he uses software serial.
I intend to use this for my school thesis, but I am using a shield, so I won't be using Software Serial.
What bothers me is this line
SerialGSM cell(2,3);

In my case, do I declare it like this?:
SerialGSM cell(0,1);

Or will there be conflicts with serial?
EDIT: In other words, how do I declare the SeralGSM object using hardware serial and not software serial?

SerialGSM is designed to work with software serial, as you can see that from the class declaration in the SerialGSM.h header:
class SerialGSM : public SoftwareSerial {
...
};

Unfortunately, changing it to use hardware serial is more complicated than it looks. There are two potential ways you could go about it:

Derive from HardwareSerial instead of SoftwareSerial. This would give you flexibility, but you'd have to take care of passing all the right data to the HardwareSerial constructor, which is quite messy.
Don't derive from anything. Use the global Serial object, and manually replace all serial function calls with their Serial.xxx() equivalents. This is probably easier, but it restricts you to a specific serial port.

Both approaches involve quite a lot of coding, so they aren't trivial tasks. It's also important to note that SerialGSM currently uses the global Serial object to output debug information. You'd have to remove or modify that before converting to hardware serial, or else it could interfere.

Thanks a lot! Ok, if that is the case, i can use it in Software Serial mode. Now, i have a gps unit that i want to use as well. That means, plug in the shield and use the SerailGSM library, and also plug in the gps on ports 0 (and 1 if i want the gps to receive data), and use Serial.begin(4800); to start the serial receiving stuff?

That should work, although bear in mind that SerialGSM outputs debug info to hardware serial. That means if you connect the hardware TX to your GPS, then it will probably go wrong.

OK, another approach then would be to use arduinos ready example of sending sms. the thing is i have this shield https://www.sparkfun.com/products/9607,  with the SM5100B chipset. Do you know if the arduinos example of SMS sending will work with this shield?

I've never used that shield, so I'm afraid I don't know. It looks SparkFun have their own sample code for it though: https://github.com/sparkfun/SM5100B_Cellular_Shield/blob/master/Firmware/Cellular_Shield_Passthrough_b/Cellular_Shield_Passthrough/Cellular_Shield_Passthrough.pde

Never mind, i went with the GSM SMS example from arduino 1.0.5 (Don't know the version of arduino IDE that included this) and works fine.
If you are considering using the SerialGSM library there is no need to!
CAUTION: In the Arduino's library, when you declare the phone number, you have to use international format
(Thanks bloomfield for the info you provided in the previous answer)


text:
Using SoftwareSerial for the serial monitor
Most programs follow this route: They have a Serial.begin() for the serial connection between PC and Arduino (the serial monitor) and they use SoftwareSerial for a device.
Can you go the other way around? Can you use SoftwareSerial for the communication between PC and Arduino, and Serial for a device?

Short answer: no.
Pins 0 and 1 an an Uno are directly wired to the PC communication chip. You could make a board that was wired differently and connected SoftwareSerial to the PC, but you would have to switch it back to pins 0 and 1 when uploading to the arduino somehow.
On an arduino leonardo "Serial" for communicating with PC over USB is different from "Serial1", which is connected to pins 0 and 1 on the board. You can use both simultaneously, so if you really need to use hardware serial and PC comms at the same time, I recommend you buy a leonardo.

But of course, you can omit the communication with the pc and have the hardware serial dedicated for communication with a device correct? And use the softwareserial for communicatoin with another device.

Yes that is correct, If you don't communicate with the PC hardware serial can be used for anything you please, and at the same time as Software Serial.

Yes you can. If you use a USB FTDI type cable to connect your computer to the SoftwareSerial pins, you can use a terminal emulator program (HyperTerm, putty, etc) to communicate with the Arduino.


text:
Arduino Uno R1 I soldered resistor but I cannot DFU program atmega8u2
I have an Arduino R1 board (the very first one) and I managed to solder the resistor into Arduino's Atmega8u2 (I went to a specialist in order to do that). Then I reset atmega8u2 and by wiring the pins mentioned in: https://www.arduino.cc/en/Hacking/DFUProgramming8U2
I can confirm it via this message over my GNU/Linux machine by running dmesg:
[ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
[ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
[ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 1544.808356] usb 1-6: Product: Arduino Uno DFU

I also to confirm that I run lsusb and I got the following result:
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 248a:8367
Bus 001 Device 058: ID 03eb:2ff7 Atmel Corp.
Bus 001 Device 003: ID 058f:6362 Alcor Micro Corp. Flash Card Reader/Writer
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Further indicating to me that arduino is in DFU mode over my ubuntu 16.04 machine. Also I further verify via dfu-util -l command:
Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

Found DFU: [03eb:2ff7] ver=0000, devnum=63, cfg=1, intf=0, alt=0, name="UNKNOWN", serial="UNKNOWN"

The I try to run:
sudo dfu-programmer atmega8u2 erase
But for some reason I get the following error:
dfu-programmer: no device present.
Do you know why I get this error and how I can fix it?
Edit 1
I installed the latest version of dfu-programmer and compiled from source via https://sourceforge.net/projects/dfu-programmer/files/dfu-programmer/0.7.2/ but still I get the error. I also tried to compile it with libusb-1.0.0
Edit2
I also tried this version with libusb-1.0.0 but still the same error occurs.
Edit 3
As many suggest I tried to do multiple times but still I get this error.
Edit 4
I also used dfu-util and I try to insert the data into the atmega8u2 via:
 sudo dfu-util -d 03eb:2ff7 -D ./Arduino-usbserial-uno.hex -R

But I get the error:
dfu-util 0.8

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

dfu-util: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
Opening DFU capable USB device...
ID 03eb:2ff7
Run-time device DFU version 0100
Claiming USB DFU Interface...
Setting Alternate Setting #0 ...
Determining device status: state = dfuIDLE, status = 0
dfuIDLE, continuing
DFU mode device DFU version 0100
Device returned transfer size 3072
Copying data from PC to DFU device
Download    [                         ]   0%            0 bytesdfu-util: Error during download
dfu-util: can't detach
Resetting USB to switch back to runtime mode

According to https://gebloggendings.wordpress.com/category/elektronik/arduino/ it is sometimes not to assume that the atmega8u2 is always the correct value in my case was the at90usb82 resulting into using the following command sequence:
sudo dfu-programmer at90usb82 erase
# Flashing the arduino provided .hex
sudo dfu-programmer at90usb82 /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/Arduino-usbserial-uno.hex
# reset the board
sudo dfu-programmer at90usb82 reset

Further information you can find into:

https://forum.arduino.cc/index.php?topic=53443.0
https://forum.arduino.cc/index.php?topic=542854.0


text:
6 wire 3 digits 7 segment display and arduino question
Here's a brain teaser for you:
I have the following 3 digit 7 segment display that has only 6 wires

Experimentally I found out how it works, even though I don't understand it, but anyways every segment is lit by a combination of HIGH and LOW of certain two pins, the combinations are below:

So I tried to make it work, but encountered the following problem (as you can see in the first picture): if, for example, I want to activate the segment that requires pin 5 high and pin 6 low, it also activates the other segments that require 5 to high, because apparently if a digital output is not high, it's automatically pulled to ground, and that's a problem.
I tried by setting the other pins I don't use in a segment to high, but then the segments that require 6 low are being activated, so that didn't work.
Other option I have would be transistors or a tri-state buffer, but for that I need all 12 digital inputs of arduino for the two states of each pin of the display.
Hope you understand what my problem is and maybe you have some advice on how to solve it.
Thanks in advance!
Edit: I managed to drive every segment individually using a small delay, and it works if the sketch has only the code for the display, but as soon as I add more code (for the temperature sensor I want to use) it starts to malfunction. You can find the code below.
LE: I managed to make it work by leaving only the display function in the loop and calling every 5 seconds the function for the temperature sensor. It still refreshes the display when it is called, but that doesn't bother me.
Here's the code: http://www.mediafire.com/file/2bs5r8u5rkzpu8g/6w_3D_7S_display.rar

You can emulate tri-state by setting a pin to INPUT.  That gives you your three states that you need: OUTPUT & HIGH, OUTPUT & LOW, and INPUT.

Sometimes the simplest solution is the best solution, thanks Majenko!

The link to your code is not working.

I changed the upload site, try now.

Still not working. I can download the file but it's corrupted. Try and upload a .ino or .txt file.

It’s a hassle because I split the code into tabs and would mean to upload everything individually. Anyways, I solved the issue.

What you have is a Charlie-Plexed display like the one in the picture below.  You need one more wire than this example because your display also includes the decimal point.  If you go through the electrical paths where for each pair one line is driven high, the other is driven low and all other lines are set to input, only one LED at a time will be forward biased.

Yes, that’s exactly how i did it, glad to find out how it works, thanks !